blob: 3d70e3a2800827e4c9abbbb94ec220bc29511052 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Christian Heimesc94e2b52008-01-14 04:13:37 +000013
Jack Janseneddc1442003-11-20 01:44:59 +000014#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000015extern double fmod(double, double);
16extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000017#endif
18
Neal Norwitz5f95a792008-01-25 08:04:16 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000026#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000027#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
30 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
32};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
42 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000043 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000047 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 q = p + N_FLOATOBJECTS;
51 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000052 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 return p + N_FLOATOBJECTS - 1;
55}
56
Christian Heimesdfdfaab2007-12-01 11:20:10 +000057double
58PyFloat_GetMax(void)
59{
60 return DBL_MAX;
61}
62
63double
64PyFloat_GetMin(void)
65{
66 return DBL_MIN;
67}
68
Christian Heimesc94e2b52008-01-14 04:13:37 +000069static PyTypeObject FloatInfoType = {0};
70
71PyDoc_STRVAR(floatinfo__doc__,
72"sys.floatinfo\n\
73\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
79 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
96};
97
98static PyStructSequence_Desc floatinfo_desc = {
99 "sys.floatinfo", /* name */
100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
103};
104
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Christian Heimesc94e2b52008-01-14 04:13:37 +0000108 static PyObject* floatinfo;
109 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000110
Christian Heimesc94e2b52008-01-14 04:13:37 +0000111 if (floatinfo != NULL) {
112 Py_INCREF(floatinfo);
113 return floatinfo;
114 }
115 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
116
117 floatinfo = PyStructSequence_New(&FloatInfoType);
118 if (floatinfo == NULL) {
119 return NULL;
120 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000121
Christian Heimesc94e2b52008-01-14 04:13:37 +0000122#define SetIntFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
124#define SetDblFlag(flag) \
125 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000126
Christian Heimesc94e2b52008-01-14 04:13:37 +0000127 SetDblFlag(DBL_MAX);
128 SetIntFlag(DBL_MAX_EXP);
129 SetIntFlag(DBL_MAX_10_EXP);
130 SetDblFlag(DBL_MIN);
131 SetIntFlag(DBL_MIN_EXP);
132 SetIntFlag(DBL_MIN_10_EXP);
133 SetIntFlag(DBL_DIG);
134 SetIntFlag(DBL_MANT_DIG);
135 SetDblFlag(DBL_EPSILON);
136 SetIntFlag(FLT_RADIX);
137 SetIntFlag(FLT_ROUNDS);
138#undef SetIntFlag
139#undef SetDblFlag
140
141 if (PyErr_Occurred()) {
142 Py_CLEAR(floatinfo);
143 return NULL;
144 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000145
Christian Heimesc94e2b52008-01-14 04:13:37 +0000146 Py_INCREF(floatinfo);
147 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000148}
149
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000153 register PyFloatObject *op;
154 if (free_list == NULL) {
155 if ((free_list = fill_free_list()) == NULL)
156 return NULL;
157 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000158 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000159 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000160 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000161 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000162 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Petersef14d732000-09-23 03:39:17 +0000166/**************************************************************************
167RED_FLAG 22-Sep-2000 tim
168PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
169
1701. If v was a regular string, *pend was set to point to its terminating
171 null byte. That's useless (the caller can find that without any
172 help from this function!).
173
1742. If v was a Unicode string, or an object convertible to a character
175 buffer, *pend was set to point into stack trash (the auto temp
176 vector holding the character buffer). That was downright dangerous.
177
178Since we can't change the interface of a public API function, pend is
179still supported but now *officially* useless: if pend is not NULL,
180*pend is set to NULL.
181**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000183PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000185 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000186 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000187 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000188#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000189 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000190#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000191 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192
Tim Petersef14d732000-09-23 03:39:17 +0000193 if (pend)
194 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000195 if (PyString_Check(v)) {
196 s = PyString_AS_STRING(v);
197 len = PyString_GET_SIZE(v);
198 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000199#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000200 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000201 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000203 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 return NULL;
205 }
Tim Petersef14d732000-09-23 03:39:17 +0000206 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000207 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000208 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000209 NULL))
210 return NULL;
211 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000212 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000213 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000214#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000215 else if (PyObject_AsCharBuffer(v, &s, &len)) {
216 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000217 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000219 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000220
Guido van Rossum4c08d552000-03-10 22:55:18 +0000221 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000222 while (*s && isspace(Py_CHARMASK(*s)))
223 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000224 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000225 PyErr_SetString(PyExc_ValueError, "empty string for float()");
226 return NULL;
227 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000228 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000229 /* We don't care about overflow or underflow. If the platform supports
230 * them, infinities and signed zeroes (on underflow) are fine.
231 * However, strtod can return 0 for denormalized numbers, where atof
232 * does not. So (alas!) we special-case a zero result. Note that
233 * whether strtod sets errno on underflow is not defined, so we can't
234 * key off errno.
235 */
Tim Peters858346e2000-09-25 21:01:28 +0000236 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000237 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000238 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000239 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000240 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000241 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000242 if (end > last)
243 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000244 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000245 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000246 char *p = (char*)sp;
247 int sign = 1;
248
249 if (*p == '-') {
250 sign = -1;
251 p++;
252 }
253 if (*p == '+') {
254 p++;
255 }
256 if (PyOS_strnicmp(p, "inf", 4) == 0) {
257 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
258 }
259#ifdef Py_NAN
260 if(PyOS_strnicmp(p, "nan", 4) == 0) {
261 return PyFloat_FromDouble(Py_NAN);
262 }
263#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000264 PyOS_snprintf(buffer, sizeof(buffer),
265 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000266 PyErr_SetString(PyExc_ValueError, buffer);
267 return NULL;
268 }
269 /* Since end != s, the platform made *some* kind of sense out
270 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000271 while (*end && isspace(Py_CHARMASK(*end)))
272 end++;
273 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000274 PyOS_snprintf(buffer, sizeof(buffer),
275 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000276 PyErr_SetString(PyExc_ValueError, buffer);
277 return NULL;
278 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000279 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000280 PyErr_SetString(PyExc_ValueError,
281 "null byte in argument for float()");
282 return NULL;
283 }
Tim Petersef14d732000-09-23 03:39:17 +0000284 if (x == 0.0) {
285 /* See above -- may have been strtod being anal
286 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000287 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000288 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000289 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000290 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000291 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000292 return PyFloat_FromDouble(x);
293}
294
Guido van Rossum234f9421993-06-17 12:35:49 +0000295static void
Fred Drakefd99de62000-07-09 05:02:18 +0000296float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000297{
Guido van Rossum9475a232001-10-05 20:51:39 +0000298 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000299 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000300 free_list = op;
301 }
302 else
Christian Heimese93237d2007-12-19 02:37:44 +0000303 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000304}
305
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306double
Fred Drakefd99de62000-07-09 05:02:18 +0000307PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 PyNumberMethods *nb;
310 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313 if (op && PyFloat_Check(op))
314 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000315
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000316 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000317 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318 return -1;
319 }
Tim Petersd2364e82001-11-01 20:09:42 +0000320
Christian Heimese93237d2007-12-19 02:37:44 +0000321 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000322 PyErr_SetString(PyExc_TypeError, "a float is required");
323 return -1;
324 }
325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000327 if (fo == NULL)
328 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 if (!PyFloat_Check(fo)) {
330 PyErr_SetString(PyExc_TypeError,
331 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000332 return -1;
333 }
Tim Petersd2364e82001-11-01 20:09:42 +0000334
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 val = PyFloat_AS_DOUBLE(fo);
336 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000337
Guido van Rossumb6775db1994-08-01 11:34:53 +0000338 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339}
340
341/* Methods */
342
Tim Peters97019e42001-11-28 22:43:45 +0000343static void
344format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
346 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000347 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000348 int i;
349
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350 /* Subroutine for float_repr and float_print.
351 We want float numbers to be recognizable as such,
352 i.e., they should contain a decimal point or an exponent.
353 However, %g may print the number as an integer;
354 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000355
356 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000357 PyOS_snprintf(format, 32, "%%.%ig", precision);
358 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359 cp = buf;
360 if (*cp == '-')
361 cp++;
362 for (; *cp != '\0'; cp++) {
363 /* Any non-digit means it's not an integer;
364 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000365 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 break;
367 }
368 if (*cp == '\0') {
369 *cp++ = '.';
370 *cp++ = '0';
371 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000372 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000374 /* Checking the next three chars should be more than enough to
375 * detect inf or nan, even on Windows. We check for inf or nan
376 * at last because they are rare cases.
377 */
378 for (i=0; *cp != '\0' && i<3; cp++, i++) {
379 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
380 continue;
381 /* found something that is neither a digit nor point
382 * it might be a NaN or INF
383 */
384#ifdef Py_NAN
385 if (Py_IS_NAN(v->ob_fval)) {
386 strcpy(buf, "nan");
387 }
388 else
389#endif
390 if (Py_IS_INFINITY(v->ob_fval)) {
391 cp = buf;
392 if (*cp == '-')
393 cp++;
394 strcpy(cp, "inf");
395 }
396 break;
397 }
398
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Tim Peters97019e42001-11-28 22:43:45 +0000401/* XXX PyFloat_AsStringEx should not be a public API function (for one
402 XXX thing, its signature passes a buffer without a length; for another,
403 XXX it isn't useful outside this file).
404*/
405void
406PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
407{
408 format_float(buf, 100, v, precision);
409}
410
Christian Heimesf15c66e2007-12-11 00:54:34 +0000411#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000412/* The following function is based on Tcl_PrintDouble,
413 * from tclUtil.c.
414 */
415
416#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
417#define is_nan(d) ((d) != (d))
418
419static void
420format_double_repr(char *dst, double value)
421{
422 char *p, c;
423 int exp;
424 int signum;
425 char buffer[30];
426
427 /*
428 * Handle NaN.
429 */
430
431 if (is_nan(value)) {
432 strcpy(dst, "nan");
433 return;
434 }
435
436 /*
437 * Handle infinities.
438 */
439
440 if (is_infinite(value)) {
441 if (value < 0) {
442 strcpy(dst, "-inf");
443 } else {
444 strcpy(dst, "inf");
445 }
446 return;
447 }
448
449 /*
450 * Ordinary (normal and denormal) values.
451 */
452
453 exp = _PyFloat_Digits(buffer, value, &signum)+1;
454 if (signum) {
455 *dst++ = '-';
456 }
457 p = buffer;
458 if (exp < -3 || exp > 17) {
459 /*
460 * E format for numbers < 1e-3 or >= 1e17.
461 */
462
463 *dst++ = *p++;
464 c = *p;
465 if (c != '\0') {
466 *dst++ = '.';
467 while (c != '\0') {
468 *dst++ = c;
469 c = *++p;
470 }
471 }
472 sprintf(dst, "e%+d", exp-1);
473 } else {
474 /*
475 * F format for others.
476 */
477
478 if (exp <= 0) {
479 *dst++ = '0';
480 }
481 c = *p;
482 while (exp-- > 0) {
483 if (c != '\0') {
484 *dst++ = c;
485 c = *++p;
486 } else {
487 *dst++ = '0';
488 }
489 }
490 *dst++ = '.';
491 if (c == '\0') {
492 *dst++ = '0';
493 } else {
494 while (++exp < 0) {
495 *dst++ = '0';
496 }
497 while (c != '\0') {
498 *dst++ = c;
499 c = *++p;
500 }
501 }
502 *dst++ = '\0';
503 }
504}
505
506static void
507format_float_repr(char *buf, PyFloatObject *v)
508{
509 assert(PyFloat_Check(v));
510 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
511}
512
Christian Heimesf15c66e2007-12-11 00:54:34 +0000513#endif /* Py_BROKEN_REPR */
514
Neil Schemenauer32117e52001-01-04 01:44:34 +0000515/* Macro and helper that convert PyObject obj to a C double and store
516 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000517 slot function. If conversion to double raises an exception, obj is
518 set to NULL, and the function invoking this macro returns NULL. If
519 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
520 stored in obj, and returned from the function invoking this macro.
521*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000522#define CONVERT_TO_DOUBLE(obj, dbl) \
523 if (PyFloat_Check(obj)) \
524 dbl = PyFloat_AS_DOUBLE(obj); \
525 else if (convert_to_double(&(obj), &(dbl)) < 0) \
526 return obj;
527
528static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000529convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000530{
531 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000532
Neil Schemenauer32117e52001-01-04 01:44:34 +0000533 if (PyInt_Check(obj)) {
534 *dbl = (double)PyInt_AS_LONG(obj);
535 }
536 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000538 if (*dbl == -1.0 && PyErr_Occurred()) {
539 *v = NULL;
540 return -1;
541 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000542 }
543 else {
544 Py_INCREF(Py_NotImplemented);
545 *v = Py_NotImplemented;
546 return -1;
547 }
548 return 0;
549}
550
Guido van Rossum57072eb1999-12-23 19:00:28 +0000551/* Precisions used by repr() and str(), respectively.
552
553 The repr() precision (17 significant decimal digits) is the minimal number
554 that is guaranteed to have enough precision so that if the number is read
555 back in the exact same binary value is recreated. This is true for IEEE
556 floating point by design, and also happens to work for all other modern
557 hardware.
558
559 The str() precision is chosen so that in most cases, the rounding noise
560 created by various operations is suppressed, while giving plenty of
561 precision for practical use.
562
563*/
564
565#define PREC_REPR 17
566#define PREC_STR 12
567
Tim Peters97019e42001-11-28 22:43:45 +0000568/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
569 XXX they pass a char buffer without passing a length.
570*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000571void
Fred Drakefd99de62000-07-09 05:02:18 +0000572PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000573{
Tim Peters97019e42001-11-28 22:43:45 +0000574 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000575}
576
Tim Peters72f98e92001-05-08 15:19:57 +0000577void
578PyFloat_AsReprString(char *buf, PyFloatObject *v)
579{
Tim Peters97019e42001-11-28 22:43:45 +0000580 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000581}
582
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000583/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000584static int
Fred Drakefd99de62000-07-09 05:02:18 +0000585float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586{
587 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000588 format_float(buf, sizeof(buf), v,
589 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000590 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000592 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000593 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594}
595
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000597float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000599#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000600 char buf[30];
601 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000602#else
603 char buf[100];
604 format_float(buf, sizeof(buf), v, PREC_REPR);
605#endif
606
Guido van Rossum57072eb1999-12-23 19:00:28 +0000607 return PyString_FromString(buf);
608}
609
610static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000611float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000612{
613 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000614 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616}
617
Tim Peters307fa782004-09-23 08:06:40 +0000618/* Comparison is pretty much a nightmare. When comparing float to float,
619 * we do it as straightforwardly (and long-windedly) as conceivable, so
620 * that, e.g., Python x == y delivers the same result as the platform
621 * C x == y when x and/or y is a NaN.
622 * When mixing float with an integer type, there's no good *uniform* approach.
623 * Converting the double to an integer obviously doesn't work, since we
624 * may lose info from fractional bits. Converting the integer to a double
625 * also has two failure modes: (1) a long int may trigger overflow (too
626 * large to fit in the dynamic range of a C double); (2) even a C long may have
627 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
628 * 63 bits of precision, but a C double probably has only 53), and then
629 * we can falsely claim equality when low-order integer bits are lost by
630 * coercion to double. So this part is painful too.
631 */
632
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633static PyObject*
634float_richcompare(PyObject *v, PyObject *w, int op)
635{
636 double i, j;
637 int r = 0;
638
Tim Peters307fa782004-09-23 08:06:40 +0000639 assert(PyFloat_Check(v));
640 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000641
Tim Peters307fa782004-09-23 08:06:40 +0000642 /* Switch on the type of w. Set i and j to doubles to be compared,
643 * and op to the richcomp to use.
644 */
645 if (PyFloat_Check(w))
646 j = PyFloat_AS_DOUBLE(w);
647
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000648 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000649 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000650 /* If i is an infinity, its magnitude exceeds any
651 * finite integer, so it doesn't matter which int we
652 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000653 */
654 j = 0.0;
655 else
656 goto Unimplemented;
657 }
658
659 else if (PyInt_Check(w)) {
660 long jj = PyInt_AS_LONG(w);
661 /* In the worst realistic case I can imagine, C double is a
662 * Cray single with 48 bits of precision, and long has 64
663 * bits.
664 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000665#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000666 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
667 if (abs >> 48) {
668 /* Needs more than 48 bits. Make it take the
669 * PyLong path.
670 */
671 PyObject *result;
672 PyObject *ww = PyLong_FromLong(jj);
673
674 if (ww == NULL)
675 return NULL;
676 result = float_richcompare(v, ww, op);
677 Py_DECREF(ww);
678 return result;
679 }
680#endif
681 j = (double)jj;
682 assert((long)j == jj);
683 }
684
685 else if (PyLong_Check(w)) {
686 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
687 int wsign = _PyLong_Sign(w);
688 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000689 int exponent;
690
691 if (vsign != wsign) {
692 /* Magnitudes are irrelevant -- the signs alone
693 * determine the outcome.
694 */
695 i = (double)vsign;
696 j = (double)wsign;
697 goto Compare;
698 }
699 /* The signs are the same. */
700 /* Convert w to a double if it fits. In particular, 0 fits. */
701 nbits = _PyLong_NumBits(w);
702 if (nbits == (size_t)-1 && PyErr_Occurred()) {
703 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000704 * to hold the # of bits. Replace with little doubles
705 * that give the same outcome -- w is so large that
706 * its magnitude must exceed the magnitude of any
707 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000708 */
709 PyErr_Clear();
710 i = (double)vsign;
711 assert(wsign != 0);
712 j = wsign * 2.0;
713 goto Compare;
714 }
715 if (nbits <= 48) {
716 j = PyLong_AsDouble(w);
717 /* It's impossible that <= 48 bits overflowed. */
718 assert(j != -1.0 || ! PyErr_Occurred());
719 goto Compare;
720 }
721 assert(wsign != 0); /* else nbits was 0 */
722 assert(vsign != 0); /* if vsign were 0, then since wsign is
723 * not 0, we would have taken the
724 * vsign != wsign branch at the start */
725 /* We want to work with non-negative numbers. */
726 if (vsign < 0) {
727 /* "Multiply both sides" by -1; this also swaps the
728 * comparator.
729 */
730 i = -i;
731 op = _Py_SwappedOp[op];
732 }
733 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000734 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000735 /* exponent is the # of bits in v before the radix point;
736 * we know that nbits (the # of bits in w) > 48 at this point
737 */
738 if (exponent < 0 || (size_t)exponent < nbits) {
739 i = 1.0;
740 j = 2.0;
741 goto Compare;
742 }
743 if ((size_t)exponent > nbits) {
744 i = 2.0;
745 j = 1.0;
746 goto Compare;
747 }
748 /* v and w have the same number of bits before the radix
749 * point. Construct two longs that have the same comparison
750 * outcome.
751 */
752 {
753 double fracpart;
754 double intpart;
755 PyObject *result = NULL;
756 PyObject *one = NULL;
757 PyObject *vv = NULL;
758 PyObject *ww = w;
759
760 if (wsign < 0) {
761 ww = PyNumber_Negative(w);
762 if (ww == NULL)
763 goto Error;
764 }
765 else
766 Py_INCREF(ww);
767
768 fracpart = modf(i, &intpart);
769 vv = PyLong_FromDouble(intpart);
770 if (vv == NULL)
771 goto Error;
772
773 if (fracpart != 0.0) {
774 /* Shift left, and or a 1 bit into vv
775 * to represent the lost fraction.
776 */
777 PyObject *temp;
778
779 one = PyInt_FromLong(1);
780 if (one == NULL)
781 goto Error;
782
783 temp = PyNumber_Lshift(ww, one);
784 if (temp == NULL)
785 goto Error;
786 Py_DECREF(ww);
787 ww = temp;
788
789 temp = PyNumber_Lshift(vv, one);
790 if (temp == NULL)
791 goto Error;
792 Py_DECREF(vv);
793 vv = temp;
794
795 temp = PyNumber_Or(vv, one);
796 if (temp == NULL)
797 goto Error;
798 Py_DECREF(vv);
799 vv = temp;
800 }
801
802 r = PyObject_RichCompareBool(vv, ww, op);
803 if (r < 0)
804 goto Error;
805 result = PyBool_FromLong(r);
806 Error:
807 Py_XDECREF(vv);
808 Py_XDECREF(ww);
809 Py_XDECREF(one);
810 return result;
811 }
812 } /* else if (PyLong_Check(w)) */
813
814 else /* w isn't float, int, or long */
815 goto Unimplemented;
816
817 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000818 PyFPE_START_PROTECT("richcompare", return NULL)
819 switch (op) {
820 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000821 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000822 break;
823 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000824 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000825 break;
826 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000827 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000828 break;
829 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000830 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000831 break;
832 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000833 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000834 break;
835 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000836 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000837 break;
838 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000839 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000840 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000841
842 Unimplemented:
843 Py_INCREF(Py_NotImplemented);
844 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000845}
846
Guido van Rossum9bfef441993-03-29 10:43:31 +0000847static long
Fred Drakefd99de62000-07-09 05:02:18 +0000848float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000849{
Tim Peters39dce292000-08-15 03:34:48 +0000850 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000851}
852
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000853static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000854float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000855{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000856 double a,b;
857 CONVERT_TO_DOUBLE(v, a);
858 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000859 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000860 a = a + b;
861 PyFPE_END_PROTECT(a)
862 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000863}
864
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000865static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000866float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000867{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000868 double a,b;
869 CONVERT_TO_DOUBLE(v, a);
870 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000871 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000872 a = a - b;
873 PyFPE_END_PROTECT(a)
874 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875}
876
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000878float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000880 double a,b;
881 CONVERT_TO_DOUBLE(v, a);
882 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000883 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000884 a = a * b;
885 PyFPE_END_PROTECT(a)
886 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000887}
888
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000890float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000891{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000892 double a,b;
893 CONVERT_TO_DOUBLE(v, a);
894 CONVERT_TO_DOUBLE(w, b);
895 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000896 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000897 return NULL;
898 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000899 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000900 a = a / b;
901 PyFPE_END_PROTECT(a)
902 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000903}
904
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000905static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000906float_classic_div(PyObject *v, PyObject *w)
907{
908 double a,b;
909 CONVERT_TO_DOUBLE(v, a);
910 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000911 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000912 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
913 return NULL;
914 if (b == 0.0) {
915 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
916 return NULL;
917 }
918 PyFPE_START_PROTECT("divide", return 0)
919 a = a / b;
920 PyFPE_END_PROTECT(a)
921 return PyFloat_FromDouble(a);
922}
923
924static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000925float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000926{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000927 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000928 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000929 CONVERT_TO_DOUBLE(v, vx);
930 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000931 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000933 return NULL;
934 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000935 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000936 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000937 /* note: checking mod*wx < 0 is incorrect -- underflows to
938 0 if wx < sqrt(smallest nonzero double) */
939 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000940 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000941 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000942 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000944}
945
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000947float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000948{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000949 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000950 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000951 CONVERT_TO_DOUBLE(v, vx);
952 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000953 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000955 return NULL;
956 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000957 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000958 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000959 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000960 exact multiple of wx. But this is fp arithmetic, and fp
961 vx - mod is an approximation; the result is that div may
962 not be an exact integral value after the division, although
963 it will always be very close to one.
964 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000965 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000966 if (mod) {
967 /* ensure the remainder has the same sign as the denominator */
968 if ((wx < 0) != (mod < 0)) {
969 mod += wx;
970 div -= 1.0;
971 }
972 }
973 else {
974 /* the remainder is zero, and in the presence of signed zeroes
975 fmod returns different results across platforms; ensure
976 it has the same sign as the denominator; we'd like to do
977 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000978 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000979 if (wx < 0.0)
980 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000981 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000982 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000983 if (div) {
984 floordiv = floor(div);
985 if (div - floordiv > 0.5)
986 floordiv += 1.0;
987 }
988 else {
989 /* div is zero - get the same sign as the true quotient */
990 div *= div; /* hide "div = +0" from optimizers */
991 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
992 }
993 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000994 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000995}
996
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000998float_floor_div(PyObject *v, PyObject *w)
999{
1000 PyObject *t, *r;
1001
1002 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +00001003 if (t == NULL || t == Py_NotImplemented)
1004 return t;
1005 assert(PyTuple_CheckExact(t));
1006 r = PyTuple_GET_ITEM(t, 0);
1007 Py_INCREF(r);
1008 Py_DECREF(t);
1009 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001010}
1011
1012static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001013float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001014{
1015 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001016
1017 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001018 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001019 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001020 return NULL;
1021 }
1022
Neil Schemenauer32117e52001-01-04 01:44:34 +00001023 CONVERT_TO_DOUBLE(v, iv);
1024 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001025
1026 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001027 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001028 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001029 }
Tim Peters96685bf2001-08-23 22:31:37 +00001030 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001031 if (iw < 0.0) {
1032 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001033 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001034 return NULL;
1035 }
1036 return PyFloat_FromDouble(0.0);
1037 }
Tim Peterse87568d2003-05-24 20:18:24 +00001038 if (iv < 0.0) {
1039 /* Whether this is an error is a mess, and bumps into libm
1040 * bugs so we have to figure it out ourselves.
1041 */
1042 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001043 PyErr_SetString(PyExc_ValueError, "negative number "
1044 "cannot be raised to a fractional power");
1045 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001046 }
1047 /* iw is an exact integer, albeit perhaps a very large one.
1048 * -1 raised to an exact integer should never be exceptional.
1049 * Alas, some libms (chiefly glibc as of early 2003) return
1050 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1051 * happen to be representable in a *C* integer. That's a
1052 * bug; we let that slide in math.pow() (which currently
1053 * reflects all platform accidents), but not for Python's **.
1054 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001055 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001056 /* Return 1 if iw is even, -1 if iw is odd; there's
1057 * no guarantee that any C integral type is big
1058 * enough to hold iw, so we have to check this
1059 * indirectly.
1060 */
1061 ix = floor(iw * 0.5) * 2.0;
1062 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1063 }
1064 /* Else iv != -1.0, and overflow or underflow are possible.
1065 * Unless we're to write pow() ourselves, we have to trust
1066 * the platform to do this correctly.
1067 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001068 }
Tim Peters96685bf2001-08-23 22:31:37 +00001069 errno = 0;
1070 PyFPE_START_PROTECT("pow", return NULL)
1071 ix = pow(iv, iw);
1072 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001073 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001074 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001075 /* We don't expect any errno value other than ERANGE, but
1076 * the range of libm bugs appears unbounded.
1077 */
Alex Martelli348dc882006-08-23 22:17:59 +00001078 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1079 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001080 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001081 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001082 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001083}
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001086float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001087{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001088 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001089}
1090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001091static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001092float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001093{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001094 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001095}
1096
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001097static int
Fred Drakefd99de62000-07-09 05:02:18 +00001098float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001099{
1100 return v->ob_fval != 0.0;
1101}
1102
Guido van Rossum234f9421993-06-17 12:35:49 +00001103static int
Fred Drakefd99de62000-07-09 05:02:18 +00001104float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001105{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001106 if (PyInt_Check(*pw)) {
1107 long x = PyInt_AsLong(*pw);
1108 *pw = PyFloat_FromDouble((double)x);
1109 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001110 return 0;
1111 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001113 double x = PyLong_AsDouble(*pw);
1114 if (x == -1.0 && PyErr_Occurred())
1115 return -1;
1116 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001117 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001118 return 0;
1119 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001120 else if (PyFloat_Check(*pw)) {
1121 Py_INCREF(*pv);
1122 Py_INCREF(*pw);
1123 return 0;
1124 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001125 return 1; /* Can't do it */
1126}
1127
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001128static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001129float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001130{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001132 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001133
1134 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001135 /* Try to get out cheap if this fits in a Python int. The attempt
1136 * to cast to long must be protected, as C doesn't define what
1137 * happens if the double is too big to fit in a long. Some rare
1138 * systems raise an exception then (RISCOS was mentioned as one,
1139 * and someone using a non-default option on Sun also bumped into
1140 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1141 * still be vulnerable: if a long has more bits of precision than
1142 * a double, casting MIN/MAX to double may yield an approximation,
1143 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1144 * yield true from the C expression wholepart<=LONG_MAX, despite
1145 * that wholepart is actually greater than LONG_MAX.
1146 */
1147 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1148 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001149 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001150 }
1151 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001152}
1153
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001154static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001155float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001156{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001157 if (PyFloat_CheckExact(v))
1158 Py_INCREF(v);
1159 else
1160 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001161 return v;
1162}
1163
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001164static PyObject *
1165float_as_integer_ratio(PyObject *v)
1166{
1167 double self;
1168 double float_part;
1169 int exponent;
1170 int is_negative;
1171 const int chunk_size = 28;
1172 PyObject *prev;
1173 PyObject *py_chunk = NULL;
1174 PyObject *py_exponent = NULL;
1175 PyObject *numerator = NULL;
1176 PyObject *denominator = NULL;
1177 PyObject *result_pair = NULL;
1178 PyNumberMethods *long_methods;
1179
1180#define INPLACE_UPDATE(obj, call) \
1181 prev = obj; \
1182 obj = call; \
1183 Py_DECREF(prev); \
1184
1185 CONVERT_TO_DOUBLE(v, self);
1186
1187 if (Py_IS_INFINITY(self)) {
1188 PyErr_SetString(PyExc_OverflowError,
1189 "Cannot pass infinity to float.as_integer_ratio.");
1190 return NULL;
1191 }
1192#ifdef Py_NAN
1193 if (Py_IS_NAN(self)) {
1194 PyErr_SetString(PyExc_ValueError,
1195 "Cannot pass nan to float.as_integer_ratio.");
1196 return NULL;
1197 }
1198#endif
1199
1200 if (self == 0) {
1201 numerator = PyInt_FromLong(0);
1202 if (numerator == NULL) goto error;
1203 denominator = PyInt_FromLong(1);
1204 if (denominator == NULL) goto error;
1205 result_pair = PyTuple_Pack(2, numerator, denominator);
1206 /* Hand ownership over to the tuple. If the tuple
1207 wasn't created successfully, we want to delete the
1208 ints anyway. */
1209 Py_DECREF(numerator);
1210 Py_DECREF(denominator);
1211 return result_pair;
1212 }
1213
1214 /* XXX: Could perhaps handle FLT_RADIX!=2 by using ilogb and
1215 scalbn, but those may not be in C89. */
1216 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1217 float_part = frexp(self, &exponent);
1218 is_negative = 0;
1219 if (float_part < 0) {
1220 float_part = -float_part;
1221 is_negative = 1;
1222 /* 0.5 <= float_part < 1.0 */
1223 }
1224 PyFPE_END_PROTECT(float_part);
1225 /* abs(self) == float_part * 2**exponent exactly */
1226
1227 /* Suck up chunk_size bits at a time; 28 is enough so that we
1228 suck up all bits in 2 iterations for all known binary
1229 double-precision formats, and small enough to fit in a
1230 long. */
1231 numerator = PyLong_FromLong(0);
1232 if (numerator == NULL) goto error;
1233
1234 long_methods = PyLong_Type.tp_as_number;
1235
1236 py_chunk = PyLong_FromLong(chunk_size);
1237 if (py_chunk == NULL) goto error;
1238
1239 while (float_part != 0) {
1240 /* invariant: abs(self) ==
1241 (numerator + float_part) * 2**exponent exactly */
1242 long digit;
1243 PyObject *py_digit;
1244
1245 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1246 /* Pull chunk_size bits out of float_part, into digits. */
1247 float_part = ldexp(float_part, chunk_size);
1248 digit = (long)float_part;
1249 float_part -= digit;
1250 /* 0 <= float_part < 1 */
1251 exponent -= chunk_size;
1252 PyFPE_END_PROTECT(float_part);
1253
1254 /* Shift digits into numerator. */
1255 // numerator <<= chunk_size
1256 INPLACE_UPDATE(numerator,
1257 long_methods->nb_lshift(numerator, py_chunk));
1258 if (numerator == NULL) goto error;
1259
1260 // numerator |= digit
1261 py_digit = PyLong_FromLong(digit);
1262 if (py_digit == NULL) goto error;
1263 INPLACE_UPDATE(numerator,
1264 long_methods->nb_or(numerator, py_digit));
1265 Py_DECREF(py_digit);
1266 if (numerator == NULL) goto error;
1267 }
1268
1269 /* Add in the sign bit. */
1270 if (is_negative) {
1271 INPLACE_UPDATE(numerator,
1272 long_methods->nb_negative(numerator));
1273 if (numerator == NULL) goto error;
1274 }
1275
1276 /* now self = numerator * 2**exponent exactly; fold in 2**exponent */
1277 denominator = PyLong_FromLong(1);
1278 py_exponent = PyLong_FromLong(labs(exponent));
1279 if (py_exponent == NULL) goto error;
1280 INPLACE_UPDATE(py_exponent,
1281 long_methods->nb_lshift(denominator, py_exponent));
1282 if (py_exponent == NULL) goto error;
1283 if (exponent > 0) {
1284 INPLACE_UPDATE(numerator,
1285 long_methods->nb_multiply(numerator,
1286 py_exponent));
1287 if (numerator == NULL) goto error;
1288 }
1289 else {
1290 Py_DECREF(denominator);
1291 denominator = py_exponent;
1292 py_exponent = NULL;
1293 }
1294
1295 result_pair = PyTuple_Pack(2, numerator, denominator);
1296
1297#undef INPLACE_UPDATE
1298error:
1299 Py_XDECREF(py_exponent);
1300 Py_XDECREF(py_chunk);
1301 Py_XDECREF(denominator);
1302 Py_XDECREF(numerator);
1303 return result_pair;
1304}
1305
1306PyDoc_STRVAR(float_as_integer_ratio_doc,
1307"float.as_integer_ratio() -> (int, int)\n"
1308"\n"
1309"Returns a pair of integers, not necessarily in lowest terms, whose\n"
1310"ratio is exactly equal to the original float. This method raises an\n"
1311"OverflowError on infinities and a ValueError on nans. The resulting\n"
1312"denominator will be positive.\n"
1313"\n"
1314">>> (10.0).as_integer_ratio()\n"
1315"(167772160L, 16777216L)\n"
1316">>> (0.0).as_integer_ratio()\n"
1317"(0, 1)\n"
1318">>> (-.25).as_integer_ratio()\n"
1319"(-134217728L, 536870912L)");
1320
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001321
Jeremy Hylton938ace62002-07-17 16:30:39 +00001322static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001323float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1324
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325static PyObject *
1326float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1327{
1328 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001329 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330
Guido van Rossumbef14172001-08-29 15:47:46 +00001331 if (type != &PyFloat_Type)
1332 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1334 return NULL;
1335 if (PyString_Check(x))
1336 return PyFloat_FromString(x, NULL);
1337 return PyNumber_Float(x);
1338}
1339
Guido van Rossumbef14172001-08-29 15:47:46 +00001340/* Wimpy, slow approach to tp_new calls for subtypes of float:
1341 first create a regular float from whatever arguments we got,
1342 then allocate a subtype instance and initialize its ob_fval
1343 from the regular float. The regular float is then thrown away.
1344*/
1345static PyObject *
1346float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1347{
Anthony Baxter377be112006-04-11 06:54:30 +00001348 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001349
1350 assert(PyType_IsSubtype(type, &PyFloat_Type));
1351 tmp = float_new(&PyFloat_Type, args, kwds);
1352 if (tmp == NULL)
1353 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001354 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001355 newobj = type->tp_alloc(type, 0);
1356 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001357 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001358 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001359 }
Anthony Baxter377be112006-04-11 06:54:30 +00001360 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001361 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001362 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001363}
1364
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001365static PyObject *
1366float_getnewargs(PyFloatObject *v)
1367{
1368 return Py_BuildValue("(d)", v->ob_fval);
1369}
1370
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001371/* this is for the benefit of the pack/unpack routines below */
1372
1373typedef enum {
1374 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1375} float_format_type;
1376
1377static float_format_type double_format, float_format;
1378static float_format_type detected_double_format, detected_float_format;
1379
1380static PyObject *
1381float_getformat(PyTypeObject *v, PyObject* arg)
1382{
1383 char* s;
1384 float_format_type r;
1385
1386 if (!PyString_Check(arg)) {
1387 PyErr_Format(PyExc_TypeError,
1388 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001389 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001390 return NULL;
1391 }
1392 s = PyString_AS_STRING(arg);
1393 if (strcmp(s, "double") == 0) {
1394 r = double_format;
1395 }
1396 else if (strcmp(s, "float") == 0) {
1397 r = float_format;
1398 }
1399 else {
1400 PyErr_SetString(PyExc_ValueError,
1401 "__getformat__() argument 1 must be "
1402 "'double' or 'float'");
1403 return NULL;
1404 }
1405
1406 switch (r) {
1407 case unknown_format:
1408 return PyString_FromString("unknown");
1409 case ieee_little_endian_format:
1410 return PyString_FromString("IEEE, little-endian");
1411 case ieee_big_endian_format:
1412 return PyString_FromString("IEEE, big-endian");
1413 default:
1414 Py_FatalError("insane float_format or double_format");
1415 return NULL;
1416 }
1417}
1418
1419PyDoc_STRVAR(float_getformat_doc,
1420"float.__getformat__(typestr) -> string\n"
1421"\n"
1422"You probably don't want to use this function. It exists mainly to be\n"
1423"used in Python's test suite.\n"
1424"\n"
1425"typestr must be 'double' or 'float'. This function returns whichever of\n"
1426"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1427"format of floating point numbers used by the C type named by typestr.");
1428
1429static PyObject *
1430float_setformat(PyTypeObject *v, PyObject* args)
1431{
1432 char* typestr;
1433 char* format;
1434 float_format_type f;
1435 float_format_type detected;
1436 float_format_type *p;
1437
1438 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1439 return NULL;
1440
1441 if (strcmp(typestr, "double") == 0) {
1442 p = &double_format;
1443 detected = detected_double_format;
1444 }
1445 else if (strcmp(typestr, "float") == 0) {
1446 p = &float_format;
1447 detected = detected_float_format;
1448 }
1449 else {
1450 PyErr_SetString(PyExc_ValueError,
1451 "__setformat__() argument 1 must "
1452 "be 'double' or 'float'");
1453 return NULL;
1454 }
1455
1456 if (strcmp(format, "unknown") == 0) {
1457 f = unknown_format;
1458 }
1459 else if (strcmp(format, "IEEE, little-endian") == 0) {
1460 f = ieee_little_endian_format;
1461 }
1462 else if (strcmp(format, "IEEE, big-endian") == 0) {
1463 f = ieee_big_endian_format;
1464 }
1465 else {
1466 PyErr_SetString(PyExc_ValueError,
1467 "__setformat__() argument 2 must be "
1468 "'unknown', 'IEEE, little-endian' or "
1469 "'IEEE, big-endian'");
1470 return NULL;
1471
1472 }
1473
1474 if (f != unknown_format && f != detected) {
1475 PyErr_Format(PyExc_ValueError,
1476 "can only set %s format to 'unknown' or the "
1477 "detected platform value", typestr);
1478 return NULL;
1479 }
1480
1481 *p = f;
1482 Py_RETURN_NONE;
1483}
1484
1485PyDoc_STRVAR(float_setformat_doc,
1486"float.__setformat__(typestr, fmt) -> None\n"
1487"\n"
1488"You probably don't want to use this function. It exists mainly to be\n"
1489"used in Python's test suite.\n"
1490"\n"
1491"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1492"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1493"one of the latter two if it appears to match the underlying C reality.\n"
1494"\n"
1495"Overrides the automatic determination of C-level floating point type.\n"
1496"This affects how floats are converted to and from binary strings.");
1497
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001498static PyObject *
1499float_getzero(PyObject *v, void *closure)
1500{
1501 return PyFloat_FromDouble(0.0);
1502}
1503
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001504static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001505 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1506 "Returns self, the complex conjugate of any float."},
1507 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1508 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001509 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1510 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001511 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001512 {"__getformat__", (PyCFunction)float_getformat,
1513 METH_O|METH_CLASS, float_getformat_doc},
1514 {"__setformat__", (PyCFunction)float_setformat,
1515 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001516 {NULL, NULL} /* sentinel */
1517};
1518
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001519static PyGetSetDef float_getset[] = {
1520 {"real",
1521 (getter)float_float, (setter)NULL,
1522 "the real part of a complex number",
1523 NULL},
1524 {"imag",
1525 (getter)float_getzero, (setter)NULL,
1526 "the imaginary part of a complex number",
1527 NULL},
1528 {NULL} /* Sentinel */
1529};
1530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001531PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532"float(x) -> floating point number\n\
1533\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001534Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535
1536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001537static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001538 float_add, /*nb_add*/
1539 float_sub, /*nb_subtract*/
1540 float_mul, /*nb_multiply*/
1541 float_classic_div, /*nb_divide*/
1542 float_rem, /*nb_remainder*/
1543 float_divmod, /*nb_divmod*/
1544 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001545 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001546 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001547 (unaryfunc)float_abs, /*nb_absolute*/
1548 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001549 0, /*nb_invert*/
1550 0, /*nb_lshift*/
1551 0, /*nb_rshift*/
1552 0, /*nb_and*/
1553 0, /*nb_xor*/
1554 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001555 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001556 float_trunc, /*nb_int*/
1557 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001558 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001559 0, /* nb_oct */
1560 0, /* nb_hex */
1561 0, /* nb_inplace_add */
1562 0, /* nb_inplace_subtract */
1563 0, /* nb_inplace_multiply */
1564 0, /* nb_inplace_divide */
1565 0, /* nb_inplace_remainder */
1566 0, /* nb_inplace_power */
1567 0, /* nb_inplace_lshift */
1568 0, /* nb_inplace_rshift */
1569 0, /* nb_inplace_and */
1570 0, /* nb_inplace_xor */
1571 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001572 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001573 float_div, /* nb_true_divide */
1574 0, /* nb_inplace_floor_divide */
1575 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001576};
1577
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001578PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001579 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001580 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001581 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001582 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 (destructor)float_dealloc, /* tp_dealloc */
1584 (printfunc)float_print, /* tp_print */
1585 0, /* tp_getattr */
1586 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001587 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 (reprfunc)float_repr, /* tp_repr */
1589 &float_as_number, /* tp_as_number */
1590 0, /* tp_as_sequence */
1591 0, /* tp_as_mapping */
1592 (hashfunc)float_hash, /* tp_hash */
1593 0, /* tp_call */
1594 (reprfunc)float_str, /* tp_str */
1595 PyObject_GenericGetAttr, /* tp_getattro */
1596 0, /* tp_setattro */
1597 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001598 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1599 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 float_doc, /* tp_doc */
1601 0, /* tp_traverse */
1602 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001603 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604 0, /* tp_weaklistoffset */
1605 0, /* tp_iter */
1606 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001607 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001609 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610 0, /* tp_base */
1611 0, /* tp_dict */
1612 0, /* tp_descr_get */
1613 0, /* tp_descr_set */
1614 0, /* tp_dictoffset */
1615 0, /* tp_init */
1616 0, /* tp_alloc */
1617 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001618};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001619
1620void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621_PyFloat_Init(void)
1622{
1623 /* We attempt to determine if this machine is using IEEE
1624 floating point formats by peering at the bits of some
1625 carefully chosen values. If it looks like we are on an
1626 IEEE platform, the float packing/unpacking routines can
1627 just copy bits, if not they resort to arithmetic & shifts
1628 and masks. The shifts & masks approach works on all finite
1629 values, but what happens to infinities, NaNs and signed
1630 zeroes on packing is an accident, and attempting to unpack
1631 a NaN or an infinity will raise an exception.
1632
1633 Note that if we're on some whacked-out platform which uses
1634 IEEE formats but isn't strictly little-endian or big-
1635 endian, we will fall back to the portable shifts & masks
1636 method. */
1637
1638#if SIZEOF_DOUBLE == 8
1639 {
1640 double x = 9006104071832581.0;
1641 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1642 detected_double_format = ieee_big_endian_format;
1643 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1644 detected_double_format = ieee_little_endian_format;
1645 else
1646 detected_double_format = unknown_format;
1647 }
1648#else
1649 detected_double_format = unknown_format;
1650#endif
1651
1652#if SIZEOF_FLOAT == 4
1653 {
1654 float y = 16711938.0;
1655 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1656 detected_float_format = ieee_big_endian_format;
1657 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1658 detected_float_format = ieee_little_endian_format;
1659 else
1660 detected_float_format = unknown_format;
1661 }
1662#else
1663 detected_float_format = unknown_format;
1664#endif
1665
1666 double_format = detected_double_format;
1667 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001668
1669#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001670 /* Initialize floating point repr */
1671 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001672#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673}
1674
1675void
Fred Drakefd99de62000-07-09 05:02:18 +00001676PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001677{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001678 PyFloatObject *p;
1679 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001680 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001681 int bc, bf; /* block count, number of freed blocks */
1682 int frem, fsum; /* remaining unfreed floats per block, total */
1683
1684 bc = 0;
1685 bf = 0;
1686 fsum = 0;
1687 list = block_list;
1688 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001689 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001690 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001691 bc++;
1692 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001693 for (i = 0, p = &list->objects[0];
1694 i < N_FLOATOBJECTS;
1695 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001696 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001697 frem++;
1698 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001699 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001700 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001701 list->next = block_list;
1702 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001703 for (i = 0, p = &list->objects[0];
1704 i < N_FLOATOBJECTS;
1705 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001706 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001707 Py_REFCNT(p) == 0) {
1708 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001709 free_list;
1710 free_list = p;
1711 }
1712 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001713 }
1714 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001715 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001716 bf++;
1717 }
1718 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001719 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001720 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001721 if (!Py_VerboseFlag)
1722 return;
1723 fprintf(stderr, "# cleanup floats");
1724 if (!fsum) {
1725 fprintf(stderr, "\n");
1726 }
1727 else {
1728 fprintf(stderr,
1729 ": %d unfreed float%s in %d out of %d block%s\n",
1730 fsum, fsum == 1 ? "" : "s",
1731 bc - bf, bc, bc == 1 ? "" : "s");
1732 }
1733 if (Py_VerboseFlag > 1) {
1734 list = block_list;
1735 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001736 for (i = 0, p = &list->objects[0];
1737 i < N_FLOATOBJECTS;
1738 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001739 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001740 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001741 char buf[100];
1742 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001743 /* XXX(twouters) cast refcount to
1744 long until %zd is universally
1745 available
1746 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001747 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001748 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001749 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001750 }
1751 }
1752 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001753 }
1754 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001755}
Tim Peters9905b942003-03-20 20:53:32 +00001756
1757/*----------------------------------------------------------------------------
1758 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1759 *
1760 * TODO: On platforms that use the standard IEEE-754 single and double
1761 * formats natively, these routines could simply copy the bytes.
1762 */
1763int
1764_PyFloat_Pack4(double x, unsigned char *p, int le)
1765{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001766 if (float_format == unknown_format) {
1767 unsigned char sign;
1768 int e;
1769 double f;
1770 unsigned int fbits;
1771 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001772
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001773 if (le) {
1774 p += 3;
1775 incr = -1;
1776 }
Tim Peters9905b942003-03-20 20:53:32 +00001777
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001778 if (x < 0) {
1779 sign = 1;
1780 x = -x;
1781 }
1782 else
1783 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001784
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001785 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001786
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001787 /* Normalize f to be in the range [1.0, 2.0) */
1788 if (0.5 <= f && f < 1.0) {
1789 f *= 2.0;
1790 e--;
1791 }
1792 else if (f == 0.0)
1793 e = 0;
1794 else {
1795 PyErr_SetString(PyExc_SystemError,
1796 "frexp() result out of range");
1797 return -1;
1798 }
1799
1800 if (e >= 128)
1801 goto Overflow;
1802 else if (e < -126) {
1803 /* Gradual underflow */
1804 f = ldexp(f, 126 + e);
1805 e = 0;
1806 }
1807 else if (!(e == 0 && f == 0.0)) {
1808 e += 127;
1809 f -= 1.0; /* Get rid of leading 1 */
1810 }
1811
1812 f *= 8388608.0; /* 2**23 */
1813 fbits = (unsigned int)(f + 0.5); /* Round */
1814 assert(fbits <= 8388608);
1815 if (fbits >> 23) {
1816 /* The carry propagated out of a string of 23 1 bits. */
1817 fbits = 0;
1818 ++e;
1819 if (e >= 255)
1820 goto Overflow;
1821 }
1822
1823 /* First byte */
1824 *p = (sign << 7) | (e >> 1);
1825 p += incr;
1826
1827 /* Second byte */
1828 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1829 p += incr;
1830
1831 /* Third byte */
1832 *p = (fbits >> 8) & 0xFF;
1833 p += incr;
1834
1835 /* Fourth byte */
1836 *p = fbits & 0xFF;
1837
1838 /* Done */
1839 return 0;
1840
1841 Overflow:
1842 PyErr_SetString(PyExc_OverflowError,
1843 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001844 return -1;
1845 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001846 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001847 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001848 const char *s = (char*)&y;
1849 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001850
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001851 if ((float_format == ieee_little_endian_format && !le)
1852 || (float_format == ieee_big_endian_format && le)) {
1853 p += 3;
1854 incr = -1;
1855 }
1856
1857 for (i = 0; i < 4; i++) {
1858 *p = *s++;
1859 p += incr;
1860 }
1861 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001862 }
Tim Peters9905b942003-03-20 20:53:32 +00001863}
1864
1865int
1866_PyFloat_Pack8(double x, unsigned char *p, int le)
1867{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001868 if (double_format == unknown_format) {
1869 unsigned char sign;
1870 int e;
1871 double f;
1872 unsigned int fhi, flo;
1873 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001874
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001875 if (le) {
1876 p += 7;
1877 incr = -1;
1878 }
Tim Peters9905b942003-03-20 20:53:32 +00001879
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001880 if (x < 0) {
1881 sign = 1;
1882 x = -x;
1883 }
1884 else
1885 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001886
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001888
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001889 /* Normalize f to be in the range [1.0, 2.0) */
1890 if (0.5 <= f && f < 1.0) {
1891 f *= 2.0;
1892 e--;
1893 }
1894 else if (f == 0.0)
1895 e = 0;
1896 else {
1897 PyErr_SetString(PyExc_SystemError,
1898 "frexp() result out of range");
1899 return -1;
1900 }
1901
1902 if (e >= 1024)
1903 goto Overflow;
1904 else if (e < -1022) {
1905 /* Gradual underflow */
1906 f = ldexp(f, 1022 + e);
1907 e = 0;
1908 }
1909 else if (!(e == 0 && f == 0.0)) {
1910 e += 1023;
1911 f -= 1.0; /* Get rid of leading 1 */
1912 }
1913
1914 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1915 f *= 268435456.0; /* 2**28 */
1916 fhi = (unsigned int)f; /* Truncate */
1917 assert(fhi < 268435456);
1918
1919 f -= (double)fhi;
1920 f *= 16777216.0; /* 2**24 */
1921 flo = (unsigned int)(f + 0.5); /* Round */
1922 assert(flo <= 16777216);
1923 if (flo >> 24) {
1924 /* The carry propagated out of a string of 24 1 bits. */
1925 flo = 0;
1926 ++fhi;
1927 if (fhi >> 28) {
1928 /* And it also progagated out of the next 28 bits. */
1929 fhi = 0;
1930 ++e;
1931 if (e >= 2047)
1932 goto Overflow;
1933 }
1934 }
1935
1936 /* First byte */
1937 *p = (sign << 7) | (e >> 4);
1938 p += incr;
1939
1940 /* Second byte */
1941 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1942 p += incr;
1943
1944 /* Third byte */
1945 *p = (fhi >> 16) & 0xFF;
1946 p += incr;
1947
1948 /* Fourth byte */
1949 *p = (fhi >> 8) & 0xFF;
1950 p += incr;
1951
1952 /* Fifth byte */
1953 *p = fhi & 0xFF;
1954 p += incr;
1955
1956 /* Sixth byte */
1957 *p = (flo >> 16) & 0xFF;
1958 p += incr;
1959
1960 /* Seventh byte */
1961 *p = (flo >> 8) & 0xFF;
1962 p += incr;
1963
1964 /* Eighth byte */
1965 *p = flo & 0xFF;
1966 p += incr;
1967
1968 /* Done */
1969 return 0;
1970
1971 Overflow:
1972 PyErr_SetString(PyExc_OverflowError,
1973 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001974 return -1;
1975 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001976 else {
1977 const char *s = (char*)&x;
1978 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001979
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001980 if ((double_format == ieee_little_endian_format && !le)
1981 || (double_format == ieee_big_endian_format && le)) {
1982 p += 7;
1983 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001984 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001985
1986 for (i = 0; i < 8; i++) {
1987 *p = *s++;
1988 p += incr;
1989 }
1990 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001991 }
Tim Peters9905b942003-03-20 20:53:32 +00001992}
1993
1994double
1995_PyFloat_Unpack4(const unsigned char *p, int le)
1996{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997 if (float_format == unknown_format) {
1998 unsigned char sign;
1999 int e;
2000 unsigned int f;
2001 double x;
2002 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002003
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002004 if (le) {
2005 p += 3;
2006 incr = -1;
2007 }
2008
2009 /* First byte */
2010 sign = (*p >> 7) & 1;
2011 e = (*p & 0x7F) << 1;
2012 p += incr;
2013
2014 /* Second byte */
2015 e |= (*p >> 7) & 1;
2016 f = (*p & 0x7F) << 16;
2017 p += incr;
2018
2019 if (e == 255) {
2020 PyErr_SetString(
2021 PyExc_ValueError,
2022 "can't unpack IEEE 754 special value "
2023 "on non-IEEE platform");
2024 return -1;
2025 }
2026
2027 /* Third byte */
2028 f |= *p << 8;
2029 p += incr;
2030
2031 /* Fourth byte */
2032 f |= *p;
2033
2034 x = (double)f / 8388608.0;
2035
2036 /* XXX This sadly ignores Inf/NaN issues */
2037 if (e == 0)
2038 e = -126;
2039 else {
2040 x += 1.0;
2041 e -= 127;
2042 }
2043 x = ldexp(x, e);
2044
2045 if (sign)
2046 x = -x;
2047
2048 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002049 }
Tim Peters9905b942003-03-20 20:53:32 +00002050 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002051 float x;
2052
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002053 if ((float_format == ieee_little_endian_format && !le)
2054 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002055 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002056 char *d = &buf[3];
2057 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002058
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002059 for (i = 0; i < 4; i++) {
2060 *d-- = *p++;
2061 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002062 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002063 }
2064 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002065 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002066 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002067
2068 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002069 }
Tim Peters9905b942003-03-20 20:53:32 +00002070}
2071
2072double
2073_PyFloat_Unpack8(const unsigned char *p, int le)
2074{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002075 if (double_format == unknown_format) {
2076 unsigned char sign;
2077 int e;
2078 unsigned int fhi, flo;
2079 double x;
2080 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002081
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002082 if (le) {
2083 p += 7;
2084 incr = -1;
2085 }
2086
2087 /* First byte */
2088 sign = (*p >> 7) & 1;
2089 e = (*p & 0x7F) << 4;
2090
2091 p += incr;
2092
2093 /* Second byte */
2094 e |= (*p >> 4) & 0xF;
2095 fhi = (*p & 0xF) << 24;
2096 p += incr;
2097
2098 if (e == 2047) {
2099 PyErr_SetString(
2100 PyExc_ValueError,
2101 "can't unpack IEEE 754 special value "
2102 "on non-IEEE platform");
2103 return -1.0;
2104 }
2105
2106 /* Third byte */
2107 fhi |= *p << 16;
2108 p += incr;
2109
2110 /* Fourth byte */
2111 fhi |= *p << 8;
2112 p += incr;
2113
2114 /* Fifth byte */
2115 fhi |= *p;
2116 p += incr;
2117
2118 /* Sixth byte */
2119 flo = *p << 16;
2120 p += incr;
2121
2122 /* Seventh byte */
2123 flo |= *p << 8;
2124 p += incr;
2125
2126 /* Eighth byte */
2127 flo |= *p;
2128
2129 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2130 x /= 268435456.0; /* 2**28 */
2131
2132 if (e == 0)
2133 e = -1022;
2134 else {
2135 x += 1.0;
2136 e -= 1023;
2137 }
2138 x = ldexp(x, e);
2139
2140 if (sign)
2141 x = -x;
2142
2143 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002144 }
Tim Peters9905b942003-03-20 20:53:32 +00002145 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002146 double x;
2147
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002148 if ((double_format == ieee_little_endian_format && !le)
2149 || (double_format == ieee_big_endian_format && le)) {
2150 char buf[8];
2151 char *d = &buf[7];
2152 int i;
2153
2154 for (i = 0; i < 8; i++) {
2155 *d-- = *p++;
2156 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002157 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158 }
2159 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002160 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002161 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002162
2163 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002164 }
Tim Peters9905b942003-03-20 20:53:32 +00002165}