blob: d0173e8d1340c1b8eee9dc52d8b2a0212cd78b21 [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
Mark Dickinsond19052c2010-06-27 18:19:09 +000024/* Special free list
25
26 Since some Python programs can spend much of their time allocating
27 and deallocating floats, these operations should be very fast.
28 Therefore we use a dedicated allocation scheme with a much lower
29 overhead (in space and time) than straight malloc(): a simple
30 dedicated free list, filled when necessary with memory from malloc().
31
32 block_list is a singly-linked list of all PyFloatBlocks ever allocated,
33 linked via their next members. PyFloatBlocks are never returned to the
34 system before shutdown (PyFloat_Fini).
35
36 free_list is a singly-linked list of available PyFloatObjects, linked
37 via abuse of their ob_type members.
38*/
39
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
41#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
42#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000043
Guido van Rossum3fce8831999-03-12 19:43:17 +000044struct _floatblock {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 struct _floatblock *next;
46 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000047};
48
49typedef struct _floatblock PyFloatBlock;
50
51static PyFloatBlock *block_list = NULL;
52static PyFloatObject *free_list = NULL;
53
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000055fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 PyFloatObject *p, *q;
58 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
59 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
60 if (p == NULL)
61 return (PyFloatObject *) PyErr_NoMemory();
62 ((PyFloatBlock *)p)->next = block_list;
63 block_list = (PyFloatBlock *)p;
64 p = &((PyFloatBlock *)p)->objects[0];
65 q = p + N_FLOATOBJECTS;
66 while (--q > p)
67 Py_TYPE(q) = (struct _typeobject *)(q-1);
68 Py_TYPE(q) = NULL;
69 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000070}
71
Christian Heimes93852662007-12-01 12:22:32 +000072double
73PyFloat_GetMax(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000076}
77
78double
79PyFloat_GetMin(void)
80{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000082}
83
Christian Heimesd32ed6f2008-01-14 18:49:24 +000084static PyTypeObject FloatInfoType;
85
86PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000087"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000088\n\
89A structseq holding information about the float type. It contains low level\n\
90information about the precision and internal representation. Please study\n\
91your system's :file:`float.h` for more information.");
92
93static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 {"max", "DBL_MAX -- maximum representable finite float"},
95 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
96 "is representable"},
97 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
98 "is representable"},
99 {"min", "DBL_MIN -- Minimum positive normalizer float"},
100 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
101 "is a normalized float"},
102 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
103 "a normalized"},
104 {"dig", "DBL_DIG -- digits"},
105 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
106 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
107 "representable float"},
108 {"radix", "FLT_RADIX -- radix of exponent"},
109 {"rounds", "FLT_ROUNDS -- addition rounds"},
110 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000111};
112
113static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 "sys.float_info", /* name */
115 floatinfo__doc__, /* doc */
116 floatinfo_fields, /* fields */
117 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000118};
119
Christian Heimes93852662007-12-01 12:22:32 +0000120PyObject *
121PyFloat_GetInfo(void)
122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject* floatinfo;
124 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 floatinfo = PyStructSequence_New(&FloatInfoType);
127 if (floatinfo == NULL) {
128 return NULL;
129 }
Christian Heimes93852662007-12-01 12:22:32 +0000130
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000131#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000133#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 SetDblFlag(DBL_MAX);
137 SetIntFlag(DBL_MAX_EXP);
138 SetIntFlag(DBL_MAX_10_EXP);
139 SetDblFlag(DBL_MIN);
140 SetIntFlag(DBL_MIN_EXP);
141 SetIntFlag(DBL_MIN_10_EXP);
142 SetIntFlag(DBL_DIG);
143 SetIntFlag(DBL_MANT_DIG);
144 SetDblFlag(DBL_EPSILON);
145 SetIntFlag(FLT_RADIX);
146 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000147#undef SetIntFlag
148#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149
150 if (PyErr_Occurred()) {
151 Py_CLEAR(floatinfo);
152 return NULL;
153 }
154 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000155}
156
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 register PyFloatObject *op;
161 if (free_list == NULL) {
162 if ((free_list = fill_free_list()) == NULL)
163 return NULL;
164 }
165 /* Inline PyObject_New */
166 op = free_list;
167 free_list = (PyFloatObject *)Py_TYPE(op);
168 PyObject_INIT(op, &PyFloat_Type);
169 op->ob_fval = fval;
170 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171}
172
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000174PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 const char *s, *last, *end;
177 double x;
178 char buffer[256]; /* for errors */
179 char *s_buffer = NULL;
180 Py_ssize_t len;
181 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 if (PyUnicode_Check(v)) {
184 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
185 if (s_buffer == NULL)
186 return PyErr_NoMemory();
187 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
188 PyUnicode_GET_SIZE(v),
189 s_buffer,
190 NULL))
191 goto error;
192 s = s_buffer;
193 len = strlen(s);
194 }
195 else if (PyObject_AsCharBuffer(v, &s, &len)) {
196 PyErr_SetString(PyExc_TypeError,
197 "float() argument must be a string or a number");
198 return NULL;
199 }
200 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 while (Py_ISSPACE(*s))
203 s++;
204 /* We don't care about overflow or underflow. If the platform
205 * supports them, infinities and signed zeroes (on underflow) are
206 * fine. */
207 x = PyOS_string_to_double(s, (char **)&end, NULL);
208 if (x == -1.0 && PyErr_Occurred())
209 goto error;
210 while (Py_ISSPACE(*end))
211 end++;
212 if (end == last)
213 result = PyFloat_FromDouble(x);
214 else {
215 PyOS_snprintf(buffer, sizeof(buffer),
216 "invalid literal for float(): %.200s", s);
217 PyErr_SetString(PyExc_ValueError, buffer);
218 result = NULL;
219 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000220
Guido van Rossum2be161d2007-05-15 20:43:51 +0000221 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (s_buffer)
223 PyMem_FREE(s_buffer);
224 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000225}
226
Guido van Rossum234f9421993-06-17 12:35:49 +0000227static void
Fred Drakefd99de62000-07-09 05:02:18 +0000228float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (PyFloat_CheckExact(op)) {
231 Py_TYPE(op) = (struct _typeobject *)free_list;
232 free_list = op;
233 }
234 else
235 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000236}
237
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238double
Fred Drakefd99de62000-07-09 05:02:18 +0000239PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyNumberMethods *nb;
242 PyFloatObject *fo;
243 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (op && PyFloat_Check(op))
246 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (op == NULL) {
249 PyErr_BadArgument();
250 return -1;
251 }
Tim Petersd2364e82001-11-01 20:09:42 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
254 PyErr_SetString(PyExc_TypeError, "a float is required");
255 return -1;
256 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 fo = (PyFloatObject*) (*nb->nb_float) (op);
259 if (fo == NULL)
260 return -1;
261 if (!PyFloat_Check(fo)) {
262 PyErr_SetString(PyExc_TypeError,
263 "nb_float should return float object");
264 return -1;
265 }
Tim Petersd2364e82001-11-01 20:09:42 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 val = PyFloat_AS_DOUBLE(fo);
268 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271}
272
Neil Schemenauer32117e52001-01-04 01:44:34 +0000273/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000274 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000275 set to NULL, and the function invoking this macro returns NULL. If
276 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
277 stored in obj, and returned from the function invoking this macro.
278*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279#define CONVERT_TO_DOUBLE(obj, dbl) \
280 if (PyFloat_Check(obj)) \
281 dbl = PyFloat_AS_DOUBLE(obj); \
282 else if (convert_to_double(&(obj), &(dbl)) < 0) \
283 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000284
Eric Smith0923d1d2009-04-16 20:16:10 +0000285/* Methods */
286
Neil Schemenauer32117e52001-01-04 01:44:34 +0000287static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000288convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (PyLong_Check(obj)) {
293 *dbl = PyLong_AsDouble(obj);
294 if (*dbl == -1.0 && PyErr_Occurred()) {
295 *v = NULL;
296 return -1;
297 }
298 }
299 else {
300 Py_INCREF(Py_NotImplemented);
301 *v = Py_NotImplemented;
302 return -1;
303 }
304 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000305}
306
Eric Smith0923d1d2009-04-16 20:16:10 +0000307static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000308float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000309{
310 PyObject *result;
311 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000312 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000313 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000314 NULL);
315 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000316 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000317 result = PyUnicode_FromString(buf);
318 PyMem_Free(buf);
319 return result;
320}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000321
Tim Peters307fa782004-09-23 08:06:40 +0000322/* Comparison is pretty much a nightmare. When comparing float to float,
323 * we do it as straightforwardly (and long-windedly) as conceivable, so
324 * that, e.g., Python x == y delivers the same result as the platform
325 * C x == y when x and/or y is a NaN.
326 * When mixing float with an integer type, there's no good *uniform* approach.
327 * Converting the double to an integer obviously doesn't work, since we
328 * may lose info from fractional bits. Converting the integer to a double
329 * also has two failure modes: (1) a long int may trigger overflow (too
330 * large to fit in the dynamic range of a C double); (2) even a C long may have
331 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
332 * 63 bits of precision, but a C double probably has only 53), and then
333 * we can falsely claim equality when low-order integer bits are lost by
334 * coercion to double. So this part is painful too.
335 */
336
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000337static PyObject*
338float_richcompare(PyObject *v, PyObject *w, int op)
339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 double i, j;
341 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 assert(PyFloat_Check(v));
344 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Switch on the type of w. Set i and j to doubles to be compared,
347 * and op to the richcomp to use.
348 */
349 if (PyFloat_Check(w))
350 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 else if (!Py_IS_FINITE(i)) {
353 if (PyLong_Check(w))
354 /* If i is an infinity, its magnitude exceeds any
355 * finite integer, so it doesn't matter which int we
356 * compare i with. If i is a NaN, similarly.
357 */
358 j = 0.0;
359 else
360 goto Unimplemented;
361 }
Tim Peters307fa782004-09-23 08:06:40 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 else if (PyLong_Check(w)) {
364 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
365 int wsign = _PyLong_Sign(w);
366 size_t nbits;
367 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (vsign != wsign) {
370 /* Magnitudes are irrelevant -- the signs alone
371 * determine the outcome.
372 */
373 i = (double)vsign;
374 j = (double)wsign;
375 goto Compare;
376 }
377 /* The signs are the same. */
378 /* Convert w to a double if it fits. In particular, 0 fits. */
379 nbits = _PyLong_NumBits(w);
380 if (nbits == (size_t)-1 && PyErr_Occurred()) {
381 /* This long is so large that size_t isn't big enough
382 * to hold the # of bits. Replace with little doubles
383 * that give the same outcome -- w is so large that
384 * its magnitude must exceed the magnitude of any
385 * finite float.
386 */
387 PyErr_Clear();
388 i = (double)vsign;
389 assert(wsign != 0);
390 j = wsign * 2.0;
391 goto Compare;
392 }
393 if (nbits <= 48) {
394 j = PyLong_AsDouble(w);
395 /* It's impossible that <= 48 bits overflowed. */
396 assert(j != -1.0 || ! PyErr_Occurred());
397 goto Compare;
398 }
399 assert(wsign != 0); /* else nbits was 0 */
400 assert(vsign != 0); /* if vsign were 0, then since wsign is
401 * not 0, we would have taken the
402 * vsign != wsign branch at the start */
403 /* We want to work with non-negative numbers. */
404 if (vsign < 0) {
405 /* "Multiply both sides" by -1; this also swaps the
406 * comparator.
407 */
408 i = -i;
409 op = _Py_SwappedOp[op];
410 }
411 assert(i > 0.0);
412 (void) frexp(i, &exponent);
413 /* exponent is the # of bits in v before the radix point;
414 * we know that nbits (the # of bits in w) > 48 at this point
415 */
416 if (exponent < 0 || (size_t)exponent < nbits) {
417 i = 1.0;
418 j = 2.0;
419 goto Compare;
420 }
421 if ((size_t)exponent > nbits) {
422 i = 2.0;
423 j = 1.0;
424 goto Compare;
425 }
426 /* v and w have the same number of bits before the radix
427 * point. Construct two longs that have the same comparison
428 * outcome.
429 */
430 {
431 double fracpart;
432 double intpart;
433 PyObject *result = NULL;
434 PyObject *one = NULL;
435 PyObject *vv = NULL;
436 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (wsign < 0) {
439 ww = PyNumber_Negative(w);
440 if (ww == NULL)
441 goto Error;
442 }
443 else
444 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 fracpart = modf(i, &intpart);
447 vv = PyLong_FromDouble(intpart);
448 if (vv == NULL)
449 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (fracpart != 0.0) {
452 /* Shift left, and or a 1 bit into vv
453 * to represent the lost fraction.
454 */
455 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 one = PyLong_FromLong(1);
458 if (one == NULL)
459 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 temp = PyNumber_Lshift(ww, one);
462 if (temp == NULL)
463 goto Error;
464 Py_DECREF(ww);
465 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 temp = PyNumber_Lshift(vv, one);
468 if (temp == NULL)
469 goto Error;
470 Py_DECREF(vv);
471 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 temp = PyNumber_Or(vv, one);
474 if (temp == NULL)
475 goto Error;
476 Py_DECREF(vv);
477 vv = temp;
478 }
Tim Peters307fa782004-09-23 08:06:40 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 r = PyObject_RichCompareBool(vv, ww, op);
481 if (r < 0)
482 goto Error;
483 result = PyBool_FromLong(r);
484 Error:
485 Py_XDECREF(vv);
486 Py_XDECREF(ww);
487 Py_XDECREF(one);
488 return result;
489 }
490 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 else /* w isn't float, int, or long */
493 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000494
495 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 PyFPE_START_PROTECT("richcompare", return NULL)
497 switch (op) {
498 case Py_EQ:
499 r = i == j;
500 break;
501 case Py_NE:
502 r = i != j;
503 break;
504 case Py_LE:
505 r = i <= j;
506 break;
507 case Py_GE:
508 r = i >= j;
509 break;
510 case Py_LT:
511 r = i < j;
512 break;
513 case Py_GT:
514 r = i > j;
515 break;
516 }
517 PyFPE_END_PROTECT(r)
518 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000519
520 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 Py_INCREF(Py_NotImplemented);
522 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000523}
524
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000525static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000526float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000529}
530
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000531static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000532float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 double a,b;
535 CONVERT_TO_DOUBLE(v, a);
536 CONVERT_TO_DOUBLE(w, b);
537 PyFPE_START_PROTECT("add", return 0)
538 a = a + b;
539 PyFPE_END_PROTECT(a)
540 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541}
542
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000544float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 double a,b;
547 CONVERT_TO_DOUBLE(v, a);
548 CONVERT_TO_DOUBLE(w, b);
549 PyFPE_START_PROTECT("subtract", return 0)
550 a = a - b;
551 PyFPE_END_PROTECT(a)
552 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000556float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 double a,b;
559 CONVERT_TO_DOUBLE(v, a);
560 CONVERT_TO_DOUBLE(w, b);
561 PyFPE_START_PROTECT("multiply", return 0)
562 a = a * b;
563 PyFPE_END_PROTECT(a)
564 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565}
566
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000568float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 double a,b;
571 CONVERT_TO_DOUBLE(v, a);
572 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000573#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (b == 0.0) {
575 PyErr_SetString(PyExc_ZeroDivisionError,
576 "float division by zero");
577 return NULL;
578 }
Christian Heimes53876d92008-04-19 00:31:39 +0000579#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyFPE_START_PROTECT("divide", return 0)
581 a = a / b;
582 PyFPE_END_PROTECT(a)
583 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584}
585
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000587float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 double vx, wx;
590 double mod;
591 CONVERT_TO_DOUBLE(v, vx);
592 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000593#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (wx == 0.0) {
595 PyErr_SetString(PyExc_ZeroDivisionError,
596 "float modulo");
597 return NULL;
598 }
Christian Heimes53876d92008-04-19 00:31:39 +0000599#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyFPE_START_PROTECT("modulo", return 0)
601 mod = fmod(vx, wx);
602 /* note: checking mod*wx < 0 is incorrect -- underflows to
603 0 if wx < sqrt(smallest nonzero double) */
604 if (mod && ((wx < 0) != (mod < 0))) {
605 mod += wx;
606 }
607 PyFPE_END_PROTECT(mod)
608 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609}
610
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000612float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 double vx, wx;
615 double div, mod, floordiv;
616 CONVERT_TO_DOUBLE(v, vx);
617 CONVERT_TO_DOUBLE(w, wx);
618 if (wx == 0.0) {
619 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
620 return NULL;
621 }
622 PyFPE_START_PROTECT("divmod", return 0)
623 mod = fmod(vx, wx);
624 /* fmod is typically exact, so vx-mod is *mathematically* an
625 exact multiple of wx. But this is fp arithmetic, and fp
626 vx - mod is an approximation; the result is that div may
627 not be an exact integral value after the division, although
628 it will always be very close to one.
629 */
630 div = (vx - mod) / wx;
631 if (mod) {
632 /* ensure the remainder has the same sign as the denominator */
633 if ((wx < 0) != (mod < 0)) {
634 mod += wx;
635 div -= 1.0;
636 }
637 }
638 else {
639 /* the remainder is zero, and in the presence of signed zeroes
640 fmod returns different results across platforms; ensure
641 it has the same sign as the denominator; we'd like to do
642 "mod = wx * 0.0", but that may get optimized away */
643 mod *= mod; /* hide "mod = +0" from optimizer */
644 if (wx < 0.0)
645 mod = -mod;
646 }
647 /* snap quotient to nearest integral value */
648 if (div) {
649 floordiv = floor(div);
650 if (div - floordiv > 0.5)
651 floordiv += 1.0;
652 }
653 else {
654 /* div is zero - get the same sign as the true quotient */
655 div *= div; /* hide "div = +0" from optimizers */
656 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
657 }
658 PyFPE_END_PROTECT(floordiv)
659 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000660}
661
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000663float_floor_div(PyObject *v, PyObject *w)
664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 t = float_divmod(v, w);
668 if (t == NULL || t == Py_NotImplemented)
669 return t;
670 assert(PyTuple_CheckExact(t));
671 r = PyTuple_GET_ITEM(t, 0);
672 Py_INCREF(r);
673 Py_DECREF(t);
674 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000675}
676
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000677/* determine whether x is an odd integer or not; assumes that
678 x is not an infinity or nan. */
679#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
680
Tim Peters63a35712001-12-11 19:57:24 +0000681static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000682float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 double iv, iw, ix;
685 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if ((PyObject *)z != Py_None) {
688 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
689 "allowed unless all arguments are integers");
690 return NULL;
691 }
Tim Peters32f453e2001-09-03 08:35:41 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 CONVERT_TO_DOUBLE(v, iv);
694 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* Sort out special cases here instead of relying on pow() */
697 if (iw == 0) { /* v**0 is 1, even 0**0 */
698 return PyFloat_FromDouble(1.0);
699 }
700 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
701 return PyFloat_FromDouble(iv);
702 }
703 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
704 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
705 }
706 if (Py_IS_INFINITY(iw)) {
707 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
708 * abs(v) > 1 (including case where v infinite)
709 *
710 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
711 * abs(v) > 1 (including case where v infinite)
712 */
713 iv = fabs(iv);
714 if (iv == 1.0)
715 return PyFloat_FromDouble(1.0);
716 else if ((iw > 0.0) == (iv > 1.0))
717 return PyFloat_FromDouble(fabs(iw)); /* return inf */
718 else
719 return PyFloat_FromDouble(0.0);
720 }
721 if (Py_IS_INFINITY(iv)) {
722 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
723 * both cases, we need to add the appropriate sign if w is
724 * an odd integer.
725 */
726 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
727 if (iw > 0.0)
728 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
729 else
730 return PyFloat_FromDouble(iw_is_odd ?
731 copysign(0.0, iv) : 0.0);
732 }
733 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
734 (already dealt with above), and an error
735 if w is negative. */
736 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
737 if (iw < 0.0) {
738 PyErr_SetString(PyExc_ZeroDivisionError,
739 "0.0 cannot be raised to a "
740 "negative power");
741 return NULL;
742 }
743 /* use correct sign if iw is odd */
744 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
745 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (iv < 0.0) {
748 /* Whether this is an error is a mess, and bumps into libm
749 * bugs so we have to figure it out ourselves.
750 */
751 if (iw != floor(iw)) {
752 /* Negative numbers raised to fractional powers
753 * become complex.
754 */
755 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
756 }
757 /* iw is an exact integer, albeit perhaps a very large
758 * one. Replace iv by its absolute value and remember
759 * to negate the pow result if iw is odd.
760 */
761 iv = -iv;
762 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
763 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
766 /* (-1) ** large_integer also ends up here. Here's an
767 * extract from the comments for the previous
768 * implementation explaining why this special case is
769 * necessary:
770 *
771 * -1 raised to an exact integer should never be exceptional.
772 * Alas, some libms (chiefly glibc as of early 2003) return
773 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
774 * happen to be representable in a *C* integer. That's a
775 * bug.
776 */
777 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
778 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 /* Now iv and iw are finite, iw is nonzero, and iv is
781 * positive and not equal to 1.0. We finally allow
782 * the platform pow to step in and do the rest.
783 */
784 errno = 0;
785 PyFPE_START_PROTECT("pow", return NULL)
786 ix = pow(iv, iw);
787 PyFPE_END_PROTECT(ix)
788 Py_ADJUST_ERANGE1(ix);
789 if (negate_result)
790 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (errno != 0) {
793 /* We don't expect any errno value other than ERANGE, but
794 * the range of libm bugs appears unbounded.
795 */
796 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
797 PyExc_ValueError);
798 return NULL;
799 }
800 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801}
802
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000803#undef DOUBLE_IS_ODD_INTEGER
804
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000805static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000806float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809}
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000812float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815}
816
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000817static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000818float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000821}
822
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000823static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000824float_is_integer(PyObject *v)
825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 double x = PyFloat_AsDouble(v);
827 PyObject *o;
828
829 if (x == -1.0 && PyErr_Occurred())
830 return NULL;
831 if (!Py_IS_FINITE(x))
832 Py_RETURN_FALSE;
833 errno = 0;
834 PyFPE_START_PROTECT("is_integer", return NULL)
835 o = (floor(x) == x) ? Py_True : Py_False;
836 PyFPE_END_PROTECT(x)
837 if (errno != 0) {
838 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
839 PyExc_ValueError);
840 return NULL;
841 }
842 Py_INCREF(o);
843 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000844}
845
846#if 0
847static PyObject *
848float_is_inf(PyObject *v)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 double x = PyFloat_AsDouble(v);
851 if (x == -1.0 && PyErr_Occurred())
852 return NULL;
853 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000854}
855
856static PyObject *
857float_is_nan(PyObject *v)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 double x = PyFloat_AsDouble(v);
860 if (x == -1.0 && PyErr_Occurred())
861 return NULL;
862 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000863}
864
865static PyObject *
866float_is_finite(PyObject *v)
867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 double x = PyFloat_AsDouble(v);
869 if (x == -1.0 && PyErr_Occurred())
870 return NULL;
871 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000872}
873#endif
874
875static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000876float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 double x = PyFloat_AsDouble(v);
879 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 (void)modf(x, &wholepart);
882 /* Try to get out cheap if this fits in a Python int. The attempt
883 * to cast to long must be protected, as C doesn't define what
884 * happens if the double is too big to fit in a long. Some rare
885 * systems raise an exception then (RISCOS was mentioned as one,
886 * and someone using a non-default option on Sun also bumped into
887 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
888 * still be vulnerable: if a long has more bits of precision than
889 * a double, casting MIN/MAX to double may yield an approximation,
890 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
891 * yield true from the C expression wholepart<=LONG_MAX, despite
892 * that wholepart is actually greater than LONG_MAX.
893 */
894 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
895 const long aslong = (long)wholepart;
896 return PyLong_FromLong(aslong);
897 }
898 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000899}
900
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000901/* double_round: rounds a finite double to the closest multiple of
902 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
903 ndigits <= 323). Returns a Python float, or sets a Python error and
904 returns NULL on failure (OverflowError and memory errors are possible). */
905
906#ifndef PY_NO_SHORT_FLOAT_REPR
907/* version of double_round that uses the correctly-rounded string<->double
908 conversions from Python/dtoa.c */
909
910static PyObject *
911double_round(double x, int ndigits) {
912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 double rounded;
914 Py_ssize_t buflen, mybuflen=100;
915 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
916 int decpt, sign;
917 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* round to a decimal string */
920 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
921 if (buf == NULL) {
922 PyErr_NoMemory();
923 return NULL;
924 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
927 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
928 buflen = buf_end - buf;
929 if (buflen + 8 > mybuflen) {
930 mybuflen = buflen+8;
931 mybuf = (char *)PyMem_Malloc(mybuflen);
932 if (mybuf == NULL) {
933 PyErr_NoMemory();
934 goto exit;
935 }
936 }
937 /* copy buf to mybuf, adding exponent, sign and leading 0 */
938 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
939 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* and convert the resulting string back to a double */
942 errno = 0;
943 rounded = _Py_dg_strtod(mybuf, NULL);
944 if (errno == ERANGE && fabs(rounded) >= 1.)
945 PyErr_SetString(PyExc_OverflowError,
946 "rounded value too large to represent");
947 else
948 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* done computing value; now clean up */
951 if (mybuf != shortbuf)
952 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 _Py_dg_freedtoa(buf);
955 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000956}
957
958#else /* PY_NO_SHORT_FLOAT_REPR */
959
960/* fallback version, to be used when correctly rounded binary<->decimal
961 conversions aren't available */
962
963static PyObject *
964double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 double pow1, pow2, y, z;
966 if (ndigits >= 0) {
967 if (ndigits > 22) {
968 /* pow1 and pow2 are each safe from overflow, but
969 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
970 pow1 = pow(10.0, (double)(ndigits-22));
971 pow2 = 1e22;
972 }
973 else {
974 pow1 = pow(10.0, (double)ndigits);
975 pow2 = 1.0;
976 }
977 y = (x*pow1)*pow2;
978 /* if y overflows, then rounded value is exactly x */
979 if (!Py_IS_FINITE(y))
980 return PyFloat_FromDouble(x);
981 }
982 else {
983 pow1 = pow(10.0, (double)-ndigits);
984 pow2 = 1.0; /* unused; silences a gcc compiler warning */
985 y = x / pow1;
986 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 z = round(y);
989 if (fabs(y-z) == 0.5)
990 /* halfway between two integers; use round-half-even */
991 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (ndigits >= 0)
994 z = (z / pow2) / pow1;
995 else
996 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* if computation resulted in overflow, raise OverflowError */
999 if (!Py_IS_FINITE(z)) {
1000 PyErr_SetString(PyExc_OverflowError,
1001 "overflow occurred during round");
1002 return NULL;
1003 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006}
1007
1008#endif /* PY_NO_SHORT_FLOAT_REPR */
1009
1010/* round a Python float v to the closest multiple of 10**-ndigits */
1011
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001012static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001013float_round(PyObject *v, PyObject *args)
1014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 double x, rounded;
1016 PyObject *o_ndigits = NULL;
1017 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 x = PyFloat_AsDouble(v);
1020 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1021 return NULL;
1022 if (o_ndigits == NULL) {
1023 /* single-argument round: round to nearest integer */
1024 rounded = round(x);
1025 if (fabs(x-rounded) == 0.5)
1026 /* halfway case: round to even */
1027 rounded = 2.0*round(x/2.0);
1028 return PyLong_FromDouble(rounded);
1029 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* interpret second argument as a Py_ssize_t; clips on overflow */
1032 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1033 if (ndigits == -1 && PyErr_Occurred())
1034 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* nans and infinities round to themselves */
1037 if (!Py_IS_FINITE(x))
1038 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1041 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1042 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001043#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1044#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (ndigits > NDIGITS_MAX)
1046 /* return x */
1047 return PyFloat_FromDouble(x);
1048 else if (ndigits < NDIGITS_MIN)
1049 /* return 0.0, but with sign of x */
1050 return PyFloat_FromDouble(0.0*x);
1051 else
1052 /* finite x, and ndigits is not unreasonably large */
1053 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001054#undef NDIGITS_MAX
1055#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001056}
1057
1058static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001059float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (PyFloat_CheckExact(v))
1062 Py_INCREF(v);
1063 else
1064 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1065 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001066}
1067
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001068/* turn ASCII hex characters into integer values and vice versa */
1069
1070static char
1071char_from_hex(int x)
1072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 assert(0 <= x && x < 16);
1074 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001075}
1076
1077static int
1078hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 int x;
1080 switch(c) {
1081 case '0':
1082 x = 0;
1083 break;
1084 case '1':
1085 x = 1;
1086 break;
1087 case '2':
1088 x = 2;
1089 break;
1090 case '3':
1091 x = 3;
1092 break;
1093 case '4':
1094 x = 4;
1095 break;
1096 case '5':
1097 x = 5;
1098 break;
1099 case '6':
1100 x = 6;
1101 break;
1102 case '7':
1103 x = 7;
1104 break;
1105 case '8':
1106 x = 8;
1107 break;
1108 case '9':
1109 x = 9;
1110 break;
1111 case 'a':
1112 case 'A':
1113 x = 10;
1114 break;
1115 case 'b':
1116 case 'B':
1117 x = 11;
1118 break;
1119 case 'c':
1120 case 'C':
1121 x = 12;
1122 break;
1123 case 'd':
1124 case 'D':
1125 x = 13;
1126 break;
1127 case 'e':
1128 case 'E':
1129 x = 14;
1130 break;
1131 case 'f':
1132 case 'F':
1133 x = 15;
1134 break;
1135 default:
1136 x = -1;
1137 break;
1138 }
1139 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001140}
1141
1142/* convert a float to a hexadecimal string */
1143
1144/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1145 of the form 4k+1. */
1146#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1147
1148static PyObject *
1149float_hex(PyObject *v)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 double x, m;
1152 int e, shift, i, si, esign;
1153 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1154 trailing NUL byte. */
1155 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001160 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001163 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 return PyUnicode_FromString("-0x0.0p+0");
1165 else
1166 return PyUnicode_FromString("0x0.0p+0");
1167 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 m = frexp(fabs(x), &e);
1170 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1171 m = ldexp(m, shift);
1172 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 si = 0;
1175 s[si] = char_from_hex((int)m);
1176 si++;
1177 m -= (int)m;
1178 s[si] = '.';
1179 si++;
1180 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1181 m *= 16.0;
1182 s[si] = char_from_hex((int)m);
1183 si++;
1184 m -= (int)m;
1185 }
1186 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (e < 0) {
1189 esign = (int)'-';
1190 e = -e;
1191 }
1192 else
1193 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (x < 0.0)
1196 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1197 else
1198 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001199}
1200
1201PyDoc_STRVAR(float_hex_doc,
1202"float.hex() -> string\n\
1203\n\
1204Return a hexadecimal representation of a floating-point number.\n\
1205>>> (-0.1).hex()\n\
1206'-0x1.999999999999ap-4'\n\
1207>>> 3.14159.hex()\n\
1208'0x1.921f9f01b866ep+1'");
1209
1210/* Convert a hexadecimal string to a float. */
1211
1212static PyObject *
1213float_fromhex(PyObject *cls, PyObject *arg)
1214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyObject *result_as_float, *result;
1216 double x;
1217 long exp, top_exp, lsb, key_digit;
1218 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1219 int half_eps, digit, round_up, negate=0;
1220 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 /*
1223 * For the sake of simplicity and correctness, we impose an artificial
1224 * limit on ndigits, the total number of hex digits in the coefficient
1225 * The limit is chosen to ensure that, writing exp for the exponent,
1226 *
1227 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1228 * guaranteed to overflow (provided it's nonzero)
1229 *
1230 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1231 * guaranteed to underflow to 0.
1232 *
1233 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1234 * overflow in the calculation of exp and top_exp below.
1235 *
1236 * More specifically, ndigits is assumed to satisfy the following
1237 * inequalities:
1238 *
1239 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1240 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1241 *
1242 * If either of these inequalities is not satisfied, a ValueError is
1243 * raised. Otherwise, write x for the value of the hex string, and
1244 * assume x is nonzero. Then
1245 *
1246 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1247 *
1248 * Now if exp > LONG_MAX/2 then:
1249 *
1250 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1251 * = DBL_MAX_EXP
1252 *
1253 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1254 * double, so overflows. If exp < LONG_MIN/2, then
1255 *
1256 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1257 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1258 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1259 *
1260 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1261 * when converted to a C double.
1262 *
1263 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1264 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1265 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 s = _PyUnicode_AsStringAndSize(arg, &length);
1268 if (s == NULL)
1269 return NULL;
1270 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /********************
1273 * Parse the string *
1274 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 /* leading whitespace */
1277 while (Py_ISSPACE(*s))
1278 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 /* infinities and nans */
1281 x = _Py_parse_inf_or_nan(s, &coeff_end);
1282 if (coeff_end != s) {
1283 s = coeff_end;
1284 goto finished;
1285 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* optional sign */
1288 if (*s == '-') {
1289 s++;
1290 negate = 1;
1291 }
1292 else if (*s == '+')
1293 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 /* [0x] */
1296 s_store = s;
1297 if (*s == '0') {
1298 s++;
1299 if (*s == 'x' || *s == 'X')
1300 s++;
1301 else
1302 s = s_store;
1303 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 /* coefficient: <integer> [. <fraction>] */
1306 coeff_start = s;
1307 while (hex_from_char(*s) >= 0)
1308 s++;
1309 s_store = s;
1310 if (*s == '.') {
1311 s++;
1312 while (hex_from_char(*s) >= 0)
1313 s++;
1314 coeff_end = s-1;
1315 }
1316 else
1317 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 /* ndigits = total # of hex digits; fdigits = # after point */
1320 ndigits = coeff_end - coeff_start;
1321 fdigits = coeff_end - s_store;
1322 if (ndigits == 0)
1323 goto parse_error;
1324 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1325 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1326 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* [p <exponent>] */
1329 if (*s == 'p' || *s == 'P') {
1330 s++;
1331 exp_start = s;
1332 if (*s == '-' || *s == '+')
1333 s++;
1334 if (!('0' <= *s && *s <= '9'))
1335 goto parse_error;
1336 s++;
1337 while ('0' <= *s && *s <= '9')
1338 s++;
1339 exp = strtol(exp_start, NULL, 10);
1340 }
1341 else
1342 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001343
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001344/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1346 coeff_end-(j) : \
1347 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /*******************************************
1350 * Compute rounded value of the hex string *
1351 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* Discard leading zeros, and catch extreme overflow and underflow */
1354 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1355 ndigits--;
1356 if (ndigits == 0 || exp < LONG_MIN/2) {
1357 x = 0.0;
1358 goto finished;
1359 }
1360 if (exp > LONG_MAX/2)
1361 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* Adjust exponent for fractional part. */
1364 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1367 top_exp = exp + 4*((long)ndigits - 1);
1368 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1369 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* catch almost all nonextreme cases of overflow and underflow here */
1372 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1373 x = 0.0;
1374 goto finished;
1375 }
1376 if (top_exp > DBL_MAX_EXP)
1377 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* lsb = exponent of least significant bit of the *rounded* value.
1380 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1381 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 x = 0.0;
1384 if (exp >= lsb) {
1385 /* no rounding required */
1386 for (i = ndigits-1; i >= 0; i--)
1387 x = 16.0*x + HEX_DIGIT(i);
1388 x = ldexp(x, (int)(exp));
1389 goto finished;
1390 }
1391 /* rounding required. key_digit is the index of the hex digit
1392 containing the first bit to be rounded away. */
1393 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1394 key_digit = (lsb - exp - 1) / 4;
1395 for (i = ndigits-1; i > key_digit; i--)
1396 x = 16.0*x + HEX_DIGIT(i);
1397 digit = HEX_DIGIT(key_digit);
1398 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1401 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1402 if ((digit & half_eps) != 0) {
1403 round_up = 0;
1404 if ((digit & (3*half_eps-1)) != 0 ||
1405 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1406 round_up = 1;
1407 else
1408 for (i = key_digit-1; i >= 0; i--)
1409 if (HEX_DIGIT(i) != 0) {
1410 round_up = 1;
1411 break;
1412 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001413 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 x += 2*half_eps;
1415 if (top_exp == DBL_MAX_EXP &&
1416 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1417 /* overflow corner case: pre-rounded value <
1418 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1419 goto overflow_error;
1420 }
1421 }
1422 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001423
1424 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* optional trailing whitespace leading to the end of the string */
1426 while (Py_ISSPACE(*s))
1427 s++;
1428 if (s != s_end)
1429 goto parse_error;
1430 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1431 if (result_as_float == NULL)
1432 return NULL;
1433 result = PyObject_CallObject(cls, result_as_float);
1434 Py_DECREF(result_as_float);
1435 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001436
1437 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 PyErr_SetString(PyExc_OverflowError,
1439 "hexadecimal value too large to represent as a float");
1440 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001441
1442 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyErr_SetString(PyExc_ValueError,
1444 "invalid hexadecimal floating-point string");
1445 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001446
1447 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyErr_SetString(PyExc_ValueError,
1449 "hexadecimal string too long to convert");
1450 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001451}
1452
1453PyDoc_STRVAR(float_fromhex_doc,
1454"float.fromhex(string) -> float\n\
1455\n\
1456Create a floating-point number from a hexadecimal string.\n\
1457>>> float.fromhex('0x1.ffffp10')\n\
14582047.984375\n\
1459>>> float.fromhex('-0x1p-1074')\n\
1460-4.9406564584124654e-324");
1461
1462
Christian Heimes26855632008-01-27 23:50:43 +00001463static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001464float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 double self;
1467 double float_part;
1468 int exponent;
1469 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyObject *prev;
1472 PyObject *py_exponent = NULL;
1473 PyObject *numerator = NULL;
1474 PyObject *denominator = NULL;
1475 PyObject *result_pair = NULL;
1476 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001477
1478#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 prev = obj; \
1480 obj = call; \
1481 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (Py_IS_INFINITY(self)) {
1486 PyErr_SetString(PyExc_OverflowError,
1487 "Cannot pass infinity to float.as_integer_ratio.");
1488 return NULL;
1489 }
Christian Heimes26855632008-01-27 23:50:43 +00001490#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (Py_IS_NAN(self)) {
1492 PyErr_SetString(PyExc_ValueError,
1493 "Cannot pass NaN to float.as_integer_ratio.");
1494 return NULL;
1495 }
Christian Heimes26855632008-01-27 23:50:43 +00001496#endif
1497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1499 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1500 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1503 float_part *= 2.0;
1504 exponent--;
1505 }
1506 /* self == float_part * 2**exponent exactly and float_part is integral.
1507 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1508 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 numerator = PyLong_FromDouble(float_part);
1511 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* fold in 2**exponent */
1514 denominator = PyLong_FromLong(1);
1515 py_exponent = PyLong_FromLong(labs((long)exponent));
1516 if (py_exponent == NULL) goto error;
1517 INPLACE_UPDATE(py_exponent,
1518 long_methods->nb_lshift(denominator, py_exponent));
1519 if (py_exponent == NULL) goto error;
1520 if (exponent > 0) {
1521 INPLACE_UPDATE(numerator,
1522 long_methods->nb_multiply(numerator, py_exponent));
1523 if (numerator == NULL) goto error;
1524 }
1525 else {
1526 Py_DECREF(denominator);
1527 denominator = py_exponent;
1528 py_exponent = NULL;
1529 }
1530
1531 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001532
1533#undef INPLACE_UPDATE
1534error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 Py_XDECREF(py_exponent);
1536 Py_XDECREF(denominator);
1537 Py_XDECREF(numerator);
1538 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001539}
1540
1541PyDoc_STRVAR(float_as_integer_ratio_doc,
1542"float.as_integer_ratio() -> (int, int)\n"
1543"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001544"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1545"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001546"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001547"\n"
1548">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001549"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001550">>> (0.0).as_integer_ratio()\n"
1551"(0, 1)\n"
1552">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001553"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001554
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001555
Jeremy Hylton938ace62002-07-17 16:30:39 +00001556static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001557float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1558
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559static PyObject *
1560float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 PyObject *x = Py_False; /* Integer zero */
1563 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (type != &PyFloat_Type)
1566 return float_subtype_new(type, args, kwds); /* Wimp out */
1567 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1568 return NULL;
1569 /* If it's a string, but not a string subclass, use
1570 PyFloat_FromString. */
1571 if (PyUnicode_CheckExact(x))
1572 return PyFloat_FromString(x);
1573 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574}
1575
Guido van Rossumbef14172001-08-29 15:47:46 +00001576/* Wimpy, slow approach to tp_new calls for subtypes of float:
1577 first create a regular float from whatever arguments we got,
1578 then allocate a subtype instance and initialize its ob_fval
1579 from the regular float. The regular float is then thrown away.
1580*/
1581static PyObject *
1582float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 assert(PyType_IsSubtype(type, &PyFloat_Type));
1587 tmp = float_new(&PyFloat_Type, args, kwds);
1588 if (tmp == NULL)
1589 return NULL;
1590 assert(PyFloat_CheckExact(tmp));
1591 newobj = type->tp_alloc(type, 0);
1592 if (newobj == NULL) {
1593 Py_DECREF(tmp);
1594 return NULL;
1595 }
1596 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1597 Py_DECREF(tmp);
1598 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001599}
1600
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001601static PyObject *
1602float_getnewargs(PyFloatObject *v)
1603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001605}
1606
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001607/* this is for the benefit of the pack/unpack routines below */
1608
1609typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611} float_format_type;
1612
1613static float_format_type double_format, float_format;
1614static float_format_type detected_double_format, detected_float_format;
1615
1616static PyObject *
1617float_getformat(PyTypeObject *v, PyObject* arg)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 char* s;
1620 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (!PyUnicode_Check(arg)) {
1623 PyErr_Format(PyExc_TypeError,
1624 "__getformat__() argument must be string, not %.500s",
1625 Py_TYPE(arg)->tp_name);
1626 return NULL;
1627 }
1628 s = _PyUnicode_AsString(arg);
1629 if (s == NULL)
1630 return NULL;
1631 if (strcmp(s, "double") == 0) {
1632 r = double_format;
1633 }
1634 else if (strcmp(s, "float") == 0) {
1635 r = float_format;
1636 }
1637 else {
1638 PyErr_SetString(PyExc_ValueError,
1639 "__getformat__() argument 1 must be "
1640 "'double' or 'float'");
1641 return NULL;
1642 }
1643
1644 switch (r) {
1645 case unknown_format:
1646 return PyUnicode_FromString("unknown");
1647 case ieee_little_endian_format:
1648 return PyUnicode_FromString("IEEE, little-endian");
1649 case ieee_big_endian_format:
1650 return PyUnicode_FromString("IEEE, big-endian");
1651 default:
1652 Py_FatalError("insane float_format or double_format");
1653 return NULL;
1654 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655}
1656
1657PyDoc_STRVAR(float_getformat_doc,
1658"float.__getformat__(typestr) -> string\n"
1659"\n"
1660"You probably don't want to use this function. It exists mainly to be\n"
1661"used in Python's test suite.\n"
1662"\n"
1663"typestr must be 'double' or 'float'. This function returns whichever of\n"
1664"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1665"format of floating point numbers used by the C type named by typestr.");
1666
1667static PyObject *
1668float_setformat(PyTypeObject *v, PyObject* args)
1669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 char* typestr;
1671 char* format;
1672 float_format_type f;
1673 float_format_type detected;
1674 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1677 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (strcmp(typestr, "double") == 0) {
1680 p = &double_format;
1681 detected = detected_double_format;
1682 }
1683 else if (strcmp(typestr, "float") == 0) {
1684 p = &float_format;
1685 detected = detected_float_format;
1686 }
1687 else {
1688 PyErr_SetString(PyExc_ValueError,
1689 "__setformat__() argument 1 must "
1690 "be 'double' or 'float'");
1691 return NULL;
1692 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (strcmp(format, "unknown") == 0) {
1695 f = unknown_format;
1696 }
1697 else if (strcmp(format, "IEEE, little-endian") == 0) {
1698 f = ieee_little_endian_format;
1699 }
1700 else if (strcmp(format, "IEEE, big-endian") == 0) {
1701 f = ieee_big_endian_format;
1702 }
1703 else {
1704 PyErr_SetString(PyExc_ValueError,
1705 "__setformat__() argument 2 must be "
1706 "'unknown', 'IEEE, little-endian' or "
1707 "'IEEE, big-endian'");
1708 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 if (f != unknown_format && f != detected) {
1713 PyErr_Format(PyExc_ValueError,
1714 "can only set %s format to 'unknown' or the "
1715 "detected platform value", typestr);
1716 return NULL;
1717 }
1718
1719 *p = f;
1720 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721}
1722
1723PyDoc_STRVAR(float_setformat_doc,
1724"float.__setformat__(typestr, fmt) -> None\n"
1725"\n"
1726"You probably don't want to use this function. It exists mainly to be\n"
1727"used in Python's test suite.\n"
1728"\n"
1729"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1730"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1731"one of the latter two if it appears to match the underlying C reality.\n"
1732"\n"
1733"Overrides the automatic determination of C-level floating point type.\n"
1734"This affects how floats are converted to and from binary strings.");
1735
Guido van Rossumb43daf72007-08-01 18:08:08 +00001736static PyObject *
1737float_getzero(PyObject *v, void *closure)
1738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001740}
1741
Eric Smith8c663262007-08-25 02:26:07 +00001742static PyObject *
1743float__format__(PyObject *self, PyObject *args)
1744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1748 return NULL;
1749 return _PyFloat_FormatAdvanced(self,
1750 PyUnicode_AS_UNICODE(format_spec),
1751 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001752}
1753
1754PyDoc_STRVAR(float__format__doc,
1755"float.__format__(format_spec) -> string\n"
1756"\n"
1757"Formats the float according to format_spec.");
1758
1759
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001760static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1762 "Returns self, the complex conjugate of any float."},
1763 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1764 "Returns the Integral closest to x between 0 and x."},
1765 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1766 "Returns the Integral closest to x, rounding half toward even.\n"
1767 "When an argument is passed, works like built-in round(x, ndigits)."},
1768 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1769 float_as_integer_ratio_doc},
1770 {"fromhex", (PyCFunction)float_fromhex,
1771 METH_O|METH_CLASS, float_fromhex_doc},
1772 {"hex", (PyCFunction)float_hex,
1773 METH_NOARGS, float_hex_doc},
1774 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1775 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001776#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1778 "Returns True if the float is positive or negative infinite."},
1779 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1780 "Returns True if the float is finite, neither infinite nor NaN."},
1781 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1782 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001783#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1785 {"__getformat__", (PyCFunction)float_getformat,
1786 METH_O|METH_CLASS, float_getformat_doc},
1787 {"__setformat__", (PyCFunction)float_setformat,
1788 METH_VARARGS|METH_CLASS, float_setformat_doc},
1789 {"__format__", (PyCFunction)float__format__,
1790 METH_VARARGS, float__format__doc},
1791 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001792};
1793
Guido van Rossumb43daf72007-08-01 18:08:08 +00001794static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001796 (getter)float_float, (setter)NULL,
1797 "the real part of a complex number",
1798 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001800 (getter)float_getzero, (setter)NULL,
1801 "the imaginary part of a complex number",
1802 NULL},
1803 {NULL} /* Sentinel */
1804};
1805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807"float(x) -> floating point number\n\
1808\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001809Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810
1811
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001812static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 float_add, /*nb_add*/
1814 float_sub, /*nb_subtract*/
1815 float_mul, /*nb_multiply*/
1816 float_rem, /*nb_remainder*/
1817 float_divmod, /*nb_divmod*/
1818 float_pow, /*nb_power*/
1819 (unaryfunc)float_neg, /*nb_negative*/
1820 (unaryfunc)float_float, /*nb_positive*/
1821 (unaryfunc)float_abs, /*nb_absolute*/
1822 (inquiry)float_bool, /*nb_bool*/
1823 0, /*nb_invert*/
1824 0, /*nb_lshift*/
1825 0, /*nb_rshift*/
1826 0, /*nb_and*/
1827 0, /*nb_xor*/
1828 0, /*nb_or*/
1829 float_trunc, /*nb_int*/
1830 0, /*nb_reserved*/
1831 float_float, /*nb_float*/
1832 0, /* nb_inplace_add */
1833 0, /* nb_inplace_subtract */
1834 0, /* nb_inplace_multiply */
1835 0, /* nb_inplace_remainder */
1836 0, /* nb_inplace_power */
1837 0, /* nb_inplace_lshift */
1838 0, /* nb_inplace_rshift */
1839 0, /* nb_inplace_and */
1840 0, /* nb_inplace_xor */
1841 0, /* nb_inplace_or */
1842 float_floor_div, /* nb_floor_divide */
1843 float_div, /* nb_true_divide */
1844 0, /* nb_inplace_floor_divide */
1845 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846};
1847
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1850 "float",
1851 sizeof(PyFloatObject),
1852 0,
1853 (destructor)float_dealloc, /* tp_dealloc */
1854 0, /* tp_print */
1855 0, /* tp_getattr */
1856 0, /* tp_setattr */
1857 0, /* tp_reserved */
1858 (reprfunc)float_repr, /* tp_repr */
1859 &float_as_number, /* tp_as_number */
1860 0, /* tp_as_sequence */
1861 0, /* tp_as_mapping */
1862 (hashfunc)float_hash, /* tp_hash */
1863 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001864 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyObject_GenericGetAttr, /* tp_getattro */
1866 0, /* tp_setattro */
1867 0, /* tp_as_buffer */
1868 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1869 float_doc, /* tp_doc */
1870 0, /* tp_traverse */
1871 0, /* tp_clear */
1872 float_richcompare, /* tp_richcompare */
1873 0, /* tp_weaklistoffset */
1874 0, /* tp_iter */
1875 0, /* tp_iternext */
1876 float_methods, /* tp_methods */
1877 0, /* tp_members */
1878 float_getset, /* tp_getset */
1879 0, /* tp_base */
1880 0, /* tp_dict */
1881 0, /* tp_descr_get */
1882 0, /* tp_descr_set */
1883 0, /* tp_dictoffset */
1884 0, /* tp_init */
1885 0, /* tp_alloc */
1886 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001887};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001888
1889void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001890_PyFloat_Init(void)
1891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* We attempt to determine if this machine is using IEEE
1893 floating point formats by peering at the bits of some
1894 carefully chosen values. If it looks like we are on an
1895 IEEE platform, the float packing/unpacking routines can
1896 just copy bits, if not they resort to arithmetic & shifts
1897 and masks. The shifts & masks approach works on all finite
1898 values, but what happens to infinities, NaNs and signed
1899 zeroes on packing is an accident, and attempting to unpack
1900 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 Note that if we're on some whacked-out platform which uses
1903 IEEE formats but isn't strictly little-endian or big-
1904 endian, we will fall back to the portable shifts & masks
1905 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906
1907#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 {
1909 double x = 9006104071832581.0;
1910 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1911 detected_double_format = ieee_big_endian_format;
1912 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1913 detected_double_format = ieee_little_endian_format;
1914 else
1915 detected_double_format = unknown_format;
1916 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001917#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919#endif
1920
1921#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 {
1923 float y = 16711938.0;
1924 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1925 detected_float_format = ieee_big_endian_format;
1926 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1927 detected_float_format = ieee_little_endian_format;
1928 else
1929 detected_float_format = unknown_format;
1930 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001933#endif
1934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 double_format = detected_double_format;
1936 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 /* Init float info */
1939 if (FloatInfoType.tp_name == 0)
1940 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001941}
1942
Georg Brandl2ee470f2008-07-16 12:55:28 +00001943int
1944PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 PyFloatObject *p;
1947 PyFloatBlock *list, *next;
1948 int i;
1949 int u; /* remaining unfreed floats per block */
1950 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 list = block_list;
1953 block_list = NULL;
1954 free_list = NULL;
1955 while (list != NULL) {
1956 u = 0;
1957 for (i = 0, p = &list->objects[0];
1958 i < N_FLOATOBJECTS;
1959 i++, p++) {
1960 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1961 u++;
1962 }
1963 next = list->next;
1964 if (u) {
1965 list->next = block_list;
1966 block_list = list;
1967 for (i = 0, p = &list->objects[0];
1968 i < N_FLOATOBJECTS;
1969 i++, p++) {
1970 if (!PyFloat_CheckExact(p) ||
1971 Py_REFCNT(p) == 0) {
1972 Py_TYPE(p) = (struct _typeobject *)
1973 free_list;
1974 free_list = p;
1975 }
1976 }
1977 }
1978 else {
1979 PyMem_FREE(list);
1980 }
1981 freelist_size += u;
1982 list = next;
1983 }
1984 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001985}
1986
1987void
1988PyFloat_Fini(void)
1989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 PyFloatObject *p;
1991 PyFloatBlock *list;
1992 int i;
1993 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (!Py_VerboseFlag)
1998 return;
1999 fprintf(stderr, "# cleanup floats");
2000 if (!u) {
2001 fprintf(stderr, "\n");
2002 }
2003 else {
2004 fprintf(stderr,
2005 ": %d unfreed float%s\n",
2006 u, u == 1 ? "" : "s");
2007 }
2008 if (Py_VerboseFlag > 1) {
2009 list = block_list;
2010 while (list != NULL) {
2011 for (i = 0, p = &list->objects[0];
2012 i < N_FLOATOBJECTS;
2013 i++, p++) {
2014 if (PyFloat_CheckExact(p) &&
2015 Py_REFCNT(p) != 0) {
2016 char *buf = PyOS_double_to_string(
2017 PyFloat_AS_DOUBLE(p), 'r',
2018 0, 0, NULL);
2019 if (buf) {
2020 /* XXX(twouters) cast
2021 refcount to long
2022 until %zd is
2023 universally
2024 available
2025 */
2026 fprintf(stderr,
2027 "# <float at %p, refcnt=%ld, val=%s>\n",
2028 p, (long)Py_REFCNT(p), buf);
2029 PyMem_Free(buf);
2030 }
2031 }
2032 }
2033 list = list->next;
2034 }
2035 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002036}
Tim Peters9905b942003-03-20 20:53:32 +00002037
2038/*----------------------------------------------------------------------------
2039 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002040 */
2041int
2042_PyFloat_Pack4(double x, unsigned char *p, int le)
2043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 if (float_format == unknown_format) {
2045 unsigned char sign;
2046 int e;
2047 double f;
2048 unsigned int fbits;
2049 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (le) {
2052 p += 3;
2053 incr = -1;
2054 }
Tim Peters9905b942003-03-20 20:53:32 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (x < 0) {
2057 sign = 1;
2058 x = -x;
2059 }
2060 else
2061 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* Normalize f to be in the range [1.0, 2.0) */
2066 if (0.5 <= f && f < 1.0) {
2067 f *= 2.0;
2068 e--;
2069 }
2070 else if (f == 0.0)
2071 e = 0;
2072 else {
2073 PyErr_SetString(PyExc_SystemError,
2074 "frexp() result out of range");
2075 return -1;
2076 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 if (e >= 128)
2079 goto Overflow;
2080 else if (e < -126) {
2081 /* Gradual underflow */
2082 f = ldexp(f, 126 + e);
2083 e = 0;
2084 }
2085 else if (!(e == 0 && f == 0.0)) {
2086 e += 127;
2087 f -= 1.0; /* Get rid of leading 1 */
2088 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 f *= 8388608.0; /* 2**23 */
2091 fbits = (unsigned int)(f + 0.5); /* Round */
2092 assert(fbits <= 8388608);
2093 if (fbits >> 23) {
2094 /* The carry propagated out of a string of 23 1 bits. */
2095 fbits = 0;
2096 ++e;
2097 if (e >= 255)
2098 goto Overflow;
2099 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 /* First byte */
2102 *p = (sign << 7) | (e >> 1);
2103 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 /* Second byte */
2106 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2107 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Third byte */
2110 *p = (fbits >> 8) & 0xFF;
2111 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 /* Fourth byte */
2114 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 /* Done */
2117 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
2120 else {
2121 float y = (float)x;
2122 const char *s = (char*)&y;
2123 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2126 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if ((float_format == ieee_little_endian_format && !le)
2129 || (float_format == ieee_big_endian_format && le)) {
2130 p += 3;
2131 incr = -1;
2132 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 for (i = 0; i < 4; i++) {
2135 *p = *s++;
2136 p += incr;
2137 }
2138 return 0;
2139 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002140 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyErr_SetString(PyExc_OverflowError,
2142 "float too large to pack with f format");
2143 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002144}
2145
2146int
2147_PyFloat_Pack8(double x, unsigned char *p, int le)
2148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (double_format == unknown_format) {
2150 unsigned char sign;
2151 int e;
2152 double f;
2153 unsigned int fhi, flo;
2154 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (le) {
2157 p += 7;
2158 incr = -1;
2159 }
Tim Peters9905b942003-03-20 20:53:32 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (x < 0) {
2162 sign = 1;
2163 x = -x;
2164 }
2165 else
2166 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* Normalize f to be in the range [1.0, 2.0) */
2171 if (0.5 <= f && f < 1.0) {
2172 f *= 2.0;
2173 e--;
2174 }
2175 else if (f == 0.0)
2176 e = 0;
2177 else {
2178 PyErr_SetString(PyExc_SystemError,
2179 "frexp() result out of range");
2180 return -1;
2181 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (e >= 1024)
2184 goto Overflow;
2185 else if (e < -1022) {
2186 /* Gradual underflow */
2187 f = ldexp(f, 1022 + e);
2188 e = 0;
2189 }
2190 else if (!(e == 0 && f == 0.0)) {
2191 e += 1023;
2192 f -= 1.0; /* Get rid of leading 1 */
2193 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2196 f *= 268435456.0; /* 2**28 */
2197 fhi = (unsigned int)f; /* Truncate */
2198 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 f -= (double)fhi;
2201 f *= 16777216.0; /* 2**24 */
2202 flo = (unsigned int)(f + 0.5); /* Round */
2203 assert(flo <= 16777216);
2204 if (flo >> 24) {
2205 /* The carry propagated out of a string of 24 1 bits. */
2206 flo = 0;
2207 ++fhi;
2208 if (fhi >> 28) {
2209 /* And it also progagated out of the next 28 bits. */
2210 fhi = 0;
2211 ++e;
2212 if (e >= 2047)
2213 goto Overflow;
2214 }
2215 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* First byte */
2218 *p = (sign << 7) | (e >> 4);
2219 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* Second byte */
2222 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2223 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Third byte */
2226 *p = (fhi >> 16) & 0xFF;
2227 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* Fourth byte */
2230 *p = (fhi >> 8) & 0xFF;
2231 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Fifth byte */
2234 *p = fhi & 0xFF;
2235 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Sixth byte */
2238 *p = (flo >> 16) & 0xFF;
2239 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Seventh byte */
2242 *p = (flo >> 8) & 0xFF;
2243 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* Eighth byte */
2246 *p = flo & 0xFF;
2247 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* Done */
2250 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 Overflow:
2253 PyErr_SetString(PyExc_OverflowError,
2254 "float too large to pack with d format");
2255 return -1;
2256 }
2257 else {
2258 const char *s = (char*)&x;
2259 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if ((double_format == ieee_little_endian_format && !le)
2262 || (double_format == ieee_big_endian_format && le)) {
2263 p += 7;
2264 incr = -1;
2265 }
2266
2267 for (i = 0; i < 8; i++) {
2268 *p = *s++;
2269 p += incr;
2270 }
2271 return 0;
2272 }
Tim Peters9905b942003-03-20 20:53:32 +00002273}
2274
2275double
2276_PyFloat_Unpack4(const unsigned char *p, int le)
2277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 if (float_format == unknown_format) {
2279 unsigned char sign;
2280 int e;
2281 unsigned int f;
2282 double x;
2283 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (le) {
2286 p += 3;
2287 incr = -1;
2288 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 /* First byte */
2291 sign = (*p >> 7) & 1;
2292 e = (*p & 0x7F) << 1;
2293 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Second byte */
2296 e |= (*p >> 7) & 1;
2297 f = (*p & 0x7F) << 16;
2298 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (e == 255) {
2301 PyErr_SetString(
2302 PyExc_ValueError,
2303 "can't unpack IEEE 754 special value "
2304 "on non-IEEE platform");
2305 return -1;
2306 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Third byte */
2309 f |= *p << 8;
2310 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* Fourth byte */
2313 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* XXX This sadly ignores Inf/NaN issues */
2318 if (e == 0)
2319 e = -126;
2320 else {
2321 x += 1.0;
2322 e -= 127;
2323 }
2324 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (sign)
2327 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 return x;
2330 }
2331 else {
2332 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if ((float_format == ieee_little_endian_format && !le)
2335 || (float_format == ieee_big_endian_format && le)) {
2336 char buf[4];
2337 char *d = &buf[3];
2338 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 for (i = 0; i < 4; i++) {
2341 *d-- = *p++;
2342 }
2343 memcpy(&x, buf, 4);
2344 }
2345 else {
2346 memcpy(&x, p, 4);
2347 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 return x;
2350 }
Tim Peters9905b942003-03-20 20:53:32 +00002351}
2352
2353double
2354_PyFloat_Unpack8(const unsigned char *p, int le)
2355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 if (double_format == unknown_format) {
2357 unsigned char sign;
2358 int e;
2359 unsigned int fhi, flo;
2360 double x;
2361 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (le) {
2364 p += 7;
2365 incr = -1;
2366 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* First byte */
2369 sign = (*p >> 7) & 1;
2370 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* Second byte */
2375 e |= (*p >> 4) & 0xF;
2376 fhi = (*p & 0xF) << 24;
2377 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 if (e == 2047) {
2380 PyErr_SetString(
2381 PyExc_ValueError,
2382 "can't unpack IEEE 754 special value "
2383 "on non-IEEE platform");
2384 return -1.0;
2385 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* Third byte */
2388 fhi |= *p << 16;
2389 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Fourth byte */
2392 fhi |= *p << 8;
2393 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* Fifth byte */
2396 fhi |= *p;
2397 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Sixth byte */
2400 flo = *p << 16;
2401 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Seventh byte */
2404 flo |= *p << 8;
2405 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 /* Eighth byte */
2408 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2411 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 if (e == 0)
2414 e = -1022;
2415 else {
2416 x += 1.0;
2417 e -= 1023;
2418 }
2419 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (sign)
2422 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return x;
2425 }
2426 else {
2427 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 if ((double_format == ieee_little_endian_format && !le)
2430 || (double_format == ieee_big_endian_format && le)) {
2431 char buf[8];
2432 char *d = &buf[7];
2433 int i;
2434
2435 for (i = 0; i < 8; i++) {
2436 *d-- = *p++;
2437 }
2438 memcpy(&x, buf, 8);
2439 }
2440 else {
2441 memcpy(&x, p, 8);
2442 }
2443
2444 return x;
2445 }
Tim Peters9905b942003-03-20 20:53:32 +00002446}