Backport r71967 changes from py3k to trunk.
[python.git] / Objects / floatobject.c
bloba433697fa8f622ce32843a55220c1b4fd0656cea
2 /* Float object implementation */
4 /* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
7 #include "Python.h"
8 #include "structseq.h"
10 #include <ctype.h>
11 #include <float.h>
13 #undef MAX
14 #undef MIN
15 #define MAX(x, y) ((x) < (y) ? (y) : (x))
16 #define MIN(x, y) ((x) < (y) ? (x) : (y))
18 #ifdef HAVE_IEEEFP_H
19 #include <ieeefp.h>
20 #endif
22 #ifdef _OSF_SOURCE
23 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24 extern int finite(double);
25 #endif
27 /* Special free list -- see comments for same code in intobject.c. */
28 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
29 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
30 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
32 struct _floatblock {
33 struct _floatblock *next;
34 PyFloatObject objects[N_FLOATOBJECTS];
37 typedef struct _floatblock PyFloatBlock;
39 static PyFloatBlock *block_list = NULL;
40 static PyFloatObject *free_list = NULL;
42 static PyFloatObject *
43 fill_free_list(void)
45 PyFloatObject *p, *q;
46 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
48 if (p == NULL)
49 return (PyFloatObject *) PyErr_NoMemory();
50 ((PyFloatBlock *)p)->next = block_list;
51 block_list = (PyFloatBlock *)p;
52 p = &((PyFloatBlock *)p)->objects[0];
53 q = p + N_FLOATOBJECTS;
54 while (--q > p)
55 Py_TYPE(q) = (struct _typeobject *)(q-1);
56 Py_TYPE(q) = NULL;
57 return p + N_FLOATOBJECTS - 1;
60 double
61 PyFloat_GetMax(void)
63 return DBL_MAX;
66 double
67 PyFloat_GetMin(void)
69 return DBL_MIN;
72 static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
74 PyDoc_STRVAR(floatinfo__doc__,
75 "sys.floatinfo\n\
76 \n\
77 A structseq holding information about the float type. It contains low level\n\
78 information about the precision and internal representation. Please study\n\
79 your system's :file:`float.h` for more information.");
81 static PyStructSequence_Field floatinfo_fields[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
84 "is representable"},
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
86 "is representable"},
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
91 "a normalized"},
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
98 {0}
101 static PyStructSequence_Desc floatinfo_desc = {
102 "sys.floatinfo", /* name */
103 floatinfo__doc__, /* doc */
104 floatinfo_fields, /* fields */
108 PyObject *
109 PyFloat_GetInfo(void)
111 PyObject* floatinfo;
112 int pos = 0;
114 floatinfo = PyStructSequence_New(&FloatInfoType);
115 if (floatinfo == NULL) {
116 return NULL;
119 #define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121 #define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
124 SetDblFlag(DBL_MAX);
125 SetIntFlag(DBL_MAX_EXP);
126 SetIntFlag(DBL_MAX_10_EXP);
127 SetDblFlag(DBL_MIN);
128 SetIntFlag(DBL_MIN_EXP);
129 SetIntFlag(DBL_MIN_10_EXP);
130 SetIntFlag(DBL_DIG);
131 SetIntFlag(DBL_MANT_DIG);
132 SetDblFlag(DBL_EPSILON);
133 SetIntFlag(FLT_RADIX);
134 SetIntFlag(FLT_ROUNDS);
135 #undef SetIntFlag
136 #undef SetDblFlag
138 if (PyErr_Occurred()) {
139 Py_CLEAR(floatinfo);
140 return NULL;
142 return floatinfo;
145 PyObject *
146 PyFloat_FromDouble(double fval)
148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
153 /* Inline PyObject_New */
154 op = free_list;
155 free_list = (PyFloatObject *)Py_TYPE(op);
156 PyObject_INIT(op, &PyFloat_Type);
157 op->ob_fval = fval;
158 return (PyObject *) op;
161 /**************************************************************************
162 RED_FLAG 22-Sep-2000 tim
163 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
165 1. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
169 2. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
173 Since we can't change the interface of a public API function, pend is
174 still supported but now *officially* useless: if pend is not NULL,
175 *pend is set to NULL.
176 **************************************************************************/
177 PyObject *
178 PyFloat_FromString(PyObject *v, char **pend)
180 const char *s, *last, *end;
181 double x;
182 char buffer[256]; /* for errors */
183 #ifdef Py_USING_UNICODE
184 char s_buffer[256]; /* for objects convertible to a char buffer */
185 #endif
186 Py_ssize_t len;
188 if (pend)
189 *pend = NULL;
190 if (PyString_Check(v)) {
191 s = PyString_AS_STRING(v);
192 len = PyString_GET_SIZE(v);
194 #ifdef Py_USING_UNICODE
195 else if (PyUnicode_Check(v)) {
196 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
197 PyErr_SetString(PyExc_ValueError,
198 "Unicode float() literal too long to convert");
199 return NULL;
201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
202 PyUnicode_GET_SIZE(v),
203 s_buffer,
204 NULL))
205 return NULL;
206 s = s_buffer;
207 len = strlen(s);
209 #endif
210 else if (PyObject_AsCharBuffer(v, &s, &len)) {
211 PyErr_SetString(PyExc_TypeError,
212 "float() argument must be a string or a number");
213 return NULL;
215 last = s + len;
217 while (*s && isspace(Py_CHARMASK(*s)))
218 s++;
219 /* We don't care about overflow or underflow. If the platform
220 * supports them, infinities and signed zeroes (on underflow) are
221 * fine. */
222 errno = 0;
223 PyFPE_START_PROTECT("strtod", return NULL)
224 x = PyOS_ascii_strtod(s, (char **)&end);
225 PyFPE_END_PROTECT(x)
226 if (end == s) {
227 if (errno == ENOMEM)
228 PyErr_NoMemory();
229 else {
230 PyOS_snprintf(buffer, sizeof(buffer),
231 "invalid literal for float(): %.200s", s);
232 PyErr_SetString(PyExc_ValueError, buffer);
234 return NULL;
236 /* Since end != s, the platform made *some* kind of sense out
237 of the input. Trust it. */
238 while (*end && isspace(Py_CHARMASK(*end)))
239 end++;
240 if (end != last) {
241 if (*end == '\0')
242 PyErr_SetString(PyExc_ValueError,
243 "null byte in argument for float()");
244 else {
245 PyOS_snprintf(buffer, sizeof(buffer),
246 "invalid literal for float(): %.200s", s);
247 PyErr_SetString(PyExc_ValueError, buffer);
249 return NULL;
251 return PyFloat_FromDouble(x);
254 static void
255 float_dealloc(PyFloatObject *op)
257 if (PyFloat_CheckExact(op)) {
258 Py_TYPE(op) = (struct _typeobject *)free_list;
259 free_list = op;
261 else
262 Py_TYPE(op)->tp_free((PyObject *)op);
265 double
266 PyFloat_AsDouble(PyObject *op)
268 PyNumberMethods *nb;
269 PyFloatObject *fo;
270 double val;
272 if (op && PyFloat_Check(op))
273 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
275 if (op == NULL) {
276 PyErr_BadArgument();
277 return -1;
280 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
281 PyErr_SetString(PyExc_TypeError, "a float is required");
282 return -1;
285 fo = (PyFloatObject*) (*nb->nb_float) (op);
286 if (fo == NULL)
287 return -1;
288 if (!PyFloat_Check(fo)) {
289 PyErr_SetString(PyExc_TypeError,
290 "nb_float should return float object");
291 return -1;
294 val = PyFloat_AS_DOUBLE(fo);
295 Py_DECREF(fo);
297 return val;
300 /* Methods */
302 static void
303 format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
305 register char *cp;
306 int i;
308 /* Subroutine for float_repr and float_print.
309 We want float numbers to be recognizable as such,
310 i.e., they should contain a decimal point or an exponent.
311 However, %g may print the number as an integer;
312 in such cases, we append ".0" to the string. */
314 assert(PyFloat_Check(v));
315 _PyOS_double_to_string(buf, buflen, v->ob_fval, 'g', precision,
316 0, NULL);
317 cp = buf;
318 if (*cp == '-')
319 cp++;
320 for (; *cp != '\0'; cp++) {
321 /* Any non-digit means it's not an integer;
322 this takes care of NAN and INF as well. */
323 if (!isdigit(Py_CHARMASK(*cp)))
324 break;
326 if (*cp == '\0') {
327 *cp++ = '.';
328 *cp++ = '0';
329 *cp++ = '\0';
330 return;
332 /* Checking the next three chars should be more than enough to
333 * detect inf or nan, even on Windows. We check for inf or nan
334 * at last because they are rare cases.
336 for (i=0; *cp != '\0' && i<3; cp++, i++) {
337 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
338 continue;
339 /* found something that is neither a digit nor point
340 * it might be a NaN or INF
342 #ifdef Py_NAN
343 if (Py_IS_NAN(v->ob_fval)) {
344 strcpy(buf, "nan");
346 else
347 #endif
348 if (Py_IS_INFINITY(v->ob_fval)) {
349 cp = buf;
350 if (*cp == '-')
351 cp++;
352 strcpy(cp, "inf");
354 break;
359 /* XXX PyFloat_AsStringEx should not be a public API function (for one
360 XXX thing, its signature passes a buffer without a length; for another,
361 XXX it isn't useful outside this file).
363 void
364 PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
366 format_float(buf, 100, v, precision);
369 /* Macro and helper that convert PyObject obj to a C double and store
370 the value in dbl; this replaces the functionality of the coercion
371 slot function. If conversion to double raises an exception, obj is
372 set to NULL, and the function invoking this macro returns NULL. If
373 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
374 stored in obj, and returned from the function invoking this macro.
376 #define CONVERT_TO_DOUBLE(obj, dbl) \
377 if (PyFloat_Check(obj)) \
378 dbl = PyFloat_AS_DOUBLE(obj); \
379 else if (convert_to_double(&(obj), &(dbl)) < 0) \
380 return obj;
382 static int
383 convert_to_double(PyObject **v, double *dbl)
385 register PyObject *obj = *v;
387 if (PyInt_Check(obj)) {
388 *dbl = (double)PyInt_AS_LONG(obj);
390 else if (PyLong_Check(obj)) {
391 *dbl = PyLong_AsDouble(obj);
392 if (*dbl == -1.0 && PyErr_Occurred()) {
393 *v = NULL;
394 return -1;
397 else {
398 Py_INCREF(Py_NotImplemented);
399 *v = Py_NotImplemented;
400 return -1;
402 return 0;
405 /* Precisions used by repr() and str(), respectively.
407 The repr() precision (17 significant decimal digits) is the minimal number
408 that is guaranteed to have enough precision so that if the number is read
409 back in the exact same binary value is recreated. This is true for IEEE
410 floating point by design, and also happens to work for all other modern
411 hardware.
413 The str() precision is chosen so that in most cases, the rounding noise
414 created by various operations is suppressed, while giving plenty of
415 precision for practical use.
419 #define PREC_REPR 17
420 #define PREC_STR 12
422 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
423 XXX they pass a char buffer without passing a length.
425 void
426 PyFloat_AsString(char *buf, PyFloatObject *v)
428 format_float(buf, 100, v, PREC_STR);
431 void
432 PyFloat_AsReprString(char *buf, PyFloatObject *v)
434 format_float(buf, 100, v, PREC_REPR);
437 /* ARGSUSED */
438 static int
439 float_print(PyFloatObject *v, FILE *fp, int flags)
441 char buf[100];
442 format_float(buf, sizeof(buf), v,
443 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
444 Py_BEGIN_ALLOW_THREADS
445 fputs(buf, fp);
446 Py_END_ALLOW_THREADS
447 return 0;
450 static PyObject *
451 float_repr(PyFloatObject *v)
453 char buf[100];
454 format_float(buf, sizeof(buf), v, PREC_REPR);
456 return PyString_FromString(buf);
459 static PyObject *
460 float_str(PyFloatObject *v)
462 char buf[100];
463 format_float(buf, sizeof(buf), v, PREC_STR);
464 return PyString_FromString(buf);
467 /* Comparison is pretty much a nightmare. When comparing float to float,
468 * we do it as straightforwardly (and long-windedly) as conceivable, so
469 * that, e.g., Python x == y delivers the same result as the platform
470 * C x == y when x and/or y is a NaN.
471 * When mixing float with an integer type, there's no good *uniform* approach.
472 * Converting the double to an integer obviously doesn't work, since we
473 * may lose info from fractional bits. Converting the integer to a double
474 * also has two failure modes: (1) a long int may trigger overflow (too
475 * large to fit in the dynamic range of a C double); (2) even a C long may have
476 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
477 * 63 bits of precision, but a C double probably has only 53), and then
478 * we can falsely claim equality when low-order integer bits are lost by
479 * coercion to double. So this part is painful too.
482 static PyObject*
483 float_richcompare(PyObject *v, PyObject *w, int op)
485 double i, j;
486 int r = 0;
488 assert(PyFloat_Check(v));
489 i = PyFloat_AS_DOUBLE(v);
491 /* Switch on the type of w. Set i and j to doubles to be compared,
492 * and op to the richcomp to use.
494 if (PyFloat_Check(w))
495 j = PyFloat_AS_DOUBLE(w);
497 else if (!Py_IS_FINITE(i)) {
498 if (PyInt_Check(w) || PyLong_Check(w))
499 /* If i is an infinity, its magnitude exceeds any
500 * finite integer, so it doesn't matter which int we
501 * compare i with. If i is a NaN, similarly.
503 j = 0.0;
504 else
505 goto Unimplemented;
508 else if (PyInt_Check(w)) {
509 long jj = PyInt_AS_LONG(w);
510 /* In the worst realistic case I can imagine, C double is a
511 * Cray single with 48 bits of precision, and long has 64
512 * bits.
514 #if SIZEOF_LONG > 6
515 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
516 if (abs >> 48) {
517 /* Needs more than 48 bits. Make it take the
518 * PyLong path.
520 PyObject *result;
521 PyObject *ww = PyLong_FromLong(jj);
523 if (ww == NULL)
524 return NULL;
525 result = float_richcompare(v, ww, op);
526 Py_DECREF(ww);
527 return result;
529 #endif
530 j = (double)jj;
531 assert((long)j == jj);
534 else if (PyLong_Check(w)) {
535 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
536 int wsign = _PyLong_Sign(w);
537 size_t nbits;
538 int exponent;
540 if (vsign != wsign) {
541 /* Magnitudes are irrelevant -- the signs alone
542 * determine the outcome.
544 i = (double)vsign;
545 j = (double)wsign;
546 goto Compare;
548 /* The signs are the same. */
549 /* Convert w to a double if it fits. In particular, 0 fits. */
550 nbits = _PyLong_NumBits(w);
551 if (nbits == (size_t)-1 && PyErr_Occurred()) {
552 /* This long is so large that size_t isn't big enough
553 * to hold the # of bits. Replace with little doubles
554 * that give the same outcome -- w is so large that
555 * its magnitude must exceed the magnitude of any
556 * finite float.
558 PyErr_Clear();
559 i = (double)vsign;
560 assert(wsign != 0);
561 j = wsign * 2.0;
562 goto Compare;
564 if (nbits <= 48) {
565 j = PyLong_AsDouble(w);
566 /* It's impossible that <= 48 bits overflowed. */
567 assert(j != -1.0 || ! PyErr_Occurred());
568 goto Compare;
570 assert(wsign != 0); /* else nbits was 0 */
571 assert(vsign != 0); /* if vsign were 0, then since wsign is
572 * not 0, we would have taken the
573 * vsign != wsign branch at the start */
574 /* We want to work with non-negative numbers. */
575 if (vsign < 0) {
576 /* "Multiply both sides" by -1; this also swaps the
577 * comparator.
579 i = -i;
580 op = _Py_SwappedOp[op];
582 assert(i > 0.0);
583 (void) frexp(i, &exponent);
584 /* exponent is the # of bits in v before the radix point;
585 * we know that nbits (the # of bits in w) > 48 at this point
587 if (exponent < 0 || (size_t)exponent < nbits) {
588 i = 1.0;
589 j = 2.0;
590 goto Compare;
592 if ((size_t)exponent > nbits) {
593 i = 2.0;
594 j = 1.0;
595 goto Compare;
597 /* v and w have the same number of bits before the radix
598 * point. Construct two longs that have the same comparison
599 * outcome.
602 double fracpart;
603 double intpart;
604 PyObject *result = NULL;
605 PyObject *one = NULL;
606 PyObject *vv = NULL;
607 PyObject *ww = w;
609 if (wsign < 0) {
610 ww = PyNumber_Negative(w);
611 if (ww == NULL)
612 goto Error;
614 else
615 Py_INCREF(ww);
617 fracpart = modf(i, &intpart);
618 vv = PyLong_FromDouble(intpart);
619 if (vv == NULL)
620 goto Error;
622 if (fracpart != 0.0) {
623 /* Shift left, and or a 1 bit into vv
624 * to represent the lost fraction.
626 PyObject *temp;
628 one = PyInt_FromLong(1);
629 if (one == NULL)
630 goto Error;
632 temp = PyNumber_Lshift(ww, one);
633 if (temp == NULL)
634 goto Error;
635 Py_DECREF(ww);
636 ww = temp;
638 temp = PyNumber_Lshift(vv, one);
639 if (temp == NULL)
640 goto Error;
641 Py_DECREF(vv);
642 vv = temp;
644 temp = PyNumber_Or(vv, one);
645 if (temp == NULL)
646 goto Error;
647 Py_DECREF(vv);
648 vv = temp;
651 r = PyObject_RichCompareBool(vv, ww, op);
652 if (r < 0)
653 goto Error;
654 result = PyBool_FromLong(r);
655 Error:
656 Py_XDECREF(vv);
657 Py_XDECREF(ww);
658 Py_XDECREF(one);
659 return result;
661 } /* else if (PyLong_Check(w)) */
663 else /* w isn't float, int, or long */
664 goto Unimplemented;
666 Compare:
667 PyFPE_START_PROTECT("richcompare", return NULL)
668 switch (op) {
669 case Py_EQ:
670 r = i == j;
671 break;
672 case Py_NE:
673 r = i != j;
674 break;
675 case Py_LE:
676 r = i <= j;
677 break;
678 case Py_GE:
679 r = i >= j;
680 break;
681 case Py_LT:
682 r = i < j;
683 break;
684 case Py_GT:
685 r = i > j;
686 break;
688 PyFPE_END_PROTECT(r)
689 return PyBool_FromLong(r);
691 Unimplemented:
692 Py_INCREF(Py_NotImplemented);
693 return Py_NotImplemented;
696 static long
697 float_hash(PyFloatObject *v)
699 return _Py_HashDouble(v->ob_fval);
702 static PyObject *
703 float_add(PyObject *v, PyObject *w)
705 double a,b;
706 CONVERT_TO_DOUBLE(v, a);
707 CONVERT_TO_DOUBLE(w, b);
708 PyFPE_START_PROTECT("add", return 0)
709 a = a + b;
710 PyFPE_END_PROTECT(a)
711 return PyFloat_FromDouble(a);
714 static PyObject *
715 float_sub(PyObject *v, PyObject *w)
717 double a,b;
718 CONVERT_TO_DOUBLE(v, a);
719 CONVERT_TO_DOUBLE(w, b);
720 PyFPE_START_PROTECT("subtract", return 0)
721 a = a - b;
722 PyFPE_END_PROTECT(a)
723 return PyFloat_FromDouble(a);
726 static PyObject *
727 float_mul(PyObject *v, PyObject *w)
729 double a,b;
730 CONVERT_TO_DOUBLE(v, a);
731 CONVERT_TO_DOUBLE(w, b);
732 PyFPE_START_PROTECT("multiply", return 0)
733 a = a * b;
734 PyFPE_END_PROTECT(a)
735 return PyFloat_FromDouble(a);
738 static PyObject *
739 float_div(PyObject *v, PyObject *w)
741 double a,b;
742 CONVERT_TO_DOUBLE(v, a);
743 CONVERT_TO_DOUBLE(w, b);
744 #ifdef Py_NAN
745 if (b == 0.0) {
746 PyErr_SetString(PyExc_ZeroDivisionError,
747 "float division");
748 return NULL;
750 #endif
751 PyFPE_START_PROTECT("divide", return 0)
752 a = a / b;
753 PyFPE_END_PROTECT(a)
754 return PyFloat_FromDouble(a);
757 static PyObject *
758 float_classic_div(PyObject *v, PyObject *w)
760 double a,b;
761 CONVERT_TO_DOUBLE(v, a);
762 CONVERT_TO_DOUBLE(w, b);
763 if (Py_DivisionWarningFlag >= 2 &&
764 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
765 return NULL;
766 #ifdef Py_NAN
767 if (b == 0.0) {
768 PyErr_SetString(PyExc_ZeroDivisionError,
769 "float division");
770 return NULL;
772 #endif
773 PyFPE_START_PROTECT("divide", return 0)
774 a = a / b;
775 PyFPE_END_PROTECT(a)
776 return PyFloat_FromDouble(a);
779 static PyObject *
780 float_rem(PyObject *v, PyObject *w)
782 double vx, wx;
783 double mod;
784 CONVERT_TO_DOUBLE(v, vx);
785 CONVERT_TO_DOUBLE(w, wx);
786 #ifdef Py_NAN
787 if (wx == 0.0) {
788 PyErr_SetString(PyExc_ZeroDivisionError,
789 "float modulo");
790 return NULL;
792 #endif
793 PyFPE_START_PROTECT("modulo", return 0)
794 mod = fmod(vx, wx);
795 /* note: checking mod*wx < 0 is incorrect -- underflows to
796 0 if wx < sqrt(smallest nonzero double) */
797 if (mod && ((wx < 0) != (mod < 0))) {
798 mod += wx;
800 PyFPE_END_PROTECT(mod)
801 return PyFloat_FromDouble(mod);
804 static PyObject *
805 float_divmod(PyObject *v, PyObject *w)
807 double vx, wx;
808 double div, mod, floordiv;
809 CONVERT_TO_DOUBLE(v, vx);
810 CONVERT_TO_DOUBLE(w, wx);
811 if (wx == 0.0) {
812 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
813 return NULL;
815 PyFPE_START_PROTECT("divmod", return 0)
816 mod = fmod(vx, wx);
817 /* fmod is typically exact, so vx-mod is *mathematically* an
818 exact multiple of wx. But this is fp arithmetic, and fp
819 vx - mod is an approximation; the result is that div may
820 not be an exact integral value after the division, although
821 it will always be very close to one.
823 div = (vx - mod) / wx;
824 if (mod) {
825 /* ensure the remainder has the same sign as the denominator */
826 if ((wx < 0) != (mod < 0)) {
827 mod += wx;
828 div -= 1.0;
831 else {
832 /* the remainder is zero, and in the presence of signed zeroes
833 fmod returns different results across platforms; ensure
834 it has the same sign as the denominator; we'd like to do
835 "mod = wx * 0.0", but that may get optimized away */
836 mod *= mod; /* hide "mod = +0" from optimizer */
837 if (wx < 0.0)
838 mod = -mod;
840 /* snap quotient to nearest integral value */
841 if (div) {
842 floordiv = floor(div);
843 if (div - floordiv > 0.5)
844 floordiv += 1.0;
846 else {
847 /* div is zero - get the same sign as the true quotient */
848 div *= div; /* hide "div = +0" from optimizers */
849 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
851 PyFPE_END_PROTECT(floordiv)
852 return Py_BuildValue("(dd)", floordiv, mod);
855 static PyObject *
856 float_floor_div(PyObject *v, PyObject *w)
858 PyObject *t, *r;
860 t = float_divmod(v, w);
861 if (t == NULL || t == Py_NotImplemented)
862 return t;
863 assert(PyTuple_CheckExact(t));
864 r = PyTuple_GET_ITEM(t, 0);
865 Py_INCREF(r);
866 Py_DECREF(t);
867 return r;
870 static PyObject *
871 float_pow(PyObject *v, PyObject *w, PyObject *z)
873 double iv, iw, ix;
875 if ((PyObject *)z != Py_None) {
876 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
877 "allowed unless all arguments are integers");
878 return NULL;
881 CONVERT_TO_DOUBLE(v, iv);
882 CONVERT_TO_DOUBLE(w, iw);
884 /* Sort out special cases here instead of relying on pow() */
885 if (iw == 0) { /* v**0 is 1, even 0**0 */
886 return PyFloat_FromDouble(1.0);
888 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
889 if (iw < 0.0) {
890 PyErr_SetString(PyExc_ZeroDivisionError,
891 "0.0 cannot be raised to a negative power");
892 return NULL;
894 return PyFloat_FromDouble(0.0);
896 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
897 return PyFloat_FromDouble(1.0);
899 if (iv < 0.0) {
900 /* Whether this is an error is a mess, and bumps into libm
901 * bugs so we have to figure it out ourselves.
903 if (iw != floor(iw)) {
904 PyErr_SetString(PyExc_ValueError, "negative number "
905 "cannot be raised to a fractional power");
906 return NULL;
908 /* iw is an exact integer, albeit perhaps a very large one.
909 * -1 raised to an exact integer should never be exceptional.
910 * Alas, some libms (chiefly glibc as of early 2003) return
911 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
912 * happen to be representable in a *C* integer. That's a
913 * bug; we let that slide in math.pow() (which currently
914 * reflects all platform accidents), but not for Python's **.
916 if (iv == -1.0 && Py_IS_FINITE(iw)) {
917 /* Return 1 if iw is even, -1 if iw is odd; there's
918 * no guarantee that any C integral type is big
919 * enough to hold iw, so we have to check this
920 * indirectly.
922 ix = floor(iw * 0.5) * 2.0;
923 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
925 /* Else iv != -1.0, and overflow or underflow are possible.
926 * Unless we're to write pow() ourselves, we have to trust
927 * the platform to do this correctly.
930 errno = 0;
931 PyFPE_START_PROTECT("pow", return NULL)
932 ix = pow(iv, iw);
933 PyFPE_END_PROTECT(ix)
934 Py_ADJUST_ERANGE1(ix);
935 if (errno != 0) {
936 /* We don't expect any errno value other than ERANGE, but
937 * the range of libm bugs appears unbounded.
939 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
940 PyExc_ValueError);
941 return NULL;
943 return PyFloat_FromDouble(ix);
946 static PyObject *
947 float_neg(PyFloatObject *v)
949 return PyFloat_FromDouble(-v->ob_fval);
952 static PyObject *
953 float_abs(PyFloatObject *v)
955 return PyFloat_FromDouble(fabs(v->ob_fval));
958 static int
959 float_nonzero(PyFloatObject *v)
961 return v->ob_fval != 0.0;
964 static int
965 float_coerce(PyObject **pv, PyObject **pw)
967 if (PyInt_Check(*pw)) {
968 long x = PyInt_AsLong(*pw);
969 *pw = PyFloat_FromDouble((double)x);
970 Py_INCREF(*pv);
971 return 0;
973 else if (PyLong_Check(*pw)) {
974 double x = PyLong_AsDouble(*pw);
975 if (x == -1.0 && PyErr_Occurred())
976 return -1;
977 *pw = PyFloat_FromDouble(x);
978 Py_INCREF(*pv);
979 return 0;
981 else if (PyFloat_Check(*pw)) {
982 Py_INCREF(*pv);
983 Py_INCREF(*pw);
984 return 0;
986 return 1; /* Can't do it */
989 static PyObject *
990 float_is_integer(PyObject *v)
992 double x = PyFloat_AsDouble(v);
993 PyObject *o;
995 if (x == -1.0 && PyErr_Occurred())
996 return NULL;
997 if (!Py_IS_FINITE(x))
998 Py_RETURN_FALSE;
999 errno = 0;
1000 PyFPE_START_PROTECT("is_integer", return NULL)
1001 o = (floor(x) == x) ? Py_True : Py_False;
1002 PyFPE_END_PROTECT(x)
1003 if (errno != 0) {
1004 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1005 PyExc_ValueError);
1006 return NULL;
1008 Py_INCREF(o);
1009 return o;
1012 #if 0
1013 static PyObject *
1014 float_is_inf(PyObject *v)
1016 double x = PyFloat_AsDouble(v);
1017 if (x == -1.0 && PyErr_Occurred())
1018 return NULL;
1019 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1022 static PyObject *
1023 float_is_nan(PyObject *v)
1025 double x = PyFloat_AsDouble(v);
1026 if (x == -1.0 && PyErr_Occurred())
1027 return NULL;
1028 return PyBool_FromLong((long)Py_IS_NAN(x));
1031 static PyObject *
1032 float_is_finite(PyObject *v)
1034 double x = PyFloat_AsDouble(v);
1035 if (x == -1.0 && PyErr_Occurred())
1036 return NULL;
1037 return PyBool_FromLong((long)Py_IS_FINITE(x));
1039 #endif
1041 static PyObject *
1042 float_trunc(PyObject *v)
1044 double x = PyFloat_AsDouble(v);
1045 double wholepart; /* integral portion of x, rounded toward 0 */
1047 (void)modf(x, &wholepart);
1048 /* Try to get out cheap if this fits in a Python int. The attempt
1049 * to cast to long must be protected, as C doesn't define what
1050 * happens if the double is too big to fit in a long. Some rare
1051 * systems raise an exception then (RISCOS was mentioned as one,
1052 * and someone using a non-default option on Sun also bumped into
1053 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1054 * still be vulnerable: if a long has more bits of precision than
1055 * a double, casting MIN/MAX to double may yield an approximation,
1056 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1057 * yield true from the C expression wholepart<=LONG_MAX, despite
1058 * that wholepart is actually greater than LONG_MAX.
1060 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1061 const long aslong = (long)wholepart;
1062 return PyInt_FromLong(aslong);
1064 return PyLong_FromDouble(wholepart);
1067 static PyObject *
1068 float_long(PyObject *v)
1070 double x = PyFloat_AsDouble(v);
1071 return PyLong_FromDouble(x);
1074 static PyObject *
1075 float_float(PyObject *v)
1077 if (PyFloat_CheckExact(v))
1078 Py_INCREF(v);
1079 else
1080 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1081 return v;
1084 /* turn ASCII hex characters into integer values and vice versa */
1086 static char
1087 char_from_hex(int x)
1089 assert(0 <= x && x < 16);
1090 return "0123456789abcdef"[x];
1093 static int
1094 hex_from_char(char c) {
1095 int x;
1096 switch(c) {
1097 case '0':
1098 x = 0;
1099 break;
1100 case '1':
1101 x = 1;
1102 break;
1103 case '2':
1104 x = 2;
1105 break;
1106 case '3':
1107 x = 3;
1108 break;
1109 case '4':
1110 x = 4;
1111 break;
1112 case '5':
1113 x = 5;
1114 break;
1115 case '6':
1116 x = 6;
1117 break;
1118 case '7':
1119 x = 7;
1120 break;
1121 case '8':
1122 x = 8;
1123 break;
1124 case '9':
1125 x = 9;
1126 break;
1127 case 'a':
1128 case 'A':
1129 x = 10;
1130 break;
1131 case 'b':
1132 case 'B':
1133 x = 11;
1134 break;
1135 case 'c':
1136 case 'C':
1137 x = 12;
1138 break;
1139 case 'd':
1140 case 'D':
1141 x = 13;
1142 break;
1143 case 'e':
1144 case 'E':
1145 x = 14;
1146 break;
1147 case 'f':
1148 case 'F':
1149 x = 15;
1150 break;
1151 default:
1152 x = -1;
1153 break;
1155 return x;
1158 /* convert a float to a hexadecimal string */
1160 /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1161 of the form 4k+1. */
1162 #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1164 static PyObject *
1165 float_hex(PyObject *v)
1167 double x, m;
1168 int e, shift, i, si, esign;
1169 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1170 trailing NUL byte. */
1171 char s[(TOHEX_NBITS-1)/4+3];
1173 CONVERT_TO_DOUBLE(v, x);
1175 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1176 return float_str((PyFloatObject *)v);
1178 if (x == 0.0) {
1179 if(copysign(1.0, x) == -1.0)
1180 return PyString_FromString("-0x0.0p+0");
1181 else
1182 return PyString_FromString("0x0.0p+0");
1185 m = frexp(fabs(x), &e);
1186 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1187 m = ldexp(m, shift);
1188 e -= shift;
1190 si = 0;
1191 s[si] = char_from_hex((int)m);
1192 si++;
1193 m -= (int)m;
1194 s[si] = '.';
1195 si++;
1196 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1197 m *= 16.0;
1198 s[si] = char_from_hex((int)m);
1199 si++;
1200 m -= (int)m;
1202 s[si] = '\0';
1204 if (e < 0) {
1205 esign = (int)'-';
1206 e = -e;
1208 else
1209 esign = (int)'+';
1211 if (x < 0.0)
1212 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1213 else
1214 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1217 PyDoc_STRVAR(float_hex_doc,
1218 "float.hex() -> string\n\
1220 Return a hexadecimal representation of a floating-point number.\n\
1221 >>> (-0.1).hex()\n\
1222 '-0x1.999999999999ap-4'\n\
1223 >>> 3.14159.hex()\n\
1224 '0x1.921f9f01b866ep+1'");
1226 /* Convert a hexadecimal string to a float. */
1228 static PyObject *
1229 float_fromhex(PyObject *cls, PyObject *arg)
1231 PyObject *result_as_float, *result;
1232 double x;
1233 long exp, top_exp, lsb, key_digit;
1234 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1235 int half_eps, digit, round_up, sign=1;
1236 Py_ssize_t length, ndigits, fdigits, i;
1239 * For the sake of simplicity and correctness, we impose an artificial
1240 * limit on ndigits, the total number of hex digits in the coefficient
1241 * The limit is chosen to ensure that, writing exp for the exponent,
1243 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1244 * guaranteed to overflow (provided it's nonzero)
1246 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1247 * guaranteed to underflow to 0.
1249 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1250 * overflow in the calculation of exp and top_exp below.
1252 * More specifically, ndigits is assumed to satisfy the following
1253 * inequalities:
1255 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1256 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1258 * If either of these inequalities is not satisfied, a ValueError is
1259 * raised. Otherwise, write x for the value of the hex string, and
1260 * assume x is nonzero. Then
1262 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1264 * Now if exp > LONG_MAX/2 then:
1266 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1267 * = DBL_MAX_EXP
1269 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1270 * double, so overflows. If exp < LONG_MIN/2, then
1272 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1273 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1274 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1276 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1277 * when converted to a C double.
1279 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1280 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1283 if (PyString_AsStringAndSize(arg, &s, &length))
1284 return NULL;
1285 s_end = s + length;
1287 /********************
1288 * Parse the string *
1289 ********************/
1291 /* leading whitespace and optional sign */
1292 while (isspace(*s))
1293 s++;
1294 if (*s == '-') {
1295 s++;
1296 sign = -1;
1298 else if (*s == '+')
1299 s++;
1301 /* infinities and nans */
1302 if (PyOS_strnicmp(s, "nan", 4) == 0) {
1303 x = Py_NAN;
1304 goto finished;
1306 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1307 PyOS_strnicmp(s, "infinity", 9) == 0) {
1308 x = sign*Py_HUGE_VAL;
1309 goto finished;
1312 /* [0x] */
1313 s_store = s;
1314 if (*s == '0') {
1315 s++;
1316 if (tolower(*s) == (int)'x')
1317 s++;
1318 else
1319 s = s_store;
1322 /* coefficient: <integer> [. <fraction>] */
1323 coeff_start = s;
1324 while (hex_from_char(*s) >= 0)
1325 s++;
1326 s_store = s;
1327 if (*s == '.') {
1328 s++;
1329 while (hex_from_char(*s) >= 0)
1330 s++;
1331 coeff_end = s-1;
1333 else
1334 coeff_end = s;
1336 /* ndigits = total # of hex digits; fdigits = # after point */
1337 ndigits = coeff_end - coeff_start;
1338 fdigits = coeff_end - s_store;
1339 if (ndigits == 0)
1340 goto parse_error;
1341 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1342 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1343 goto insane_length_error;
1345 /* [p <exponent>] */
1346 if (tolower(*s) == (int)'p') {
1347 s++;
1348 exp_start = s;
1349 if (*s == '-' || *s == '+')
1350 s++;
1351 if (!('0' <= *s && *s <= '9'))
1352 goto parse_error;
1353 s++;
1354 while ('0' <= *s && *s <= '9')
1355 s++;
1356 exp = strtol(exp_start, NULL, 10);
1358 else
1359 exp = 0;
1361 /* optional trailing whitespace leading to the end of the string */
1362 while (isspace(*s))
1363 s++;
1364 if (s != s_end)
1365 goto parse_error;
1367 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1368 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1369 coeff_end-(j) : \
1370 coeff_end-1-(j)))
1372 /*******************************************
1373 * Compute rounded value of the hex string *
1374 *******************************************/
1376 /* Discard leading zeros, and catch extreme overflow and underflow */
1377 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1378 ndigits--;
1379 if (ndigits == 0 || exp < LONG_MIN/2) {
1380 x = sign * 0.0;
1381 goto finished;
1383 if (exp > LONG_MAX/2)
1384 goto overflow_error;
1386 /* Adjust exponent for fractional part. */
1387 exp = exp - 4*((long)fdigits);
1389 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1390 top_exp = exp + 4*((long)ndigits - 1);
1391 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1392 top_exp++;
1394 /* catch almost all nonextreme cases of overflow and underflow here */
1395 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1396 x = sign * 0.0;
1397 goto finished;
1399 if (top_exp > DBL_MAX_EXP)
1400 goto overflow_error;
1402 /* lsb = exponent of least significant bit of the *rounded* value.
1403 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1404 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1406 x = 0.0;
1407 if (exp >= lsb) {
1408 /* no rounding required */
1409 for (i = ndigits-1; i >= 0; i--)
1410 x = 16.0*x + HEX_DIGIT(i);
1411 x = sign * ldexp(x, (int)(exp));
1412 goto finished;
1414 /* rounding required. key_digit is the index of the hex digit
1415 containing the first bit to be rounded away. */
1416 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1417 key_digit = (lsb - exp - 1) / 4;
1418 for (i = ndigits-1; i > key_digit; i--)
1419 x = 16.0*x + HEX_DIGIT(i);
1420 digit = HEX_DIGIT(key_digit);
1421 x = 16.0*x + (double)(digit & (16-2*half_eps));
1423 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1424 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1425 if ((digit & half_eps) != 0) {
1426 round_up = 0;
1427 if ((digit & (3*half_eps-1)) != 0 ||
1428 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1429 round_up = 1;
1430 else
1431 for (i = key_digit-1; i >= 0; i--)
1432 if (HEX_DIGIT(i) != 0) {
1433 round_up = 1;
1434 break;
1436 if (round_up == 1) {
1437 x += 2*half_eps;
1438 if (top_exp == DBL_MAX_EXP &&
1439 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1440 /* overflow corner case: pre-rounded value <
1441 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1442 goto overflow_error;
1445 x = sign * ldexp(x, (int)(exp+4*key_digit));
1447 finished:
1448 result_as_float = Py_BuildValue("(d)", x);
1449 if (result_as_float == NULL)
1450 return NULL;
1451 result = PyObject_CallObject(cls, result_as_float);
1452 Py_DECREF(result_as_float);
1453 return result;
1455 overflow_error:
1456 PyErr_SetString(PyExc_OverflowError,
1457 "hexadecimal value too large to represent as a float");
1458 return NULL;
1460 parse_error:
1461 PyErr_SetString(PyExc_ValueError,
1462 "invalid hexadecimal floating-point string");
1463 return NULL;
1465 insane_length_error:
1466 PyErr_SetString(PyExc_ValueError,
1467 "hexadecimal string too long to convert");
1468 return NULL;
1471 PyDoc_STRVAR(float_fromhex_doc,
1472 "float.fromhex(string) -> float\n\
1474 Create a floating-point number from a hexadecimal string.\n\
1475 >>> float.fromhex('0x1.ffffp10')\n\
1476 2047.984375\n\
1477 >>> float.fromhex('-0x1p-1074')\n\
1478 -4.9406564584124654e-324");
1481 static PyObject *
1482 float_as_integer_ratio(PyObject *v, PyObject *unused)
1484 double self;
1485 double float_part;
1486 int exponent;
1487 int i;
1489 PyObject *prev;
1490 PyObject *py_exponent = NULL;
1491 PyObject *numerator = NULL;
1492 PyObject *denominator = NULL;
1493 PyObject *result_pair = NULL;
1494 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
1496 #define INPLACE_UPDATE(obj, call) \
1497 prev = obj; \
1498 obj = call; \
1499 Py_DECREF(prev); \
1501 CONVERT_TO_DOUBLE(v, self);
1503 if (Py_IS_INFINITY(self)) {
1504 PyErr_SetString(PyExc_OverflowError,
1505 "Cannot pass infinity to float.as_integer_ratio.");
1506 return NULL;
1508 #ifdef Py_NAN
1509 if (Py_IS_NAN(self)) {
1510 PyErr_SetString(PyExc_ValueError,
1511 "Cannot pass NaN to float.as_integer_ratio.");
1512 return NULL;
1514 #endif
1516 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1517 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1518 PyFPE_END_PROTECT(float_part);
1520 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1521 float_part *= 2.0;
1522 exponent--;
1524 /* self == float_part * 2**exponent exactly and float_part is integral.
1525 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1526 to be truncated by PyLong_FromDouble(). */
1528 numerator = PyLong_FromDouble(float_part);
1529 if (numerator == NULL) goto error;
1531 /* fold in 2**exponent */
1532 denominator = PyLong_FromLong(1);
1533 py_exponent = PyLong_FromLong(labs((long)exponent));
1534 if (py_exponent == NULL) goto error;
1535 INPLACE_UPDATE(py_exponent,
1536 long_methods->nb_lshift(denominator, py_exponent));
1537 if (py_exponent == NULL) goto error;
1538 if (exponent > 0) {
1539 INPLACE_UPDATE(numerator,
1540 long_methods->nb_multiply(numerator, py_exponent));
1541 if (numerator == NULL) goto error;
1543 else {
1544 Py_DECREF(denominator);
1545 denominator = py_exponent;
1546 py_exponent = NULL;
1549 /* Returns ints instead of longs where possible */
1550 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1551 if (numerator == NULL) goto error;
1552 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1553 if (denominator == NULL) goto error;
1555 result_pair = PyTuple_Pack(2, numerator, denominator);
1557 #undef INPLACE_UPDATE
1558 error:
1559 Py_XDECREF(py_exponent);
1560 Py_XDECREF(denominator);
1561 Py_XDECREF(numerator);
1562 return result_pair;
1565 PyDoc_STRVAR(float_as_integer_ratio_doc,
1566 "float.as_integer_ratio() -> (int, int)\n"
1567 "\n"
1568 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
1569 "float and with a positive denominator.\n"
1570 "Raises OverflowError on infinities and a ValueError on NaNs.\n"
1571 "\n"
1572 ">>> (10.0).as_integer_ratio()\n"
1573 "(10, 1)\n"
1574 ">>> (0.0).as_integer_ratio()\n"
1575 "(0, 1)\n"
1576 ">>> (-.25).as_integer_ratio()\n"
1577 "(-1, 4)");
1580 static PyObject *
1581 float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1583 static PyObject *
1584 float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1586 PyObject *x = Py_False; /* Integer zero */
1587 static char *kwlist[] = {"x", 0};
1589 if (type != &PyFloat_Type)
1590 return float_subtype_new(type, args, kwds); /* Wimp out */
1591 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1592 return NULL;
1593 /* If it's a string, but not a string subclass, use
1594 PyFloat_FromString. */
1595 if (PyString_CheckExact(x))
1596 return PyFloat_FromString(x, NULL);
1597 return PyNumber_Float(x);
1600 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1601 first create a regular float from whatever arguments we got,
1602 then allocate a subtype instance and initialize its ob_fval
1603 from the regular float. The regular float is then thrown away.
1605 static PyObject *
1606 float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1608 PyObject *tmp, *newobj;
1610 assert(PyType_IsSubtype(type, &PyFloat_Type));
1611 tmp = float_new(&PyFloat_Type, args, kwds);
1612 if (tmp == NULL)
1613 return NULL;
1614 assert(PyFloat_CheckExact(tmp));
1615 newobj = type->tp_alloc(type, 0);
1616 if (newobj == NULL) {
1617 Py_DECREF(tmp);
1618 return NULL;
1620 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1621 Py_DECREF(tmp);
1622 return newobj;
1625 static PyObject *
1626 float_getnewargs(PyFloatObject *v)
1628 return Py_BuildValue("(d)", v->ob_fval);
1631 /* this is for the benefit of the pack/unpack routines below */
1633 typedef enum {
1634 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1635 } float_format_type;
1637 static float_format_type double_format, float_format;
1638 static float_format_type detected_double_format, detected_float_format;
1640 static PyObject *
1641 float_getformat(PyTypeObject *v, PyObject* arg)
1643 char* s;
1644 float_format_type r;
1646 if (!PyString_Check(arg)) {
1647 PyErr_Format(PyExc_TypeError,
1648 "__getformat__() argument must be string, not %.500s",
1649 Py_TYPE(arg)->tp_name);
1650 return NULL;
1652 s = PyString_AS_STRING(arg);
1653 if (strcmp(s, "double") == 0) {
1654 r = double_format;
1656 else if (strcmp(s, "float") == 0) {
1657 r = float_format;
1659 else {
1660 PyErr_SetString(PyExc_ValueError,
1661 "__getformat__() argument 1 must be "
1662 "'double' or 'float'");
1663 return NULL;
1666 switch (r) {
1667 case unknown_format:
1668 return PyString_FromString("unknown");
1669 case ieee_little_endian_format:
1670 return PyString_FromString("IEEE, little-endian");
1671 case ieee_big_endian_format:
1672 return PyString_FromString("IEEE, big-endian");
1673 default:
1674 Py_FatalError("insane float_format or double_format");
1675 return NULL;
1679 PyDoc_STRVAR(float_getformat_doc,
1680 "float.__getformat__(typestr) -> string\n"
1681 "\n"
1682 "You probably don't want to use this function. It exists mainly to be\n"
1683 "used in Python's test suite.\n"
1684 "\n"
1685 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1686 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1687 "format of floating point numbers used by the C type named by typestr.");
1689 static PyObject *
1690 float_setformat(PyTypeObject *v, PyObject* args)
1692 char* typestr;
1693 char* format;
1694 float_format_type f;
1695 float_format_type detected;
1696 float_format_type *p;
1698 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1699 return NULL;
1701 if (strcmp(typestr, "double") == 0) {
1702 p = &double_format;
1703 detected = detected_double_format;
1705 else if (strcmp(typestr, "float") == 0) {
1706 p = &float_format;
1707 detected = detected_float_format;
1709 else {
1710 PyErr_SetString(PyExc_ValueError,
1711 "__setformat__() argument 1 must "
1712 "be 'double' or 'float'");
1713 return NULL;
1716 if (strcmp(format, "unknown") == 0) {
1717 f = unknown_format;
1719 else if (strcmp(format, "IEEE, little-endian") == 0) {
1720 f = ieee_little_endian_format;
1722 else if (strcmp(format, "IEEE, big-endian") == 0) {
1723 f = ieee_big_endian_format;
1725 else {
1726 PyErr_SetString(PyExc_ValueError,
1727 "__setformat__() argument 2 must be "
1728 "'unknown', 'IEEE, little-endian' or "
1729 "'IEEE, big-endian'");
1730 return NULL;
1734 if (f != unknown_format && f != detected) {
1735 PyErr_Format(PyExc_ValueError,
1736 "can only set %s format to 'unknown' or the "
1737 "detected platform value", typestr);
1738 return NULL;
1741 *p = f;
1742 Py_RETURN_NONE;
1745 PyDoc_STRVAR(float_setformat_doc,
1746 "float.__setformat__(typestr, fmt) -> None\n"
1747 "\n"
1748 "You probably don't want to use this function. It exists mainly to be\n"
1749 "used in Python's test suite.\n"
1750 "\n"
1751 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1752 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1753 "one of the latter two if it appears to match the underlying C reality.\n"
1754 "\n"
1755 "Overrides the automatic determination of C-level floating point type.\n"
1756 "This affects how floats are converted to and from binary strings.");
1758 static PyObject *
1759 float_getzero(PyObject *v, void *closure)
1761 return PyFloat_FromDouble(0.0);
1764 static PyObject *
1765 float__format__(PyObject *self, PyObject *args)
1767 PyObject *format_spec;
1769 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1770 return NULL;
1771 if (PyBytes_Check(format_spec))
1772 return _PyFloat_FormatAdvanced(self,
1773 PyBytes_AS_STRING(format_spec),
1774 PyBytes_GET_SIZE(format_spec));
1775 if (PyUnicode_Check(format_spec)) {
1776 /* Convert format_spec to a str */
1777 PyObject *result;
1778 PyObject *str_spec = PyObject_Str(format_spec);
1780 if (str_spec == NULL)
1781 return NULL;
1783 result = _PyFloat_FormatAdvanced(self,
1784 PyBytes_AS_STRING(str_spec),
1785 PyBytes_GET_SIZE(str_spec));
1787 Py_DECREF(str_spec);
1788 return result;
1790 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1791 return NULL;
1794 PyDoc_STRVAR(float__format__doc,
1795 "float.__format__(format_spec) -> string\n"
1796 "\n"
1797 "Formats the float according to format_spec.");
1800 static PyMethodDef float_methods[] = {
1801 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1802 "Returns self, the complex conjugate of any float."},
1803 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1804 "Returns the Integral closest to x between 0 and x."},
1805 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1806 float_as_integer_ratio_doc},
1807 {"fromhex", (PyCFunction)float_fromhex,
1808 METH_O|METH_CLASS, float_fromhex_doc},
1809 {"hex", (PyCFunction)float_hex,
1810 METH_NOARGS, float_hex_doc},
1811 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1812 "Returns True if the float is an integer."},
1813 #if 0
1814 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1815 "Returns True if the float is positive or negative infinite."},
1816 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1817 "Returns True if the float is finite, neither infinite nor NaN."},
1818 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1819 "Returns True if the float is not a number (NaN)."},
1820 #endif
1821 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1822 {"__getformat__", (PyCFunction)float_getformat,
1823 METH_O|METH_CLASS, float_getformat_doc},
1824 {"__setformat__", (PyCFunction)float_setformat,
1825 METH_VARARGS|METH_CLASS, float_setformat_doc},
1826 {"__format__", (PyCFunction)float__format__,
1827 METH_VARARGS, float__format__doc},
1828 {NULL, NULL} /* sentinel */
1831 static PyGetSetDef float_getset[] = {
1832 {"real",
1833 (getter)float_float, (setter)NULL,
1834 "the real part of a complex number",
1835 NULL},
1836 {"imag",
1837 (getter)float_getzero, (setter)NULL,
1838 "the imaginary part of a complex number",
1839 NULL},
1840 {NULL} /* Sentinel */
1843 PyDoc_STRVAR(float_doc,
1844 "float(x) -> floating point number\n\
1846 Convert a string or number to a floating point number, if possible.");
1849 static PyNumberMethods float_as_number = {
1850 float_add, /*nb_add*/
1851 float_sub, /*nb_subtract*/
1852 float_mul, /*nb_multiply*/
1853 float_classic_div, /*nb_divide*/
1854 float_rem, /*nb_remainder*/
1855 float_divmod, /*nb_divmod*/
1856 float_pow, /*nb_power*/
1857 (unaryfunc)float_neg, /*nb_negative*/
1858 (unaryfunc)float_float, /*nb_positive*/
1859 (unaryfunc)float_abs, /*nb_absolute*/
1860 (inquiry)float_nonzero, /*nb_nonzero*/
1861 0, /*nb_invert*/
1862 0, /*nb_lshift*/
1863 0, /*nb_rshift*/
1864 0, /*nb_and*/
1865 0, /*nb_xor*/
1866 0, /*nb_or*/
1867 float_coerce, /*nb_coerce*/
1868 float_trunc, /*nb_int*/
1869 float_long, /*nb_long*/
1870 float_float, /*nb_float*/
1871 0, /* nb_oct */
1872 0, /* nb_hex */
1873 0, /* nb_inplace_add */
1874 0, /* nb_inplace_subtract */
1875 0, /* nb_inplace_multiply */
1876 0, /* nb_inplace_divide */
1877 0, /* nb_inplace_remainder */
1878 0, /* nb_inplace_power */
1879 0, /* nb_inplace_lshift */
1880 0, /* nb_inplace_rshift */
1881 0, /* nb_inplace_and */
1882 0, /* nb_inplace_xor */
1883 0, /* nb_inplace_or */
1884 float_floor_div, /* nb_floor_divide */
1885 float_div, /* nb_true_divide */
1886 0, /* nb_inplace_floor_divide */
1887 0, /* nb_inplace_true_divide */
1890 PyTypeObject PyFloat_Type = {
1891 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1892 "float",
1893 sizeof(PyFloatObject),
1895 (destructor)float_dealloc, /* tp_dealloc */
1896 (printfunc)float_print, /* tp_print */
1897 0, /* tp_getattr */
1898 0, /* tp_setattr */
1899 0, /* tp_compare */
1900 (reprfunc)float_repr, /* tp_repr */
1901 &float_as_number, /* tp_as_number */
1902 0, /* tp_as_sequence */
1903 0, /* tp_as_mapping */
1904 (hashfunc)float_hash, /* tp_hash */
1905 0, /* tp_call */
1906 (reprfunc)float_str, /* tp_str */
1907 PyObject_GenericGetAttr, /* tp_getattro */
1908 0, /* tp_setattro */
1909 0, /* tp_as_buffer */
1910 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1911 Py_TPFLAGS_BASETYPE, /* tp_flags */
1912 float_doc, /* tp_doc */
1913 0, /* tp_traverse */
1914 0, /* tp_clear */
1915 float_richcompare, /* tp_richcompare */
1916 0, /* tp_weaklistoffset */
1917 0, /* tp_iter */
1918 0, /* tp_iternext */
1919 float_methods, /* tp_methods */
1920 0, /* tp_members */
1921 float_getset, /* tp_getset */
1922 0, /* tp_base */
1923 0, /* tp_dict */
1924 0, /* tp_descr_get */
1925 0, /* tp_descr_set */
1926 0, /* tp_dictoffset */
1927 0, /* tp_init */
1928 0, /* tp_alloc */
1929 float_new, /* tp_new */
1932 void
1933 _PyFloat_Init(void)
1935 /* We attempt to determine if this machine is using IEEE
1936 floating point formats by peering at the bits of some
1937 carefully chosen values. If it looks like we are on an
1938 IEEE platform, the float packing/unpacking routines can
1939 just copy bits, if not they resort to arithmetic & shifts
1940 and masks. The shifts & masks approach works on all finite
1941 values, but what happens to infinities, NaNs and signed
1942 zeroes on packing is an accident, and attempting to unpack
1943 a NaN or an infinity will raise an exception.
1945 Note that if we're on some whacked-out platform which uses
1946 IEEE formats but isn't strictly little-endian or big-
1947 endian, we will fall back to the portable shifts & masks
1948 method. */
1950 #if SIZEOF_DOUBLE == 8
1952 double x = 9006104071832581.0;
1953 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1954 detected_double_format = ieee_big_endian_format;
1955 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1956 detected_double_format = ieee_little_endian_format;
1957 else
1958 detected_double_format = unknown_format;
1960 #else
1961 detected_double_format = unknown_format;
1962 #endif
1964 #if SIZEOF_FLOAT == 4
1966 float y = 16711938.0;
1967 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1968 detected_float_format = ieee_big_endian_format;
1969 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1970 detected_float_format = ieee_little_endian_format;
1971 else
1972 detected_float_format = unknown_format;
1974 #else
1975 detected_float_format = unknown_format;
1976 #endif
1978 double_format = detected_double_format;
1979 float_format = detected_float_format;
1981 /* Init float info */
1982 if (FloatInfoType.tp_name == 0)
1983 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
1987 PyFloat_ClearFreeList(void)
1989 PyFloatObject *p;
1990 PyFloatBlock *list, *next;
1991 int i;
1992 int u; /* remaining unfreed ints per block */
1993 int freelist_size = 0;
1995 list = block_list;
1996 block_list = NULL;
1997 free_list = NULL;
1998 while (list != NULL) {
1999 u = 0;
2000 for (i = 0, p = &list->objects[0];
2001 i < N_FLOATOBJECTS;
2002 i++, p++) {
2003 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
2004 u++;
2006 next = list->next;
2007 if (u) {
2008 list->next = block_list;
2009 block_list = list;
2010 for (i = 0, p = &list->objects[0];
2011 i < N_FLOATOBJECTS;
2012 i++, p++) {
2013 if (!PyFloat_CheckExact(p) ||
2014 Py_REFCNT(p) == 0) {
2015 Py_TYPE(p) = (struct _typeobject *)
2016 free_list;
2017 free_list = p;
2021 else {
2022 PyMem_FREE(list);
2024 freelist_size += u;
2025 list = next;
2027 return freelist_size;
2030 void
2031 PyFloat_Fini(void)
2033 PyFloatObject *p;
2034 PyFloatBlock *list;
2035 int i;
2036 int u; /* total unfreed floats per block */
2038 u = PyFloat_ClearFreeList();
2040 if (!Py_VerboseFlag)
2041 return;
2042 fprintf(stderr, "# cleanup floats");
2043 if (!u) {
2044 fprintf(stderr, "\n");
2046 else {
2047 fprintf(stderr,
2048 ": %d unfreed float%s\n",
2049 u, u == 1 ? "" : "s");
2051 if (Py_VerboseFlag > 1) {
2052 list = block_list;
2053 while (list != NULL) {
2054 for (i = 0, p = &list->objects[0];
2055 i < N_FLOATOBJECTS;
2056 i++, p++) {
2057 if (PyFloat_CheckExact(p) &&
2058 Py_REFCNT(p) != 0) {
2059 char buf[100];
2060 PyFloat_AsString(buf, p);
2061 /* XXX(twouters) cast refcount to
2062 long until %zd is universally
2063 available
2065 fprintf(stderr,
2066 "# <float at %p, refcnt=%ld, val=%s>\n",
2067 p, (long)Py_REFCNT(p), buf);
2070 list = list->next;
2075 /*----------------------------------------------------------------------------
2076 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
2079 _PyFloat_Pack4(double x, unsigned char *p, int le)
2081 if (float_format == unknown_format) {
2082 unsigned char sign;
2083 int e;
2084 double f;
2085 unsigned int fbits;
2086 int incr = 1;
2088 if (le) {
2089 p += 3;
2090 incr = -1;
2093 if (x < 0) {
2094 sign = 1;
2095 x = -x;
2097 else
2098 sign = 0;
2100 f = frexp(x, &e);
2102 /* Normalize f to be in the range [1.0, 2.0) */
2103 if (0.5 <= f && f < 1.0) {
2104 f *= 2.0;
2105 e--;
2107 else if (f == 0.0)
2108 e = 0;
2109 else {
2110 PyErr_SetString(PyExc_SystemError,
2111 "frexp() result out of range");
2112 return -1;
2115 if (e >= 128)
2116 goto Overflow;
2117 else if (e < -126) {
2118 /* Gradual underflow */
2119 f = ldexp(f, 126 + e);
2120 e = 0;
2122 else if (!(e == 0 && f == 0.0)) {
2123 e += 127;
2124 f -= 1.0; /* Get rid of leading 1 */
2127 f *= 8388608.0; /* 2**23 */
2128 fbits = (unsigned int)(f + 0.5); /* Round */
2129 assert(fbits <= 8388608);
2130 if (fbits >> 23) {
2131 /* The carry propagated out of a string of 23 1 bits. */
2132 fbits = 0;
2133 ++e;
2134 if (e >= 255)
2135 goto Overflow;
2138 /* First byte */
2139 *p = (sign << 7) | (e >> 1);
2140 p += incr;
2142 /* Second byte */
2143 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2144 p += incr;
2146 /* Third byte */
2147 *p = (fbits >> 8) & 0xFF;
2148 p += incr;
2150 /* Fourth byte */
2151 *p = fbits & 0xFF;
2153 /* Done */
2154 return 0;
2157 else {
2158 float y = (float)x;
2159 const char *s = (char*)&y;
2160 int i, incr = 1;
2162 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2163 goto Overflow;
2165 if ((float_format == ieee_little_endian_format && !le)
2166 || (float_format == ieee_big_endian_format && le)) {
2167 p += 3;
2168 incr = -1;
2171 for (i = 0; i < 4; i++) {
2172 *p = *s++;
2173 p += incr;
2175 return 0;
2177 Overflow:
2178 PyErr_SetString(PyExc_OverflowError,
2179 "float too large to pack with f format");
2180 return -1;
2184 _PyFloat_Pack8(double x, unsigned char *p, int le)
2186 if (double_format == unknown_format) {
2187 unsigned char sign;
2188 int e;
2189 double f;
2190 unsigned int fhi, flo;
2191 int incr = 1;
2193 if (le) {
2194 p += 7;
2195 incr = -1;
2198 if (x < 0) {
2199 sign = 1;
2200 x = -x;
2202 else
2203 sign = 0;
2205 f = frexp(x, &e);
2207 /* Normalize f to be in the range [1.0, 2.0) */
2208 if (0.5 <= f && f < 1.0) {
2209 f *= 2.0;
2210 e--;
2212 else if (f == 0.0)
2213 e = 0;
2214 else {
2215 PyErr_SetString(PyExc_SystemError,
2216 "frexp() result out of range");
2217 return -1;
2220 if (e >= 1024)
2221 goto Overflow;
2222 else if (e < -1022) {
2223 /* Gradual underflow */
2224 f = ldexp(f, 1022 + e);
2225 e = 0;
2227 else if (!(e == 0 && f == 0.0)) {
2228 e += 1023;
2229 f -= 1.0; /* Get rid of leading 1 */
2232 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2233 f *= 268435456.0; /* 2**28 */
2234 fhi = (unsigned int)f; /* Truncate */
2235 assert(fhi < 268435456);
2237 f -= (double)fhi;
2238 f *= 16777216.0; /* 2**24 */
2239 flo = (unsigned int)(f + 0.5); /* Round */
2240 assert(flo <= 16777216);
2241 if (flo >> 24) {
2242 /* The carry propagated out of a string of 24 1 bits. */
2243 flo = 0;
2244 ++fhi;
2245 if (fhi >> 28) {
2246 /* And it also progagated out of the next 28 bits. */
2247 fhi = 0;
2248 ++e;
2249 if (e >= 2047)
2250 goto Overflow;
2254 /* First byte */
2255 *p = (sign << 7) | (e >> 4);
2256 p += incr;
2258 /* Second byte */
2259 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2260 p += incr;
2262 /* Third byte */
2263 *p = (fhi >> 16) & 0xFF;
2264 p += incr;
2266 /* Fourth byte */
2267 *p = (fhi >> 8) & 0xFF;
2268 p += incr;
2270 /* Fifth byte */
2271 *p = fhi & 0xFF;
2272 p += incr;
2274 /* Sixth byte */
2275 *p = (flo >> 16) & 0xFF;
2276 p += incr;
2278 /* Seventh byte */
2279 *p = (flo >> 8) & 0xFF;
2280 p += incr;
2282 /* Eighth byte */
2283 *p = flo & 0xFF;
2284 p += incr;
2286 /* Done */
2287 return 0;
2289 Overflow:
2290 PyErr_SetString(PyExc_OverflowError,
2291 "float too large to pack with d format");
2292 return -1;
2294 else {
2295 const char *s = (char*)&x;
2296 int i, incr = 1;
2298 if ((double_format == ieee_little_endian_format && !le)
2299 || (double_format == ieee_big_endian_format && le)) {
2300 p += 7;
2301 incr = -1;
2304 for (i = 0; i < 8; i++) {
2305 *p = *s++;
2306 p += incr;
2308 return 0;
2312 double
2313 _PyFloat_Unpack4(const unsigned char *p, int le)
2315 if (float_format == unknown_format) {
2316 unsigned char sign;
2317 int e;
2318 unsigned int f;
2319 double x;
2320 int incr = 1;
2322 if (le) {
2323 p += 3;
2324 incr = -1;
2327 /* First byte */
2328 sign = (*p >> 7) & 1;
2329 e = (*p & 0x7F) << 1;
2330 p += incr;
2332 /* Second byte */
2333 e |= (*p >> 7) & 1;
2334 f = (*p & 0x7F) << 16;
2335 p += incr;
2337 if (e == 255) {
2338 PyErr_SetString(
2339 PyExc_ValueError,
2340 "can't unpack IEEE 754 special value "
2341 "on non-IEEE platform");
2342 return -1;
2345 /* Third byte */
2346 f |= *p << 8;
2347 p += incr;
2349 /* Fourth byte */
2350 f |= *p;
2352 x = (double)f / 8388608.0;
2354 /* XXX This sadly ignores Inf/NaN issues */
2355 if (e == 0)
2356 e = -126;
2357 else {
2358 x += 1.0;
2359 e -= 127;
2361 x = ldexp(x, e);
2363 if (sign)
2364 x = -x;
2366 return x;
2368 else {
2369 float x;
2371 if ((float_format == ieee_little_endian_format && !le)
2372 || (float_format == ieee_big_endian_format && le)) {
2373 char buf[4];
2374 char *d = &buf[3];
2375 int i;
2377 for (i = 0; i < 4; i++) {
2378 *d-- = *p++;
2380 memcpy(&x, buf, 4);
2382 else {
2383 memcpy(&x, p, 4);
2386 return x;
2390 double
2391 _PyFloat_Unpack8(const unsigned char *p, int le)
2393 if (double_format == unknown_format) {
2394 unsigned char sign;
2395 int e;
2396 unsigned int fhi, flo;
2397 double x;
2398 int incr = 1;
2400 if (le) {
2401 p += 7;
2402 incr = -1;
2405 /* First byte */
2406 sign = (*p >> 7) & 1;
2407 e = (*p & 0x7F) << 4;
2409 p += incr;
2411 /* Second byte */
2412 e |= (*p >> 4) & 0xF;
2413 fhi = (*p & 0xF) << 24;
2414 p += incr;
2416 if (e == 2047) {
2417 PyErr_SetString(
2418 PyExc_ValueError,
2419 "can't unpack IEEE 754 special value "
2420 "on non-IEEE platform");
2421 return -1.0;
2424 /* Third byte */
2425 fhi |= *p << 16;
2426 p += incr;
2428 /* Fourth byte */
2429 fhi |= *p << 8;
2430 p += incr;
2432 /* Fifth byte */
2433 fhi |= *p;
2434 p += incr;
2436 /* Sixth byte */
2437 flo = *p << 16;
2438 p += incr;
2440 /* Seventh byte */
2441 flo |= *p << 8;
2442 p += incr;
2444 /* Eighth byte */
2445 flo |= *p;
2447 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2448 x /= 268435456.0; /* 2**28 */
2450 if (e == 0)
2451 e = -1022;
2452 else {
2453 x += 1.0;
2454 e -= 1023;
2456 x = ldexp(x, e);
2458 if (sign)
2459 x = -x;
2461 return x;
2463 else {
2464 double x;
2466 if ((double_format == ieee_little_endian_format && !le)
2467 || (double_format == ieee_big_endian_format && le)) {
2468 char buf[8];
2469 char *d = &buf[7];
2470 int i;
2472 for (i = 0; i < 8; i++) {
2473 *d-- = *p++;
2475 memcpy(&x, buf, 8);
2477 else {
2478 memcpy(&x, p, 8);
2481 return x;