blob: 9f94003184376f4835b3d036284228f512dcaa49 [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 Heimesd32ed6f2008-01-14 18:49:24 +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 Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Christian Heimes969fe572008-01-25 11:23:10 +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. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
26#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
27#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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000032};
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyFloatObject *p, *q;
43 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
45 if (p == NULL)
46 return (PyFloatObject *) PyErr_NoMemory();
47 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
50 q = p + N_FLOATOBJECTS;
51 while (--q > p)
52 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
54 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055}
56
Christian Heimes93852662007-12-01 12:22:32 +000057double
58PyFloat_GetMax(void)
59{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000061}
62
63double
64PyFloat_GetMin(void)
65{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000067}
68
Christian Heimesd32ed6f2008-01-14 18:49:24 +000069static PyTypeObject FloatInfoType;
70
71PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000072"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073\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[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 {"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}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000096};
97
98static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 "sys.float_info", /* name */
100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000103};
104
Christian Heimes93852662007-12-01 12:22:32 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyObject* floatinfo;
109 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 floatinfo = PyStructSequence_New(&FloatInfoType);
112 if (floatinfo == NULL) {
113 return NULL;
114 }
Christian Heimes93852662007-12-01 12:22:32 +0000115
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000116#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000118#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 SetDblFlag(DBL_MAX);
122 SetIntFlag(DBL_MAX_EXP);
123 SetIntFlag(DBL_MAX_10_EXP);
124 SetDblFlag(DBL_MIN);
125 SetIntFlag(DBL_MIN_EXP);
126 SetIntFlag(DBL_MIN_10_EXP);
127 SetIntFlag(DBL_DIG);
128 SetIntFlag(DBL_MANT_DIG);
129 SetDblFlag(DBL_EPSILON);
130 SetIntFlag(FLT_RADIX);
131 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000132#undef SetIntFlag
133#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134
135 if (PyErr_Occurred()) {
136 Py_CLEAR(floatinfo);
137 return NULL;
138 }
139 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000140}
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 register PyFloatObject *op;
146 if (free_list == NULL) {
147 if ((free_list = fill_free_list()) == NULL)
148 return NULL;
149 }
150 /* Inline PyObject_New */
151 op = free_list;
152 free_list = (PyFloatObject *)Py_TYPE(op);
153 PyObject_INIT(op, &PyFloat_Type);
154 op->ob_fval = fval;
155 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000158PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000159PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 const char *s, *last, *end;
162 double x;
163 char buffer[256]; /* for errors */
164 char *s_buffer = NULL;
165 Py_ssize_t len;
166 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (PyUnicode_Check(v)) {
169 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
170 if (s_buffer == NULL)
171 return PyErr_NoMemory();
172 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
173 PyUnicode_GET_SIZE(v),
174 s_buffer,
175 NULL))
176 goto error;
177 s = s_buffer;
178 len = strlen(s);
179 }
180 else if (PyObject_AsCharBuffer(v, &s, &len)) {
181 PyErr_SetString(PyExc_TypeError,
182 "float() argument must be a string or a number");
183 return NULL;
184 }
185 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 while (Py_ISSPACE(*s))
188 s++;
189 /* We don't care about overflow or underflow. If the platform
190 * supports them, infinities and signed zeroes (on underflow) are
191 * fine. */
192 x = PyOS_string_to_double(s, (char **)&end, NULL);
193 if (x == -1.0 && PyErr_Occurred())
194 goto error;
195 while (Py_ISSPACE(*end))
196 end++;
197 if (end == last)
198 result = PyFloat_FromDouble(x);
199 else {
200 PyOS_snprintf(buffer, sizeof(buffer),
201 "invalid literal for float(): %.200s", s);
202 PyErr_SetString(PyExc_ValueError, buffer);
203 result = NULL;
204 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000205
Guido van Rossum2be161d2007-05-15 20:43:51 +0000206 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (s_buffer)
208 PyMem_FREE(s_buffer);
209 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210}
211
Guido van Rossum234f9421993-06-17 12:35:49 +0000212static void
Fred Drakefd99de62000-07-09 05:02:18 +0000213float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 if (PyFloat_CheckExact(op)) {
216 Py_TYPE(op) = (struct _typeobject *)free_list;
217 free_list = op;
218 }
219 else
220 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000221}
222
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223double
Fred Drakefd99de62000-07-09 05:02:18 +0000224PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyNumberMethods *nb;
227 PyFloatObject *fo;
228 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (op && PyFloat_Check(op))
231 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (op == NULL) {
234 PyErr_BadArgument();
235 return -1;
236 }
Tim Petersd2364e82001-11-01 20:09:42 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
239 PyErr_SetString(PyExc_TypeError, "a float is required");
240 return -1;
241 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 fo = (PyFloatObject*) (*nb->nb_float) (op);
244 if (fo == NULL)
245 return -1;
246 if (!PyFloat_Check(fo)) {
247 PyErr_SetString(PyExc_TypeError,
248 "nb_float should return float object");
249 return -1;
250 }
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 val = PyFloat_AS_DOUBLE(fo);
253 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256}
257
Neil Schemenauer32117e52001-01-04 01:44:34 +0000258/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000259 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000260 set to NULL, and the function invoking this macro returns NULL. If
261 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
262 stored in obj, and returned from the function invoking this macro.
263*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264#define CONVERT_TO_DOUBLE(obj, dbl) \
265 if (PyFloat_Check(obj)) \
266 dbl = PyFloat_AS_DOUBLE(obj); \
267 else if (convert_to_double(&(obj), &(dbl)) < 0) \
268 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000269
Eric Smith0923d1d2009-04-16 20:16:10 +0000270/* Methods */
271
Neil Schemenauer32117e52001-01-04 01:44:34 +0000272static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000273convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (PyLong_Check(obj)) {
278 *dbl = PyLong_AsDouble(obj);
279 if (*dbl == -1.0 && PyErr_Occurred()) {
280 *v = NULL;
281 return -1;
282 }
283 }
284 else {
285 Py_INCREF(Py_NotImplemented);
286 *v = Py_NotImplemented;
287 return -1;
288 }
289 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000290}
291
Eric Smith0923d1d2009-04-16 20:16:10 +0000292static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000293float_str_or_repr(PyFloatObject *v, int precision, char format_code)
Eric Smith0923d1d2009-04-16 20:16:10 +0000294{
295 PyObject *result;
296 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Eric Smith63376222009-05-05 14:04:18 +0000297 format_code, precision,
298 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000299 NULL);
300 if (!buf)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000302 result = PyUnicode_FromString(buf);
303 PyMem_Free(buf);
304 return result;
305}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000306
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000308float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Eric Smith63376222009-05-05 14:04:18 +0000310 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000311}
312
313static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000314float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000315{
Eric Smith63376222009-05-05 14:04:18 +0000316 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317}
318
Tim Peters307fa782004-09-23 08:06:40 +0000319/* Comparison is pretty much a nightmare. When comparing float to float,
320 * we do it as straightforwardly (and long-windedly) as conceivable, so
321 * that, e.g., Python x == y delivers the same result as the platform
322 * C x == y when x and/or y is a NaN.
323 * When mixing float with an integer type, there's no good *uniform* approach.
324 * Converting the double to an integer obviously doesn't work, since we
325 * may lose info from fractional bits. Converting the integer to a double
326 * also has two failure modes: (1) a long int may trigger overflow (too
327 * large to fit in the dynamic range of a C double); (2) even a C long may have
328 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
329 * 63 bits of precision, but a C double probably has only 53), and then
330 * we can falsely claim equality when low-order integer bits are lost by
331 * coercion to double. So this part is painful too.
332 */
333
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000334static PyObject*
335float_richcompare(PyObject *v, PyObject *w, int op)
336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 double i, j;
338 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 assert(PyFloat_Check(v));
341 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 /* Switch on the type of w. Set i and j to doubles to be compared,
344 * and op to the richcomp to use.
345 */
346 if (PyFloat_Check(w))
347 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 else if (!Py_IS_FINITE(i)) {
350 if (PyLong_Check(w))
351 /* If i is an infinity, its magnitude exceeds any
352 * finite integer, so it doesn't matter which int we
353 * compare i with. If i is a NaN, similarly.
354 */
355 j = 0.0;
356 else
357 goto Unimplemented;
358 }
Tim Peters307fa782004-09-23 08:06:40 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 else if (PyLong_Check(w)) {
361 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
362 int wsign = _PyLong_Sign(w);
363 size_t nbits;
364 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (vsign != wsign) {
367 /* Magnitudes are irrelevant -- the signs alone
368 * determine the outcome.
369 */
370 i = (double)vsign;
371 j = (double)wsign;
372 goto Compare;
373 }
374 /* The signs are the same. */
375 /* Convert w to a double if it fits. In particular, 0 fits. */
376 nbits = _PyLong_NumBits(w);
377 if (nbits == (size_t)-1 && PyErr_Occurred()) {
378 /* This long is so large that size_t isn't big enough
379 * to hold the # of bits. Replace with little doubles
380 * that give the same outcome -- w is so large that
381 * its magnitude must exceed the magnitude of any
382 * finite float.
383 */
384 PyErr_Clear();
385 i = (double)vsign;
386 assert(wsign != 0);
387 j = wsign * 2.0;
388 goto Compare;
389 }
390 if (nbits <= 48) {
391 j = PyLong_AsDouble(w);
392 /* It's impossible that <= 48 bits overflowed. */
393 assert(j != -1.0 || ! PyErr_Occurred());
394 goto Compare;
395 }
396 assert(wsign != 0); /* else nbits was 0 */
397 assert(vsign != 0); /* if vsign were 0, then since wsign is
398 * not 0, we would have taken the
399 * vsign != wsign branch at the start */
400 /* We want to work with non-negative numbers. */
401 if (vsign < 0) {
402 /* "Multiply both sides" by -1; this also swaps the
403 * comparator.
404 */
405 i = -i;
406 op = _Py_SwappedOp[op];
407 }
408 assert(i > 0.0);
409 (void) frexp(i, &exponent);
410 /* exponent is the # of bits in v before the radix point;
411 * we know that nbits (the # of bits in w) > 48 at this point
412 */
413 if (exponent < 0 || (size_t)exponent < nbits) {
414 i = 1.0;
415 j = 2.0;
416 goto Compare;
417 }
418 if ((size_t)exponent > nbits) {
419 i = 2.0;
420 j = 1.0;
421 goto Compare;
422 }
423 /* v and w have the same number of bits before the radix
424 * point. Construct two longs that have the same comparison
425 * outcome.
426 */
427 {
428 double fracpart;
429 double intpart;
430 PyObject *result = NULL;
431 PyObject *one = NULL;
432 PyObject *vv = NULL;
433 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (wsign < 0) {
436 ww = PyNumber_Negative(w);
437 if (ww == NULL)
438 goto Error;
439 }
440 else
441 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 fracpart = modf(i, &intpart);
444 vv = PyLong_FromDouble(intpart);
445 if (vv == NULL)
446 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (fracpart != 0.0) {
449 /* Shift left, and or a 1 bit into vv
450 * to represent the lost fraction.
451 */
452 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 one = PyLong_FromLong(1);
455 if (one == NULL)
456 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 temp = PyNumber_Lshift(ww, one);
459 if (temp == NULL)
460 goto Error;
461 Py_DECREF(ww);
462 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 temp = PyNumber_Lshift(vv, one);
465 if (temp == NULL)
466 goto Error;
467 Py_DECREF(vv);
468 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 temp = PyNumber_Or(vv, one);
471 if (temp == NULL)
472 goto Error;
473 Py_DECREF(vv);
474 vv = temp;
475 }
Tim Peters307fa782004-09-23 08:06:40 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 r = PyObject_RichCompareBool(vv, ww, op);
478 if (r < 0)
479 goto Error;
480 result = PyBool_FromLong(r);
481 Error:
482 Py_XDECREF(vv);
483 Py_XDECREF(ww);
484 Py_XDECREF(one);
485 return result;
486 }
487 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 else /* w isn't float, int, or long */
490 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000491
492 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyFPE_START_PROTECT("richcompare", return NULL)
494 switch (op) {
495 case Py_EQ:
496 r = i == j;
497 break;
498 case Py_NE:
499 r = i != j;
500 break;
501 case Py_LE:
502 r = i <= j;
503 break;
504 case Py_GE:
505 r = i >= j;
506 break;
507 case Py_LT:
508 r = i < j;
509 break;
510 case Py_GT:
511 r = i > j;
512 break;
513 }
514 PyFPE_END_PROTECT(r)
515 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000516
517 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Py_INCREF(Py_NotImplemented);
519 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000520}
521
Guido van Rossum9bfef441993-03-29 10:43:31 +0000522static long
Fred Drakefd99de62000-07-09 05:02:18 +0000523float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526}
527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 double a,b;
532 CONVERT_TO_DOUBLE(v, a);
533 CONVERT_TO_DOUBLE(w, b);
534 PyFPE_START_PROTECT("add", return 0)
535 a = a + b;
536 PyFPE_END_PROTECT(a)
537 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538}
539
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 double a,b;
544 CONVERT_TO_DOUBLE(v, a);
545 CONVERT_TO_DOUBLE(w, b);
546 PyFPE_START_PROTECT("subtract", return 0)
547 a = a - b;
548 PyFPE_END_PROTECT(a)
549 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 double a,b;
556 CONVERT_TO_DOUBLE(v, a);
557 CONVERT_TO_DOUBLE(w, b);
558 PyFPE_START_PROTECT("multiply", return 0)
559 a = a * b;
560 PyFPE_END_PROTECT(a)
561 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 double a,b;
568 CONVERT_TO_DOUBLE(v, a);
569 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000570#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (b == 0.0) {
572 PyErr_SetString(PyExc_ZeroDivisionError,
573 "float division by zero");
574 return NULL;
575 }
Christian Heimes53876d92008-04-19 00:31:39 +0000576#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 PyFPE_START_PROTECT("divide", return 0)
578 a = a / b;
579 PyFPE_END_PROTECT(a)
580 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 double vx, wx;
587 double mod;
588 CONVERT_TO_DOUBLE(v, vx);
589 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000590#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (wx == 0.0) {
592 PyErr_SetString(PyExc_ZeroDivisionError,
593 "float modulo");
594 return NULL;
595 }
Christian Heimes53876d92008-04-19 00:31:39 +0000596#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 PyFPE_START_PROTECT("modulo", return 0)
598 mod = fmod(vx, wx);
599 /* note: checking mod*wx < 0 is incorrect -- underflows to
600 0 if wx < sqrt(smallest nonzero double) */
601 if (mod && ((wx < 0) != (mod < 0))) {
602 mod += wx;
603 }
604 PyFPE_END_PROTECT(mod)
605 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606}
607
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000609float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 double vx, wx;
612 double div, mod, floordiv;
613 CONVERT_TO_DOUBLE(v, vx);
614 CONVERT_TO_DOUBLE(w, wx);
615 if (wx == 0.0) {
616 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
617 return NULL;
618 }
619 PyFPE_START_PROTECT("divmod", return 0)
620 mod = fmod(vx, wx);
621 /* fmod is typically exact, so vx-mod is *mathematically* an
622 exact multiple of wx. But this is fp arithmetic, and fp
623 vx - mod is an approximation; the result is that div may
624 not be an exact integral value after the division, although
625 it will always be very close to one.
626 */
627 div = (vx - mod) / wx;
628 if (mod) {
629 /* ensure the remainder has the same sign as the denominator */
630 if ((wx < 0) != (mod < 0)) {
631 mod += wx;
632 div -= 1.0;
633 }
634 }
635 else {
636 /* the remainder is zero, and in the presence of signed zeroes
637 fmod returns different results across platforms; ensure
638 it has the same sign as the denominator; we'd like to do
639 "mod = wx * 0.0", but that may get optimized away */
640 mod *= mod; /* hide "mod = +0" from optimizer */
641 if (wx < 0.0)
642 mod = -mod;
643 }
644 /* snap quotient to nearest integral value */
645 if (div) {
646 floordiv = floor(div);
647 if (div - floordiv > 0.5)
648 floordiv += 1.0;
649 }
650 else {
651 /* div is zero - get the same sign as the true quotient */
652 div *= div; /* hide "div = +0" from optimizers */
653 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
654 }
655 PyFPE_END_PROTECT(floordiv)
656 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000660float_floor_div(PyObject *v, PyObject *w)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 t = float_divmod(v, w);
665 if (t == NULL || t == Py_NotImplemented)
666 return t;
667 assert(PyTuple_CheckExact(t));
668 r = PyTuple_GET_ITEM(t, 0);
669 Py_INCREF(r);
670 Py_DECREF(t);
671 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000672}
673
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000674/* determine whether x is an odd integer or not; assumes that
675 x is not an infinity or nan. */
676#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
677
Tim Peters63a35712001-12-11 19:57:24 +0000678static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 double iv, iw, ix;
682 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if ((PyObject *)z != Py_None) {
685 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
686 "allowed unless all arguments are integers");
687 return NULL;
688 }
Tim Peters32f453e2001-09-03 08:35:41 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 CONVERT_TO_DOUBLE(v, iv);
691 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* Sort out special cases here instead of relying on pow() */
694 if (iw == 0) { /* v**0 is 1, even 0**0 */
695 return PyFloat_FromDouble(1.0);
696 }
697 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
698 return PyFloat_FromDouble(iv);
699 }
700 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
701 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
702 }
703 if (Py_IS_INFINITY(iw)) {
704 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
705 * abs(v) > 1 (including case where v infinite)
706 *
707 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
708 * abs(v) > 1 (including case where v infinite)
709 */
710 iv = fabs(iv);
711 if (iv == 1.0)
712 return PyFloat_FromDouble(1.0);
713 else if ((iw > 0.0) == (iv > 1.0))
714 return PyFloat_FromDouble(fabs(iw)); /* return inf */
715 else
716 return PyFloat_FromDouble(0.0);
717 }
718 if (Py_IS_INFINITY(iv)) {
719 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
720 * both cases, we need to add the appropriate sign if w is
721 * an odd integer.
722 */
723 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
724 if (iw > 0.0)
725 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
726 else
727 return PyFloat_FromDouble(iw_is_odd ?
728 copysign(0.0, iv) : 0.0);
729 }
730 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
731 (already dealt with above), and an error
732 if w is negative. */
733 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
734 if (iw < 0.0) {
735 PyErr_SetString(PyExc_ZeroDivisionError,
736 "0.0 cannot be raised to a "
737 "negative power");
738 return NULL;
739 }
740 /* use correct sign if iw is odd */
741 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
742 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (iv < 0.0) {
745 /* Whether this is an error is a mess, and bumps into libm
746 * bugs so we have to figure it out ourselves.
747 */
748 if (iw != floor(iw)) {
749 /* Negative numbers raised to fractional powers
750 * become complex.
751 */
752 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
753 }
754 /* iw is an exact integer, albeit perhaps a very large
755 * one. Replace iv by its absolute value and remember
756 * to negate the pow result if iw is odd.
757 */
758 iv = -iv;
759 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
760 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
763 /* (-1) ** large_integer also ends up here. Here's an
764 * extract from the comments for the previous
765 * implementation explaining why this special case is
766 * necessary:
767 *
768 * -1 raised to an exact integer should never be exceptional.
769 * Alas, some libms (chiefly glibc as of early 2003) return
770 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
771 * happen to be representable in a *C* integer. That's a
772 * bug.
773 */
774 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
775 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* Now iv and iw are finite, iw is nonzero, and iv is
778 * positive and not equal to 1.0. We finally allow
779 * the platform pow to step in and do the rest.
780 */
781 errno = 0;
782 PyFPE_START_PROTECT("pow", return NULL)
783 ix = pow(iv, iw);
784 PyFPE_END_PROTECT(ix)
785 Py_ADJUST_ERANGE1(ix);
786 if (negate_result)
787 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (errno != 0) {
790 /* We don't expect any errno value other than ERANGE, but
791 * the range of libm bugs appears unbounded.
792 */
793 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
794 PyExc_ValueError);
795 return NULL;
796 }
797 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798}
799
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000800#undef DOUBLE_IS_ODD_INTEGER
801
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000802static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000803float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806}
807
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000809float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000814static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000815float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000818}
819
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000820static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000821float_is_integer(PyObject *v)
822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 double x = PyFloat_AsDouble(v);
824 PyObject *o;
825
826 if (x == -1.0 && PyErr_Occurred())
827 return NULL;
828 if (!Py_IS_FINITE(x))
829 Py_RETURN_FALSE;
830 errno = 0;
831 PyFPE_START_PROTECT("is_integer", return NULL)
832 o = (floor(x) == x) ? Py_True : Py_False;
833 PyFPE_END_PROTECT(x)
834 if (errno != 0) {
835 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
836 PyExc_ValueError);
837 return NULL;
838 }
839 Py_INCREF(o);
840 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000841}
842
843#if 0
844static PyObject *
845float_is_inf(PyObject *v)
846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 double x = PyFloat_AsDouble(v);
848 if (x == -1.0 && PyErr_Occurred())
849 return NULL;
850 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000851}
852
853static PyObject *
854float_is_nan(PyObject *v)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 double x = PyFloat_AsDouble(v);
857 if (x == -1.0 && PyErr_Occurred())
858 return NULL;
859 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000860}
861
862static PyObject *
863float_is_finite(PyObject *v)
864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 double x = PyFloat_AsDouble(v);
866 if (x == -1.0 && PyErr_Occurred())
867 return NULL;
868 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000869}
870#endif
871
872static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000873float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 double x = PyFloat_AsDouble(v);
876 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 (void)modf(x, &wholepart);
879 /* Try to get out cheap if this fits in a Python int. The attempt
880 * to cast to long must be protected, as C doesn't define what
881 * happens if the double is too big to fit in a long. Some rare
882 * systems raise an exception then (RISCOS was mentioned as one,
883 * and someone using a non-default option on Sun also bumped into
884 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
885 * still be vulnerable: if a long has more bits of precision than
886 * a double, casting MIN/MAX to double may yield an approximation,
887 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
888 * yield true from the C expression wholepart<=LONG_MAX, despite
889 * that wholepart is actually greater than LONG_MAX.
890 */
891 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
892 const long aslong = (long)wholepart;
893 return PyLong_FromLong(aslong);
894 }
895 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000896}
897
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000898/* double_round: rounds a finite double to the closest multiple of
899 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
900 ndigits <= 323). Returns a Python float, or sets a Python error and
901 returns NULL on failure (OverflowError and memory errors are possible). */
902
903#ifndef PY_NO_SHORT_FLOAT_REPR
904/* version of double_round that uses the correctly-rounded string<->double
905 conversions from Python/dtoa.c */
906
907static PyObject *
908double_round(double x, int ndigits) {
909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 double rounded;
911 Py_ssize_t buflen, mybuflen=100;
912 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
913 int decpt, sign;
914 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* round to a decimal string */
917 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
918 if (buf == NULL) {
919 PyErr_NoMemory();
920 return NULL;
921 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
924 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
925 buflen = buf_end - buf;
926 if (buflen + 8 > mybuflen) {
927 mybuflen = buflen+8;
928 mybuf = (char *)PyMem_Malloc(mybuflen);
929 if (mybuf == NULL) {
930 PyErr_NoMemory();
931 goto exit;
932 }
933 }
934 /* copy buf to mybuf, adding exponent, sign and leading 0 */
935 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
936 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* and convert the resulting string back to a double */
939 errno = 0;
940 rounded = _Py_dg_strtod(mybuf, NULL);
941 if (errno == ERANGE && fabs(rounded) >= 1.)
942 PyErr_SetString(PyExc_OverflowError,
943 "rounded value too large to represent");
944 else
945 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* done computing value; now clean up */
948 if (mybuf != shortbuf)
949 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000950 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 _Py_dg_freedtoa(buf);
952 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953}
954
955#else /* PY_NO_SHORT_FLOAT_REPR */
956
957/* fallback version, to be used when correctly rounded binary<->decimal
958 conversions aren't available */
959
960static PyObject *
961double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 double pow1, pow2, y, z;
963 if (ndigits >= 0) {
964 if (ndigits > 22) {
965 /* pow1 and pow2 are each safe from overflow, but
966 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
967 pow1 = pow(10.0, (double)(ndigits-22));
968 pow2 = 1e22;
969 }
970 else {
971 pow1 = pow(10.0, (double)ndigits);
972 pow2 = 1.0;
973 }
974 y = (x*pow1)*pow2;
975 /* if y overflows, then rounded value is exactly x */
976 if (!Py_IS_FINITE(y))
977 return PyFloat_FromDouble(x);
978 }
979 else {
980 pow1 = pow(10.0, (double)-ndigits);
981 pow2 = 1.0; /* unused; silences a gcc compiler warning */
982 y = x / pow1;
983 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 z = round(y);
986 if (fabs(y-z) == 0.5)
987 /* halfway between two integers; use round-half-even */
988 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (ndigits >= 0)
991 z = (z / pow2) / pow1;
992 else
993 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* if computation resulted in overflow, raise OverflowError */
996 if (!Py_IS_FINITE(z)) {
997 PyErr_SetString(PyExc_OverflowError,
998 "overflow occurred during round");
999 return NULL;
1000 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003}
1004
1005#endif /* PY_NO_SHORT_FLOAT_REPR */
1006
1007/* round a Python float v to the closest multiple of 10**-ndigits */
1008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001009static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001010float_round(PyObject *v, PyObject *args)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 double x, rounded;
1013 PyObject *o_ndigits = NULL;
1014 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 x = PyFloat_AsDouble(v);
1017 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1018 return NULL;
1019 if (o_ndigits == NULL) {
1020 /* single-argument round: round to nearest integer */
1021 rounded = round(x);
1022 if (fabs(x-rounded) == 0.5)
1023 /* halfway case: round to even */
1024 rounded = 2.0*round(x/2.0);
1025 return PyLong_FromDouble(rounded);
1026 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* interpret second argument as a Py_ssize_t; clips on overflow */
1029 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1030 if (ndigits == -1 && PyErr_Occurred())
1031 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 /* nans and infinities round to themselves */
1034 if (!Py_IS_FINITE(x))
1035 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1038 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1039 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001040#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1041#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (ndigits > NDIGITS_MAX)
1043 /* return x */
1044 return PyFloat_FromDouble(x);
1045 else if (ndigits < NDIGITS_MIN)
1046 /* return 0.0, but with sign of x */
1047 return PyFloat_FromDouble(0.0*x);
1048 else
1049 /* finite x, and ndigits is not unreasonably large */
1050 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001051#undef NDIGITS_MAX
1052#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001053}
1054
1055static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001056float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 if (PyFloat_CheckExact(v))
1059 Py_INCREF(v);
1060 else
1061 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1062 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063}
1064
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001065/* turn ASCII hex characters into integer values and vice versa */
1066
1067static char
1068char_from_hex(int x)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 assert(0 <= x && x < 16);
1071 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001072}
1073
1074static int
1075hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 int x;
1077 switch(c) {
1078 case '0':
1079 x = 0;
1080 break;
1081 case '1':
1082 x = 1;
1083 break;
1084 case '2':
1085 x = 2;
1086 break;
1087 case '3':
1088 x = 3;
1089 break;
1090 case '4':
1091 x = 4;
1092 break;
1093 case '5':
1094 x = 5;
1095 break;
1096 case '6':
1097 x = 6;
1098 break;
1099 case '7':
1100 x = 7;
1101 break;
1102 case '8':
1103 x = 8;
1104 break;
1105 case '9':
1106 x = 9;
1107 break;
1108 case 'a':
1109 case 'A':
1110 x = 10;
1111 break;
1112 case 'b':
1113 case 'B':
1114 x = 11;
1115 break;
1116 case 'c':
1117 case 'C':
1118 x = 12;
1119 break;
1120 case 'd':
1121 case 'D':
1122 x = 13;
1123 break;
1124 case 'e':
1125 case 'E':
1126 x = 14;
1127 break;
1128 case 'f':
1129 case 'F':
1130 x = 15;
1131 break;
1132 default:
1133 x = -1;
1134 break;
1135 }
1136 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001137}
1138
1139/* convert a float to a hexadecimal string */
1140
1141/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1142 of the form 4k+1. */
1143#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1144
1145static PyObject *
1146float_hex(PyObject *v)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 double x, m;
1149 int e, shift, i, si, esign;
1150 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1151 trailing NUL byte. */
1152 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1157 return float_str((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (x == 0.0) {
1160 if(copysign(1.0, x) == -1.0)
1161 return PyUnicode_FromString("-0x0.0p+0");
1162 else
1163 return PyUnicode_FromString("0x0.0p+0");
1164 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 m = frexp(fabs(x), &e);
1167 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1168 m = ldexp(m, shift);
1169 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 si = 0;
1172 s[si] = char_from_hex((int)m);
1173 si++;
1174 m -= (int)m;
1175 s[si] = '.';
1176 si++;
1177 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1178 m *= 16.0;
1179 s[si] = char_from_hex((int)m);
1180 si++;
1181 m -= (int)m;
1182 }
1183 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (e < 0) {
1186 esign = (int)'-';
1187 e = -e;
1188 }
1189 else
1190 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (x < 0.0)
1193 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1194 else
1195 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001196}
1197
1198PyDoc_STRVAR(float_hex_doc,
1199"float.hex() -> string\n\
1200\n\
1201Return a hexadecimal representation of a floating-point number.\n\
1202>>> (-0.1).hex()\n\
1203'-0x1.999999999999ap-4'\n\
1204>>> 3.14159.hex()\n\
1205'0x1.921f9f01b866ep+1'");
1206
1207/* Convert a hexadecimal string to a float. */
1208
1209static PyObject *
1210float_fromhex(PyObject *cls, PyObject *arg)
1211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *result_as_float, *result;
1213 double x;
1214 long exp, top_exp, lsb, key_digit;
1215 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1216 int half_eps, digit, round_up, negate=0;
1217 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /*
1220 * For the sake of simplicity and correctness, we impose an artificial
1221 * limit on ndigits, the total number of hex digits in the coefficient
1222 * The limit is chosen to ensure that, writing exp for the exponent,
1223 *
1224 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1225 * guaranteed to overflow (provided it's nonzero)
1226 *
1227 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1228 * guaranteed to underflow to 0.
1229 *
1230 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1231 * overflow in the calculation of exp and top_exp below.
1232 *
1233 * More specifically, ndigits is assumed to satisfy the following
1234 * inequalities:
1235 *
1236 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1237 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1238 *
1239 * If either of these inequalities is not satisfied, a ValueError is
1240 * raised. Otherwise, write x for the value of the hex string, and
1241 * assume x is nonzero. Then
1242 *
1243 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1244 *
1245 * Now if exp > LONG_MAX/2 then:
1246 *
1247 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1248 * = DBL_MAX_EXP
1249 *
1250 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1251 * double, so overflows. If exp < LONG_MIN/2, then
1252 *
1253 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1254 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1255 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1256 *
1257 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1258 * when converted to a C double.
1259 *
1260 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1261 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1262 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 s = _PyUnicode_AsStringAndSize(arg, &length);
1265 if (s == NULL)
1266 return NULL;
1267 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /********************
1270 * Parse the string *
1271 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* leading whitespace */
1274 while (Py_ISSPACE(*s))
1275 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 /* infinities and nans */
1278 x = _Py_parse_inf_or_nan(s, &coeff_end);
1279 if (coeff_end != s) {
1280 s = coeff_end;
1281 goto finished;
1282 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* optional sign */
1285 if (*s == '-') {
1286 s++;
1287 negate = 1;
1288 }
1289 else if (*s == '+')
1290 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* [0x] */
1293 s_store = s;
1294 if (*s == '0') {
1295 s++;
1296 if (*s == 'x' || *s == 'X')
1297 s++;
1298 else
1299 s = s_store;
1300 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* coefficient: <integer> [. <fraction>] */
1303 coeff_start = s;
1304 while (hex_from_char(*s) >= 0)
1305 s++;
1306 s_store = s;
1307 if (*s == '.') {
1308 s++;
1309 while (hex_from_char(*s) >= 0)
1310 s++;
1311 coeff_end = s-1;
1312 }
1313 else
1314 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /* ndigits = total # of hex digits; fdigits = # after point */
1317 ndigits = coeff_end - coeff_start;
1318 fdigits = coeff_end - s_store;
1319 if (ndigits == 0)
1320 goto parse_error;
1321 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1322 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1323 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* [p <exponent>] */
1326 if (*s == 'p' || *s == 'P') {
1327 s++;
1328 exp_start = s;
1329 if (*s == '-' || *s == '+')
1330 s++;
1331 if (!('0' <= *s && *s <= '9'))
1332 goto parse_error;
1333 s++;
1334 while ('0' <= *s && *s <= '9')
1335 s++;
1336 exp = strtol(exp_start, NULL, 10);
1337 }
1338 else
1339 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1343 coeff_end-(j) : \
1344 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /*******************************************
1347 * Compute rounded value of the hex string *
1348 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* Discard leading zeros, and catch extreme overflow and underflow */
1351 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1352 ndigits--;
1353 if (ndigits == 0 || exp < LONG_MIN/2) {
1354 x = 0.0;
1355 goto finished;
1356 }
1357 if (exp > LONG_MAX/2)
1358 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* Adjust exponent for fractional part. */
1361 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1364 top_exp = exp + 4*((long)ndigits - 1);
1365 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1366 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* catch almost all nonextreme cases of overflow and underflow here */
1369 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1370 x = 0.0;
1371 goto finished;
1372 }
1373 if (top_exp > DBL_MAX_EXP)
1374 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* lsb = exponent of least significant bit of the *rounded* value.
1377 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1378 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 x = 0.0;
1381 if (exp >= lsb) {
1382 /* no rounding required */
1383 for (i = ndigits-1; i >= 0; i--)
1384 x = 16.0*x + HEX_DIGIT(i);
1385 x = ldexp(x, (int)(exp));
1386 goto finished;
1387 }
1388 /* rounding required. key_digit is the index of the hex digit
1389 containing the first bit to be rounded away. */
1390 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1391 key_digit = (lsb - exp - 1) / 4;
1392 for (i = ndigits-1; i > key_digit; i--)
1393 x = 16.0*x + HEX_DIGIT(i);
1394 digit = HEX_DIGIT(key_digit);
1395 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1398 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1399 if ((digit & half_eps) != 0) {
1400 round_up = 0;
1401 if ((digit & (3*half_eps-1)) != 0 ||
1402 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1403 round_up = 1;
1404 else
1405 for (i = key_digit-1; i >= 0; i--)
1406 if (HEX_DIGIT(i) != 0) {
1407 round_up = 1;
1408 break;
1409 }
1410 if (round_up == 1) {
1411 x += 2*half_eps;
1412 if (top_exp == DBL_MAX_EXP &&
1413 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1414 /* overflow corner case: pre-rounded value <
1415 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1416 goto overflow_error;
1417 }
1418 }
1419 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001420
1421 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* optional trailing whitespace leading to the end of the string */
1423 while (Py_ISSPACE(*s))
1424 s++;
1425 if (s != s_end)
1426 goto parse_error;
1427 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1428 if (result_as_float == NULL)
1429 return NULL;
1430 result = PyObject_CallObject(cls, result_as_float);
1431 Py_DECREF(result_as_float);
1432 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001433
1434 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyErr_SetString(PyExc_OverflowError,
1436 "hexadecimal value too large to represent as a float");
1437 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001438
1439 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 PyErr_SetString(PyExc_ValueError,
1441 "invalid hexadecimal floating-point string");
1442 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443
1444 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyErr_SetString(PyExc_ValueError,
1446 "hexadecimal string too long to convert");
1447 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001448}
1449
1450PyDoc_STRVAR(float_fromhex_doc,
1451"float.fromhex(string) -> float\n\
1452\n\
1453Create a floating-point number from a hexadecimal string.\n\
1454>>> float.fromhex('0x1.ffffp10')\n\
14552047.984375\n\
1456>>> float.fromhex('-0x1p-1074')\n\
1457-4.9406564584124654e-324");
1458
1459
Christian Heimes26855632008-01-27 23:50:43 +00001460static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001461float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 double self;
1464 double float_part;
1465 int exponent;
1466 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *prev;
1469 PyObject *py_exponent = NULL;
1470 PyObject *numerator = NULL;
1471 PyObject *denominator = NULL;
1472 PyObject *result_pair = NULL;
1473 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001474
1475#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 prev = obj; \
1477 obj = call; \
1478 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (Py_IS_INFINITY(self)) {
1483 PyErr_SetString(PyExc_OverflowError,
1484 "Cannot pass infinity to float.as_integer_ratio.");
1485 return NULL;
1486 }
Christian Heimes26855632008-01-27 23:50:43 +00001487#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (Py_IS_NAN(self)) {
1489 PyErr_SetString(PyExc_ValueError,
1490 "Cannot pass NaN to float.as_integer_ratio.");
1491 return NULL;
1492 }
Christian Heimes26855632008-01-27 23:50:43 +00001493#endif
1494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1496 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1497 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1500 float_part *= 2.0;
1501 exponent--;
1502 }
1503 /* self == float_part * 2**exponent exactly and float_part is integral.
1504 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1505 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 numerator = PyLong_FromDouble(float_part);
1508 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 /* fold in 2**exponent */
1511 denominator = PyLong_FromLong(1);
1512 py_exponent = PyLong_FromLong(labs((long)exponent));
1513 if (py_exponent == NULL) goto error;
1514 INPLACE_UPDATE(py_exponent,
1515 long_methods->nb_lshift(denominator, py_exponent));
1516 if (py_exponent == NULL) goto error;
1517 if (exponent > 0) {
1518 INPLACE_UPDATE(numerator,
1519 long_methods->nb_multiply(numerator, py_exponent));
1520 if (numerator == NULL) goto error;
1521 }
1522 else {
1523 Py_DECREF(denominator);
1524 denominator = py_exponent;
1525 py_exponent = NULL;
1526 }
1527
1528 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001529
1530#undef INPLACE_UPDATE
1531error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 Py_XDECREF(py_exponent);
1533 Py_XDECREF(denominator);
1534 Py_XDECREF(numerator);
1535 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001536}
1537
1538PyDoc_STRVAR(float_as_integer_ratio_doc,
1539"float.as_integer_ratio() -> (int, int)\n"
1540"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001541"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1542"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001543"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001544"\n"
1545">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001546"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001547">>> (0.0).as_integer_ratio()\n"
1548"(0, 1)\n"
1549">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001550"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001551
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001552
Jeremy Hylton938ace62002-07-17 16:30:39 +00001553static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001554float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1555
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556static PyObject *
1557float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *x = Py_False; /* Integer zero */
1560 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (type != &PyFloat_Type)
1563 return float_subtype_new(type, args, kwds); /* Wimp out */
1564 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1565 return NULL;
1566 /* If it's a string, but not a string subclass, use
1567 PyFloat_FromString. */
1568 if (PyUnicode_CheckExact(x))
1569 return PyFloat_FromString(x);
1570 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571}
1572
Guido van Rossumbef14172001-08-29 15:47:46 +00001573/* Wimpy, slow approach to tp_new calls for subtypes of float:
1574 first create a regular float from whatever arguments we got,
1575 then allocate a subtype instance and initialize its ob_fval
1576 from the regular float. The regular float is then thrown away.
1577*/
1578static PyObject *
1579float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 assert(PyType_IsSubtype(type, &PyFloat_Type));
1584 tmp = float_new(&PyFloat_Type, args, kwds);
1585 if (tmp == NULL)
1586 return NULL;
1587 assert(PyFloat_CheckExact(tmp));
1588 newobj = type->tp_alloc(type, 0);
1589 if (newobj == NULL) {
1590 Py_DECREF(tmp);
1591 return NULL;
1592 }
1593 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1594 Py_DECREF(tmp);
1595 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001596}
1597
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001598static PyObject *
1599float_getnewargs(PyFloatObject *v)
1600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001602}
1603
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001604/* this is for the benefit of the pack/unpack routines below */
1605
1606typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001608} float_format_type;
1609
1610static float_format_type double_format, float_format;
1611static float_format_type detected_double_format, detected_float_format;
1612
1613static PyObject *
1614float_getformat(PyTypeObject *v, PyObject* arg)
1615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 char* s;
1617 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (!PyUnicode_Check(arg)) {
1620 PyErr_Format(PyExc_TypeError,
1621 "__getformat__() argument must be string, not %.500s",
1622 Py_TYPE(arg)->tp_name);
1623 return NULL;
1624 }
1625 s = _PyUnicode_AsString(arg);
1626 if (s == NULL)
1627 return NULL;
1628 if (strcmp(s, "double") == 0) {
1629 r = double_format;
1630 }
1631 else if (strcmp(s, "float") == 0) {
1632 r = float_format;
1633 }
1634 else {
1635 PyErr_SetString(PyExc_ValueError,
1636 "__getformat__() argument 1 must be "
1637 "'double' or 'float'");
1638 return NULL;
1639 }
1640
1641 switch (r) {
1642 case unknown_format:
1643 return PyUnicode_FromString("unknown");
1644 case ieee_little_endian_format:
1645 return PyUnicode_FromString("IEEE, little-endian");
1646 case ieee_big_endian_format:
1647 return PyUnicode_FromString("IEEE, big-endian");
1648 default:
1649 Py_FatalError("insane float_format or double_format");
1650 return NULL;
1651 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001652}
1653
1654PyDoc_STRVAR(float_getformat_doc,
1655"float.__getformat__(typestr) -> string\n"
1656"\n"
1657"You probably don't want to use this function. It exists mainly to be\n"
1658"used in Python's test suite.\n"
1659"\n"
1660"typestr must be 'double' or 'float'. This function returns whichever of\n"
1661"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1662"format of floating point numbers used by the C type named by typestr.");
1663
1664static PyObject *
1665float_setformat(PyTypeObject *v, PyObject* args)
1666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 char* typestr;
1668 char* format;
1669 float_format_type f;
1670 float_format_type detected;
1671 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1674 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 if (strcmp(typestr, "double") == 0) {
1677 p = &double_format;
1678 detected = detected_double_format;
1679 }
1680 else if (strcmp(typestr, "float") == 0) {
1681 p = &float_format;
1682 detected = detected_float_format;
1683 }
1684 else {
1685 PyErr_SetString(PyExc_ValueError,
1686 "__setformat__() argument 1 must "
1687 "be 'double' or 'float'");
1688 return NULL;
1689 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 if (strcmp(format, "unknown") == 0) {
1692 f = unknown_format;
1693 }
1694 else if (strcmp(format, "IEEE, little-endian") == 0) {
1695 f = ieee_little_endian_format;
1696 }
1697 else if (strcmp(format, "IEEE, big-endian") == 0) {
1698 f = ieee_big_endian_format;
1699 }
1700 else {
1701 PyErr_SetString(PyExc_ValueError,
1702 "__setformat__() argument 2 must be "
1703 "'unknown', 'IEEE, little-endian' or "
1704 "'IEEE, big-endian'");
1705 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (f != unknown_format && f != detected) {
1710 PyErr_Format(PyExc_ValueError,
1711 "can only set %s format to 'unknown' or the "
1712 "detected platform value", typestr);
1713 return NULL;
1714 }
1715
1716 *p = f;
1717 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001718}
1719
1720PyDoc_STRVAR(float_setformat_doc,
1721"float.__setformat__(typestr, fmt) -> None\n"
1722"\n"
1723"You probably don't want to use this function. It exists mainly to be\n"
1724"used in Python's test suite.\n"
1725"\n"
1726"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1727"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1728"one of the latter two if it appears to match the underlying C reality.\n"
1729"\n"
1730"Overrides the automatic determination of C-level floating point type.\n"
1731"This affects how floats are converted to and from binary strings.");
1732
Guido van Rossumb43daf72007-08-01 18:08:08 +00001733static PyObject *
1734float_getzero(PyObject *v, void *closure)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001737}
1738
Eric Smith8c663262007-08-25 02:26:07 +00001739static PyObject *
1740float__format__(PyObject *self, PyObject *args)
1741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1745 return NULL;
1746 return _PyFloat_FormatAdvanced(self,
1747 PyUnicode_AS_UNICODE(format_spec),
1748 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001749}
1750
1751PyDoc_STRVAR(float__format__doc,
1752"float.__format__(format_spec) -> string\n"
1753"\n"
1754"Formats the float according to format_spec.");
1755
1756
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001757static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1759 "Returns self, the complex conjugate of any float."},
1760 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1761 "Returns the Integral closest to x between 0 and x."},
1762 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1763 "Returns the Integral closest to x, rounding half toward even.\n"
1764 "When an argument is passed, works like built-in round(x, ndigits)."},
1765 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1766 float_as_integer_ratio_doc},
1767 {"fromhex", (PyCFunction)float_fromhex,
1768 METH_O|METH_CLASS, float_fromhex_doc},
1769 {"hex", (PyCFunction)float_hex,
1770 METH_NOARGS, float_hex_doc},
1771 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1772 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001773#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1775 "Returns True if the float is positive or negative infinite."},
1776 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1777 "Returns True if the float is finite, neither infinite nor NaN."},
1778 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1779 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001780#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1782 {"__getformat__", (PyCFunction)float_getformat,
1783 METH_O|METH_CLASS, float_getformat_doc},
1784 {"__setformat__", (PyCFunction)float_setformat,
1785 METH_VARARGS|METH_CLASS, float_setformat_doc},
1786 {"__format__", (PyCFunction)float__format__,
1787 METH_VARARGS, float__format__doc},
1788 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001789};
1790
Guido van Rossumb43daf72007-08-01 18:08:08 +00001791static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001793 (getter)float_float, (setter)NULL,
1794 "the real part of a complex number",
1795 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001797 (getter)float_getzero, (setter)NULL,
1798 "the imaginary part of a complex number",
1799 NULL},
1800 {NULL} /* Sentinel */
1801};
1802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804"float(x) -> floating point number\n\
1805\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
1808
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001809static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 float_add, /*nb_add*/
1811 float_sub, /*nb_subtract*/
1812 float_mul, /*nb_multiply*/
1813 float_rem, /*nb_remainder*/
1814 float_divmod, /*nb_divmod*/
1815 float_pow, /*nb_power*/
1816 (unaryfunc)float_neg, /*nb_negative*/
1817 (unaryfunc)float_float, /*nb_positive*/
1818 (unaryfunc)float_abs, /*nb_absolute*/
1819 (inquiry)float_bool, /*nb_bool*/
1820 0, /*nb_invert*/
1821 0, /*nb_lshift*/
1822 0, /*nb_rshift*/
1823 0, /*nb_and*/
1824 0, /*nb_xor*/
1825 0, /*nb_or*/
1826 float_trunc, /*nb_int*/
1827 0, /*nb_reserved*/
1828 float_float, /*nb_float*/
1829 0, /* nb_inplace_add */
1830 0, /* nb_inplace_subtract */
1831 0, /* nb_inplace_multiply */
1832 0, /* nb_inplace_remainder */
1833 0, /* nb_inplace_power */
1834 0, /* nb_inplace_lshift */
1835 0, /* nb_inplace_rshift */
1836 0, /* nb_inplace_and */
1837 0, /* nb_inplace_xor */
1838 0, /* nb_inplace_or */
1839 float_floor_div, /* nb_floor_divide */
1840 float_div, /* nb_true_divide */
1841 0, /* nb_inplace_floor_divide */
1842 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001843};
1844
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001845PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1847 "float",
1848 sizeof(PyFloatObject),
1849 0,
1850 (destructor)float_dealloc, /* tp_dealloc */
1851 0, /* tp_print */
1852 0, /* tp_getattr */
1853 0, /* tp_setattr */
1854 0, /* tp_reserved */
1855 (reprfunc)float_repr, /* tp_repr */
1856 &float_as_number, /* tp_as_number */
1857 0, /* tp_as_sequence */
1858 0, /* tp_as_mapping */
1859 (hashfunc)float_hash, /* tp_hash */
1860 0, /* tp_call */
1861 (reprfunc)float_str, /* tp_str */
1862 PyObject_GenericGetAttr, /* tp_getattro */
1863 0, /* tp_setattro */
1864 0, /* tp_as_buffer */
1865 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1866 float_doc, /* tp_doc */
1867 0, /* tp_traverse */
1868 0, /* tp_clear */
1869 float_richcompare, /* tp_richcompare */
1870 0, /* tp_weaklistoffset */
1871 0, /* tp_iter */
1872 0, /* tp_iternext */
1873 float_methods, /* tp_methods */
1874 0, /* tp_members */
1875 float_getset, /* tp_getset */
1876 0, /* tp_base */
1877 0, /* tp_dict */
1878 0, /* tp_descr_get */
1879 0, /* tp_descr_set */
1880 0, /* tp_dictoffset */
1881 0, /* tp_init */
1882 0, /* tp_alloc */
1883 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001884};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001885
1886void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887_PyFloat_Init(void)
1888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* We attempt to determine if this machine is using IEEE
1890 floating point formats by peering at the bits of some
1891 carefully chosen values. If it looks like we are on an
1892 IEEE platform, the float packing/unpacking routines can
1893 just copy bits, if not they resort to arithmetic & shifts
1894 and masks. The shifts & masks approach works on all finite
1895 values, but what happens to infinities, NaNs and signed
1896 zeroes on packing is an accident, and attempting to unpack
1897 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 Note that if we're on some whacked-out platform which uses
1900 IEEE formats but isn't strictly little-endian or big-
1901 endian, we will fall back to the portable shifts & masks
1902 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001903
1904#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 {
1906 double x = 9006104071832581.0;
1907 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1908 detected_double_format = ieee_big_endian_format;
1909 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1910 detected_double_format = ieee_little_endian_format;
1911 else
1912 detected_double_format = unknown_format;
1913 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001914#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001916#endif
1917
1918#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 {
1920 float y = 16711938.0;
1921 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1922 detected_float_format = ieee_big_endian_format;
1923 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1924 detected_float_format = ieee_little_endian_format;
1925 else
1926 detected_float_format = unknown_format;
1927 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001928#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930#endif
1931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 double_format = detected_double_format;
1933 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* Init float info */
1936 if (FloatInfoType.tp_name == 0)
1937 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001938}
1939
Georg Brandl2ee470f2008-07-16 12:55:28 +00001940int
1941PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 PyFloatObject *p;
1944 PyFloatBlock *list, *next;
1945 int i;
1946 int u; /* remaining unfreed floats per block */
1947 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 list = block_list;
1950 block_list = NULL;
1951 free_list = NULL;
1952 while (list != NULL) {
1953 u = 0;
1954 for (i = 0, p = &list->objects[0];
1955 i < N_FLOATOBJECTS;
1956 i++, p++) {
1957 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1958 u++;
1959 }
1960 next = list->next;
1961 if (u) {
1962 list->next = block_list;
1963 block_list = list;
1964 for (i = 0, p = &list->objects[0];
1965 i < N_FLOATOBJECTS;
1966 i++, p++) {
1967 if (!PyFloat_CheckExact(p) ||
1968 Py_REFCNT(p) == 0) {
1969 Py_TYPE(p) = (struct _typeobject *)
1970 free_list;
1971 free_list = p;
1972 }
1973 }
1974 }
1975 else {
1976 PyMem_FREE(list);
1977 }
1978 freelist_size += u;
1979 list = next;
1980 }
1981 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001982}
1983
1984void
1985PyFloat_Fini(void)
1986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 PyFloatObject *p;
1988 PyFloatBlock *list;
1989 int i;
1990 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (!Py_VerboseFlag)
1995 return;
1996 fprintf(stderr, "# cleanup floats");
1997 if (!u) {
1998 fprintf(stderr, "\n");
1999 }
2000 else {
2001 fprintf(stderr,
2002 ": %d unfreed float%s\n",
2003 u, u == 1 ? "" : "s");
2004 }
2005 if (Py_VerboseFlag > 1) {
2006 list = block_list;
2007 while (list != NULL) {
2008 for (i = 0, p = &list->objects[0];
2009 i < N_FLOATOBJECTS;
2010 i++, p++) {
2011 if (PyFloat_CheckExact(p) &&
2012 Py_REFCNT(p) != 0) {
2013 char *buf = PyOS_double_to_string(
2014 PyFloat_AS_DOUBLE(p), 'r',
2015 0, 0, NULL);
2016 if (buf) {
2017 /* XXX(twouters) cast
2018 refcount to long
2019 until %zd is
2020 universally
2021 available
2022 */
2023 fprintf(stderr,
2024 "# <float at %p, refcnt=%ld, val=%s>\n",
2025 p, (long)Py_REFCNT(p), buf);
2026 PyMem_Free(buf);
2027 }
2028 }
2029 }
2030 list = list->next;
2031 }
2032 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002033}
Tim Peters9905b942003-03-20 20:53:32 +00002034
2035/*----------------------------------------------------------------------------
2036 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002037 */
2038int
2039_PyFloat_Pack4(double x, unsigned char *p, int le)
2040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 if (float_format == unknown_format) {
2042 unsigned char sign;
2043 int e;
2044 double f;
2045 unsigned int fbits;
2046 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (le) {
2049 p += 3;
2050 incr = -1;
2051 }
Tim Peters9905b942003-03-20 20:53:32 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (x < 0) {
2054 sign = 1;
2055 x = -x;
2056 }
2057 else
2058 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* Normalize f to be in the range [1.0, 2.0) */
2063 if (0.5 <= f && f < 1.0) {
2064 f *= 2.0;
2065 e--;
2066 }
2067 else if (f == 0.0)
2068 e = 0;
2069 else {
2070 PyErr_SetString(PyExc_SystemError,
2071 "frexp() result out of range");
2072 return -1;
2073 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (e >= 128)
2076 goto Overflow;
2077 else if (e < -126) {
2078 /* Gradual underflow */
2079 f = ldexp(f, 126 + e);
2080 e = 0;
2081 }
2082 else if (!(e == 0 && f == 0.0)) {
2083 e += 127;
2084 f -= 1.0; /* Get rid of leading 1 */
2085 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 f *= 8388608.0; /* 2**23 */
2088 fbits = (unsigned int)(f + 0.5); /* Round */
2089 assert(fbits <= 8388608);
2090 if (fbits >> 23) {
2091 /* The carry propagated out of a string of 23 1 bits. */
2092 fbits = 0;
2093 ++e;
2094 if (e >= 255)
2095 goto Overflow;
2096 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* First byte */
2099 *p = (sign << 7) | (e >> 1);
2100 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* Second byte */
2103 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2104 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* Third byte */
2107 *p = (fbits >> 8) & 0xFF;
2108 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* Fourth byte */
2111 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 /* Done */
2114 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 }
2117 else {
2118 float y = (float)x;
2119 const char *s = (char*)&y;
2120 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2123 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if ((float_format == ieee_little_endian_format && !le)
2126 || (float_format == ieee_big_endian_format && le)) {
2127 p += 3;
2128 incr = -1;
2129 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 for (i = 0; i < 4; i++) {
2132 *p = *s++;
2133 p += incr;
2134 }
2135 return 0;
2136 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002137 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyErr_SetString(PyExc_OverflowError,
2139 "float too large to pack with f format");
2140 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002141}
2142
2143int
2144_PyFloat_Pack8(double x, unsigned char *p, int le)
2145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (double_format == unknown_format) {
2147 unsigned char sign;
2148 int e;
2149 double f;
2150 unsigned int fhi, flo;
2151 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (le) {
2154 p += 7;
2155 incr = -1;
2156 }
Tim Peters9905b942003-03-20 20:53:32 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (x < 0) {
2159 sign = 1;
2160 x = -x;
2161 }
2162 else
2163 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Normalize f to be in the range [1.0, 2.0) */
2168 if (0.5 <= f && f < 1.0) {
2169 f *= 2.0;
2170 e--;
2171 }
2172 else if (f == 0.0)
2173 e = 0;
2174 else {
2175 PyErr_SetString(PyExc_SystemError,
2176 "frexp() result out of range");
2177 return -1;
2178 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (e >= 1024)
2181 goto Overflow;
2182 else if (e < -1022) {
2183 /* Gradual underflow */
2184 f = ldexp(f, 1022 + e);
2185 e = 0;
2186 }
2187 else if (!(e == 0 && f == 0.0)) {
2188 e += 1023;
2189 f -= 1.0; /* Get rid of leading 1 */
2190 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2193 f *= 268435456.0; /* 2**28 */
2194 fhi = (unsigned int)f; /* Truncate */
2195 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 f -= (double)fhi;
2198 f *= 16777216.0; /* 2**24 */
2199 flo = (unsigned int)(f + 0.5); /* Round */
2200 assert(flo <= 16777216);
2201 if (flo >> 24) {
2202 /* The carry propagated out of a string of 24 1 bits. */
2203 flo = 0;
2204 ++fhi;
2205 if (fhi >> 28) {
2206 /* And it also progagated out of the next 28 bits. */
2207 fhi = 0;
2208 ++e;
2209 if (e >= 2047)
2210 goto Overflow;
2211 }
2212 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* First byte */
2215 *p = (sign << 7) | (e >> 4);
2216 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Second byte */
2219 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2220 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Third byte */
2223 *p = (fhi >> 16) & 0xFF;
2224 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Fourth byte */
2227 *p = (fhi >> 8) & 0xFF;
2228 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Fifth byte */
2231 *p = fhi & 0xFF;
2232 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Sixth byte */
2235 *p = (flo >> 16) & 0xFF;
2236 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Seventh byte */
2239 *p = (flo >> 8) & 0xFF;
2240 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Eighth byte */
2243 *p = flo & 0xFF;
2244 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Done */
2247 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 Overflow:
2250 PyErr_SetString(PyExc_OverflowError,
2251 "float too large to pack with d format");
2252 return -1;
2253 }
2254 else {
2255 const char *s = (char*)&x;
2256 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if ((double_format == ieee_little_endian_format && !le)
2259 || (double_format == ieee_big_endian_format && le)) {
2260 p += 7;
2261 incr = -1;
2262 }
2263
2264 for (i = 0; i < 8; i++) {
2265 *p = *s++;
2266 p += incr;
2267 }
2268 return 0;
2269 }
Tim Peters9905b942003-03-20 20:53:32 +00002270}
2271
2272double
2273_PyFloat_Unpack4(const unsigned char *p, int le)
2274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 if (float_format == unknown_format) {
2276 unsigned char sign;
2277 int e;
2278 unsigned int f;
2279 double x;
2280 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (le) {
2283 p += 3;
2284 incr = -1;
2285 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* First byte */
2288 sign = (*p >> 7) & 1;
2289 e = (*p & 0x7F) << 1;
2290 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 /* Second byte */
2293 e |= (*p >> 7) & 1;
2294 f = (*p & 0x7F) << 16;
2295 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (e == 255) {
2298 PyErr_SetString(
2299 PyExc_ValueError,
2300 "can't unpack IEEE 754 special value "
2301 "on non-IEEE platform");
2302 return -1;
2303 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Third byte */
2306 f |= *p << 8;
2307 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Fourth byte */
2310 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* XXX This sadly ignores Inf/NaN issues */
2315 if (e == 0)
2316 e = -126;
2317 else {
2318 x += 1.0;
2319 e -= 127;
2320 }
2321 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (sign)
2324 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 return x;
2327 }
2328 else {
2329 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if ((float_format == ieee_little_endian_format && !le)
2332 || (float_format == ieee_big_endian_format && le)) {
2333 char buf[4];
2334 char *d = &buf[3];
2335 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 for (i = 0; i < 4; i++) {
2338 *d-- = *p++;
2339 }
2340 memcpy(&x, buf, 4);
2341 }
2342 else {
2343 memcpy(&x, p, 4);
2344 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 return x;
2347 }
Tim Peters9905b942003-03-20 20:53:32 +00002348}
2349
2350double
2351_PyFloat_Unpack8(const unsigned char *p, int le)
2352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 if (double_format == unknown_format) {
2354 unsigned char sign;
2355 int e;
2356 unsigned int fhi, flo;
2357 double x;
2358 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 if (le) {
2361 p += 7;
2362 incr = -1;
2363 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* First byte */
2366 sign = (*p >> 7) & 1;
2367 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* Second byte */
2372 e |= (*p >> 4) & 0xF;
2373 fhi = (*p & 0xF) << 24;
2374 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 if (e == 2047) {
2377 PyErr_SetString(
2378 PyExc_ValueError,
2379 "can't unpack IEEE 754 special value "
2380 "on non-IEEE platform");
2381 return -1.0;
2382 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* Third byte */
2385 fhi |= *p << 16;
2386 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* Fourth byte */
2389 fhi |= *p << 8;
2390 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Fifth byte */
2393 fhi |= *p;
2394 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* Sixth byte */
2397 flo = *p << 16;
2398 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Seventh byte */
2401 flo |= *p << 8;
2402 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* Eighth byte */
2405 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2408 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (e == 0)
2411 e = -1022;
2412 else {
2413 x += 1.0;
2414 e -= 1023;
2415 }
2416 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (sign)
2419 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 return x;
2422 }
2423 else {
2424 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 if ((double_format == ieee_little_endian_format && !le)
2427 || (double_format == ieee_big_endian_format && le)) {
2428 char buf[8];
2429 char *d = &buf[7];
2430 int i;
2431
2432 for (i = 0; i < 8; i++) {
2433 *d-- = *p++;
2434 }
2435 memcpy(&x, buf, 8);
2436 }
2437 else {
2438 memcpy(&x, p, 8);
2439 }
2440
2441 return x;
2442 }
Tim Peters9905b942003-03-20 20:53:32 +00002443}