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. */
15 #define MAX(x, y) ((x) < (y) ? (y) : (x))
16 #define MIN(x, y) ((x) < (y) ? (x) : (y))
23 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24 extern int finite(double);
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))
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
*
46 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
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
;
55 Py_TYPE(q
) = (struct _typeobject
*)(q
-1);
57 return p
+ N_FLOATOBJECTS
- 1;
72 static PyTypeObject FloatInfoType
= {0, 0, 0, 0, 0, 0};
74 PyDoc_STRVAR(floatinfo__doc__
,
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) "
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
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 "
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"},
101 static PyStructSequence_Desc floatinfo_desc
= {
102 "sys.float_info", /* name */
103 floatinfo__doc__
, /* doc */
104 floatinfo_fields
, /* fields */
109 PyFloat_GetInfo(void)
114 floatinfo
= PyStructSequence_New(&FloatInfoType
);
115 if (floatinfo
== 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))
125 SetIntFlag(DBL_MAX_EXP
);
126 SetIntFlag(DBL_MAX_10_EXP
);
128 SetIntFlag(DBL_MIN_EXP
);
129 SetIntFlag(DBL_MIN_10_EXP
);
131 SetIntFlag(DBL_MANT_DIG
);
132 SetDblFlag(DBL_EPSILON
);
133 SetIntFlag(FLT_RADIX
);
134 SetIntFlag(FLT_ROUNDS
);
138 if (PyErr_Occurred()) {
146 PyFloat_FromDouble(double fval
)
148 register PyFloatObject
*op
;
149 if (free_list
== NULL
) {
150 if ((free_list
= fill_free_list()) == NULL
)
153 /* Inline PyObject_New */
155 free_list
= (PyFloatObject
*)Py_TYPE(op
);
156 PyObject_INIT(op
, &PyFloat_Type
);
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 **************************************************************************/
178 PyFloat_FromString(PyObject
*v
, char **pend
)
180 const char *s
, *last
, *end
;
182 char buffer
[256]; /* for errors */
183 #ifdef Py_USING_UNICODE
184 char *s_buffer
= NULL
;
187 PyObject
*result
= NULL
;
191 if (PyString_Check(v
)) {
192 s
= PyString_AS_STRING(v
);
193 len
= PyString_GET_SIZE(v
);
195 #ifdef Py_USING_UNICODE
196 else if (PyUnicode_Check(v
)) {
197 s_buffer
= (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v
)+1);
198 if (s_buffer
== NULL
)
199 return PyErr_NoMemory();
200 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
201 PyUnicode_GET_SIZE(v
),
209 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
210 PyErr_SetString(PyExc_TypeError
,
211 "float() argument must be a string or a number");
216 while (Py_ISSPACE(*s
))
218 /* We don't care about overflow or underflow. If the platform
219 * supports them, infinities and signed zeroes (on underflow) are
221 x
= PyOS_string_to_double(s
, (char **)&end
, NULL
);
222 if (x
== -1.0 && PyErr_Occurred())
224 while (Py_ISSPACE(*end
))
227 result
= PyFloat_FromDouble(x
);
229 PyOS_snprintf(buffer
, sizeof(buffer
),
230 "invalid literal for float(): %.200s", s
);
231 PyErr_SetString(PyExc_ValueError
, buffer
);
236 #ifdef Py_USING_UNICODE
238 PyMem_FREE(s_buffer
);
244 float_dealloc(PyFloatObject
*op
)
246 if (PyFloat_CheckExact(op
)) {
247 Py_TYPE(op
) = (struct _typeobject
*)free_list
;
251 Py_TYPE(op
)->tp_free((PyObject
*)op
);
255 PyFloat_AsDouble(PyObject
*op
)
261 if (op
&& PyFloat_Check(op
))
262 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
269 if ((nb
= Py_TYPE(op
)->tp_as_number
) == NULL
|| nb
->nb_float
== NULL
) {
270 PyErr_SetString(PyExc_TypeError
, "a float is required");
274 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
277 if (!PyFloat_Check(fo
)) {
278 PyErr_SetString(PyExc_TypeError
,
279 "nb_float should return float object");
283 val
= PyFloat_AS_DOUBLE(fo
);
291 /* Macro and helper that convert PyObject obj to a C double and store
292 the value in dbl; this replaces the functionality of the coercion
293 slot function. If conversion to double raises an exception, obj is
294 set to NULL, and the function invoking this macro returns NULL. If
295 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
296 stored in obj, and returned from the function invoking this macro.
298 #define CONVERT_TO_DOUBLE(obj, dbl) \
299 if (PyFloat_Check(obj)) \
300 dbl = PyFloat_AS_DOUBLE(obj); \
301 else if (convert_to_double(&(obj), &(dbl)) < 0) \
305 convert_to_double(PyObject
**v
, double *dbl
)
307 register PyObject
*obj
= *v
;
309 if (PyInt_Check(obj
)) {
310 *dbl
= (double)PyInt_AS_LONG(obj
);
312 else if (PyLong_Check(obj
)) {
313 *dbl
= PyLong_AsDouble(obj
);
314 if (*dbl
== -1.0 && PyErr_Occurred()) {
320 Py_INCREF(Py_NotImplemented
);
321 *v
= Py_NotImplemented
;
327 /* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
328 XXX they pass a char buffer without passing a length.
331 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
333 char *tmp
= PyOS_double_to_string(v
->ob_fval
, 'g',
334 PyFloat_STR_PRECISION
,
335 Py_DTSF_ADD_DOT_0
, NULL
);
341 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
343 char * tmp
= PyOS_double_to_string(v
->ob_fval
, 'r', 0,
344 Py_DTSF_ADD_DOT_0
, NULL
);
351 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
354 if (flags
& Py_PRINT_RAW
)
355 buf
= PyOS_double_to_string(v
->ob_fval
,
356 'g', PyFloat_STR_PRECISION
,
357 Py_DTSF_ADD_DOT_0
, NULL
);
359 buf
= PyOS_double_to_string(v
->ob_fval
,
360 'r', 0, Py_DTSF_ADD_DOT_0
, NULL
);
361 Py_BEGIN_ALLOW_THREADS
369 float_str_or_repr(PyFloatObject
*v
, int precision
, char format_code
)
372 char *buf
= PyOS_double_to_string(PyFloat_AS_DOUBLE(v
),
373 format_code
, precision
,
377 return PyErr_NoMemory();
378 result
= PyString_FromString(buf
);
384 float_repr(PyFloatObject
*v
)
386 return float_str_or_repr(v
, 0, 'r');
390 float_str(PyFloatObject
*v
)
392 return float_str_or_repr(v
, PyFloat_STR_PRECISION
, 'g');
395 /* Comparison is pretty much a nightmare. When comparing float to float,
396 * we do it as straightforwardly (and long-windedly) as conceivable, so
397 * that, e.g., Python x == y delivers the same result as the platform
398 * C x == y when x and/or y is a NaN.
399 * When mixing float with an integer type, there's no good *uniform* approach.
400 * Converting the double to an integer obviously doesn't work, since we
401 * may lose info from fractional bits. Converting the integer to a double
402 * also has two failure modes: (1) a long int may trigger overflow (too
403 * large to fit in the dynamic range of a C double); (2) even a C long may have
404 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
405 * 63 bits of precision, but a C double probably has only 53), and then
406 * we can falsely claim equality when low-order integer bits are lost by
407 * coercion to double. So this part is painful too.
411 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
416 assert(PyFloat_Check(v
));
417 i
= PyFloat_AS_DOUBLE(v
);
419 /* Switch on the type of w. Set i and j to doubles to be compared,
420 * and op to the richcomp to use.
422 if (PyFloat_Check(w
))
423 j
= PyFloat_AS_DOUBLE(w
);
425 else if (!Py_IS_FINITE(i
)) {
426 if (PyInt_Check(w
) || PyLong_Check(w
))
427 /* If i is an infinity, its magnitude exceeds any
428 * finite integer, so it doesn't matter which int we
429 * compare i with. If i is a NaN, similarly.
436 else if (PyInt_Check(w
)) {
437 long jj
= PyInt_AS_LONG(w
);
438 /* In the worst realistic case I can imagine, C double is a
439 * Cray single with 48 bits of precision, and long has 64
443 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
445 /* Needs more than 48 bits. Make it take the
449 PyObject
*ww
= PyLong_FromLong(jj
);
453 result
= float_richcompare(v
, ww
, op
);
459 assert((long)j
== jj
);
462 else if (PyLong_Check(w
)) {
463 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
464 int wsign
= _PyLong_Sign(w
);
468 if (vsign
!= wsign
) {
469 /* Magnitudes are irrelevant -- the signs alone
470 * determine the outcome.
476 /* The signs are the same. */
477 /* Convert w to a double if it fits. In particular, 0 fits. */
478 nbits
= _PyLong_NumBits(w
);
479 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
480 /* This long is so large that size_t isn't big enough
481 * to hold the # of bits. Replace with little doubles
482 * that give the same outcome -- w is so large that
483 * its magnitude must exceed the magnitude of any
493 j
= PyLong_AsDouble(w
);
494 /* It's impossible that <= 48 bits overflowed. */
495 assert(j
!= -1.0 || ! PyErr_Occurred());
498 assert(wsign
!= 0); /* else nbits was 0 */
499 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
500 * not 0, we would have taken the
501 * vsign != wsign branch at the start */
502 /* We want to work with non-negative numbers. */
504 /* "Multiply both sides" by -1; this also swaps the
508 op
= _Py_SwappedOp
[op
];
511 (void) frexp(i
, &exponent
);
512 /* exponent is the # of bits in v before the radix point;
513 * we know that nbits (the # of bits in w) > 48 at this point
515 if (exponent
< 0 || (size_t)exponent
< nbits
) {
520 if ((size_t)exponent
> nbits
) {
525 /* v and w have the same number of bits before the radix
526 * point. Construct two longs that have the same comparison
532 PyObject
*result
= NULL
;
533 PyObject
*one
= NULL
;
538 ww
= PyNumber_Negative(w
);
545 fracpart
= modf(i
, &intpart
);
546 vv
= PyLong_FromDouble(intpart
);
550 if (fracpart
!= 0.0) {
551 /* Shift left, and or a 1 bit into vv
552 * to represent the lost fraction.
556 one
= PyInt_FromLong(1);
560 temp
= PyNumber_Lshift(ww
, one
);
566 temp
= PyNumber_Lshift(vv
, one
);
572 temp
= PyNumber_Or(vv
, one
);
579 r
= PyObject_RichCompareBool(vv
, ww
, op
);
582 result
= PyBool_FromLong(r
);
589 } /* else if (PyLong_Check(w)) */
591 else /* w isn't float, int, or long */
595 PyFPE_START_PROTECT("richcompare", return NULL
)
617 return PyBool_FromLong(r
);
620 Py_INCREF(Py_NotImplemented
);
621 return Py_NotImplemented
;
625 float_hash(PyFloatObject
*v
)
627 return _Py_HashDouble(v
->ob_fval
);
631 float_add(PyObject
*v
, PyObject
*w
)
634 CONVERT_TO_DOUBLE(v
, a
);
635 CONVERT_TO_DOUBLE(w
, b
);
636 PyFPE_START_PROTECT("add", return 0)
639 return PyFloat_FromDouble(a
);
643 float_sub(PyObject
*v
, PyObject
*w
)
646 CONVERT_TO_DOUBLE(v
, a
);
647 CONVERT_TO_DOUBLE(w
, b
);
648 PyFPE_START_PROTECT("subtract", return 0)
651 return PyFloat_FromDouble(a
);
655 float_mul(PyObject
*v
, PyObject
*w
)
658 CONVERT_TO_DOUBLE(v
, a
);
659 CONVERT_TO_DOUBLE(w
, b
);
660 PyFPE_START_PROTECT("multiply", return 0)
663 return PyFloat_FromDouble(a
);
667 float_div(PyObject
*v
, PyObject
*w
)
670 CONVERT_TO_DOUBLE(v
, a
);
671 CONVERT_TO_DOUBLE(w
, b
);
674 PyErr_SetString(PyExc_ZeroDivisionError
,
679 PyFPE_START_PROTECT("divide", return 0)
682 return PyFloat_FromDouble(a
);
686 float_classic_div(PyObject
*v
, PyObject
*w
)
689 CONVERT_TO_DOUBLE(v
, a
);
690 CONVERT_TO_DOUBLE(w
, b
);
691 if (Py_DivisionWarningFlag
>= 2 &&
692 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
696 PyErr_SetString(PyExc_ZeroDivisionError
,
701 PyFPE_START_PROTECT("divide", return 0)
704 return PyFloat_FromDouble(a
);
708 float_rem(PyObject
*v
, PyObject
*w
)
712 CONVERT_TO_DOUBLE(v
, vx
);
713 CONVERT_TO_DOUBLE(w
, wx
);
716 PyErr_SetString(PyExc_ZeroDivisionError
,
721 PyFPE_START_PROTECT("modulo", return 0)
723 /* note: checking mod*wx < 0 is incorrect -- underflows to
724 0 if wx < sqrt(smallest nonzero double) */
725 if (mod
&& ((wx
< 0) != (mod
< 0))) {
728 PyFPE_END_PROTECT(mod
)
729 return PyFloat_FromDouble(mod
);
733 float_divmod(PyObject
*v
, PyObject
*w
)
736 double div
, mod
, floordiv
;
737 CONVERT_TO_DOUBLE(v
, vx
);
738 CONVERT_TO_DOUBLE(w
, wx
);
740 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
743 PyFPE_START_PROTECT("divmod", return 0)
745 /* fmod is typically exact, so vx-mod is *mathematically* an
746 exact multiple of wx. But this is fp arithmetic, and fp
747 vx - mod is an approximation; the result is that div may
748 not be an exact integral value after the division, although
749 it will always be very close to one.
751 div
= (vx
- mod
) / wx
;
753 /* ensure the remainder has the same sign as the denominator */
754 if ((wx
< 0) != (mod
< 0)) {
760 /* the remainder is zero, and in the presence of signed zeroes
761 fmod returns different results across platforms; ensure
762 it has the same sign as the denominator; we'd like to do
763 "mod = wx * 0.0", but that may get optimized away */
764 mod
*= mod
; /* hide "mod = +0" from optimizer */
768 /* snap quotient to nearest integral value */
770 floordiv
= floor(div
);
771 if (div
- floordiv
> 0.5)
775 /* div is zero - get the same sign as the true quotient */
776 div
*= div
; /* hide "div = +0" from optimizers */
777 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
779 PyFPE_END_PROTECT(floordiv
)
780 return Py_BuildValue("(dd)", floordiv
, mod
);
784 float_floor_div(PyObject
*v
, PyObject
*w
)
788 t
= float_divmod(v
, w
);
789 if (t
== NULL
|| t
== Py_NotImplemented
)
791 assert(PyTuple_CheckExact(t
));
792 r
= PyTuple_GET_ITEM(t
, 0);
799 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
803 if ((PyObject
*)z
!= Py_None
) {
804 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
805 "allowed unless all arguments are integers");
809 CONVERT_TO_DOUBLE(v
, iv
);
810 CONVERT_TO_DOUBLE(w
, iw
);
812 /* Sort out special cases here instead of relying on pow() */
813 if (iw
== 0) { /* v**0 is 1, even 0**0 */
814 return PyFloat_FromDouble(1.0);
816 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
818 PyErr_SetString(PyExc_ZeroDivisionError
,
819 "0.0 cannot be raised to a negative power");
822 return PyFloat_FromDouble(0.0);
824 if (iv
== 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
825 return PyFloat_FromDouble(1.0);
828 /* Whether this is an error is a mess, and bumps into libm
829 * bugs so we have to figure it out ourselves.
831 if (iw
!= floor(iw
)) {
832 PyErr_SetString(PyExc_ValueError
, "negative number "
833 "cannot be raised to a fractional power");
836 /* iw is an exact integer, albeit perhaps a very large one.
837 * -1 raised to an exact integer should never be exceptional.
838 * Alas, some libms (chiefly glibc as of early 2003) return
839 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
840 * happen to be representable in a *C* integer. That's a
841 * bug; we let that slide in math.pow() (which currently
842 * reflects all platform accidents), but not for Python's **.
844 if (iv
== -1.0 && Py_IS_FINITE(iw
)) {
845 /* Return 1 if iw is even, -1 if iw is odd; there's
846 * no guarantee that any C integral type is big
847 * enough to hold iw, so we have to check this
850 ix
= floor(iw
* 0.5) * 2.0;
851 return PyFloat_FromDouble(ix
== iw
? 1.0 : -1.0);
853 /* Else iv != -1.0, and overflow or underflow are possible.
854 * Unless we're to write pow() ourselves, we have to trust
855 * the platform to do this correctly.
859 PyFPE_START_PROTECT("pow", return NULL
)
861 PyFPE_END_PROTECT(ix
)
862 Py_ADJUST_ERANGE1(ix
);
864 /* We don't expect any errno value other than ERANGE, but
865 * the range of libm bugs appears unbounded.
867 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
871 return PyFloat_FromDouble(ix
);
875 float_neg(PyFloatObject
*v
)
877 return PyFloat_FromDouble(-v
->ob_fval
);
881 float_abs(PyFloatObject
*v
)
883 return PyFloat_FromDouble(fabs(v
->ob_fval
));
887 float_nonzero(PyFloatObject
*v
)
889 return v
->ob_fval
!= 0.0;
893 float_coerce(PyObject
**pv
, PyObject
**pw
)
895 if (PyInt_Check(*pw
)) {
896 long x
= PyInt_AsLong(*pw
);
897 *pw
= PyFloat_FromDouble((double)x
);
901 else if (PyLong_Check(*pw
)) {
902 double x
= PyLong_AsDouble(*pw
);
903 if (x
== -1.0 && PyErr_Occurred())
905 *pw
= PyFloat_FromDouble(x
);
909 else if (PyFloat_Check(*pw
)) {
914 return 1; /* Can't do it */
918 float_is_integer(PyObject
*v
)
920 double x
= PyFloat_AsDouble(v
);
923 if (x
== -1.0 && PyErr_Occurred())
925 if (!Py_IS_FINITE(x
))
928 PyFPE_START_PROTECT("is_integer", return NULL
)
929 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
932 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
942 float_is_inf(PyObject
*v
)
944 double x
= PyFloat_AsDouble(v
);
945 if (x
== -1.0 && PyErr_Occurred())
947 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
951 float_is_nan(PyObject
*v
)
953 double x
= PyFloat_AsDouble(v
);
954 if (x
== -1.0 && PyErr_Occurred())
956 return PyBool_FromLong((long)Py_IS_NAN(x
));
960 float_is_finite(PyObject
*v
)
962 double x
= PyFloat_AsDouble(v
);
963 if (x
== -1.0 && PyErr_Occurred())
965 return PyBool_FromLong((long)Py_IS_FINITE(x
));
970 float_trunc(PyObject
*v
)
972 double x
= PyFloat_AsDouble(v
);
973 double wholepart
; /* integral portion of x, rounded toward 0 */
975 (void)modf(x
, &wholepart
);
976 /* Try to get out cheap if this fits in a Python int. The attempt
977 * to cast to long must be protected, as C doesn't define what
978 * happens if the double is too big to fit in a long. Some rare
979 * systems raise an exception then (RISCOS was mentioned as one,
980 * and someone using a non-default option on Sun also bumped into
981 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
982 * still be vulnerable: if a long has more bits of precision than
983 * a double, casting MIN/MAX to double may yield an approximation,
984 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
985 * yield true from the C expression wholepart<=LONG_MAX, despite
986 * that wholepart is actually greater than LONG_MAX.
988 if (LONG_MIN
< wholepart
&& wholepart
< LONG_MAX
) {
989 const long aslong
= (long)wholepart
;
990 return PyInt_FromLong(aslong
);
992 return PyLong_FromDouble(wholepart
);
996 float_long(PyObject
*v
)
998 double x
= PyFloat_AsDouble(v
);
999 return PyLong_FromDouble(x
);
1003 float_float(PyObject
*v
)
1005 if (PyFloat_CheckExact(v
))
1008 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1012 /* turn ASCII hex characters into integer values and vice versa */
1015 char_from_hex(int x
)
1017 assert(0 <= x
&& x
< 16);
1018 return "0123456789abcdef"[x
];
1022 hex_from_char(char c
) {
1086 /* convert a float to a hexadecimal string */
1088 /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1089 of the form 4k+1. */
1090 #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1093 float_hex(PyObject
*v
)
1096 int e
, shift
, i
, si
, esign
;
1097 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1098 trailing NUL byte. */
1099 char s
[(TOHEX_NBITS
-1)/4+3];
1101 CONVERT_TO_DOUBLE(v
, x
);
1103 if (Py_IS_NAN(x
) || Py_IS_INFINITY(x
))
1104 return float_str((PyFloatObject
*)v
);
1107 if(copysign(1.0, x
) == -1.0)
1108 return PyString_FromString("-0x0.0p+0");
1110 return PyString_FromString("0x0.0p+0");
1113 m
= frexp(fabs(x
), &e
);
1114 shift
= 1 - MAX(DBL_MIN_EXP
- e
, 0);
1115 m
= ldexp(m
, shift
);
1119 s
[si
] = char_from_hex((int)m
);
1124 for (i
=0; i
< (TOHEX_NBITS
-1)/4; i
++) {
1126 s
[si
] = char_from_hex((int)m
);
1140 return PyString_FromFormat("-0x%sp%c%d", s
, esign
, e
);
1142 return PyString_FromFormat("0x%sp%c%d", s
, esign
, e
);
1145 PyDoc_STRVAR(float_hex_doc
,
1146 "float.hex() -> string\n\
1148 Return a hexadecimal representation of a floating-point number.\n\
1150 '-0x1.999999999999ap-4'\n\
1151 >>> 3.14159.hex()\n\
1152 '0x1.921f9f01b866ep+1'");
1154 /* Case-insensitive locale-independent string match used for nan and inf
1155 detection. t should be lower-case and null-terminated. Return a nonzero
1156 result if the first strlen(t) characters of s match t and 0 otherwise. */
1159 case_insensitive_match(const char *s
, const char *t
)
1161 while(*t
&& Py_TOLOWER(*s
) == *t
) {
1168 /* Convert a hexadecimal string to a float. */
1171 float_fromhex(PyObject
*cls
, PyObject
*arg
)
1173 PyObject
*result_as_float
, *result
;
1175 long exp
, top_exp
, lsb
, key_digit
;
1176 char *s
, *coeff_start
, *s_store
, *coeff_end
, *exp_start
, *s_end
;
1177 int half_eps
, digit
, round_up
, sign
=1;
1178 Py_ssize_t length
, ndigits
, fdigits
, i
;
1181 * For the sake of simplicity and correctness, we impose an artificial
1182 * limit on ndigits, the total number of hex digits in the coefficient
1183 * The limit is chosen to ensure that, writing exp for the exponent,
1185 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1186 * guaranteed to overflow (provided it's nonzero)
1188 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1189 * guaranteed to underflow to 0.
1191 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1192 * overflow in the calculation of exp and top_exp below.
1194 * More specifically, ndigits is assumed to satisfy the following
1197 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1198 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1200 * If either of these inequalities is not satisfied, a ValueError is
1201 * raised. Otherwise, write x for the value of the hex string, and
1202 * assume x is nonzero. Then
1204 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1206 * Now if exp > LONG_MAX/2 then:
1208 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1211 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1212 * double, so overflows. If exp < LONG_MIN/2, then
1214 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1215 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1216 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1218 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1219 * when converted to a C double.
1221 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1222 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1225 if (PyString_AsStringAndSize(arg
, &s
, &length
))
1229 /********************
1230 * Parse the string *
1231 ********************/
1233 /* leading whitespace and optional sign */
1234 while (Py_ISSPACE(*s
))
1243 /* infinities and nans */
1244 if (*s
== 'i' || *s
== 'I') {
1245 if (!case_insensitive_match(s
+1, "nf"))
1249 if (case_insensitive_match(s
, "inity"))
1253 if (*s
== 'n' || *s
== 'N') {
1254 if (!case_insensitive_match(s
+1, "an"))
1265 if (*s
== 'x' || *s
== 'X')
1271 /* coefficient: <integer> [. <fraction>] */
1273 while (hex_from_char(*s
) >= 0)
1278 while (hex_from_char(*s
) >= 0)
1285 /* ndigits = total # of hex digits; fdigits = # after point */
1286 ndigits
= coeff_end
- coeff_start
;
1287 fdigits
= coeff_end
- s_store
;
1290 if (ndigits
> MIN(DBL_MIN_EXP
- DBL_MANT_DIG
- LONG_MIN
/2,
1291 LONG_MAX
/2 + 1 - DBL_MAX_EXP
)/4)
1292 goto insane_length_error
;
1294 /* [p <exponent>] */
1295 if (*s
== 'p' || *s
== 'P') {
1298 if (*s
== '-' || *s
== '+')
1300 if (!('0' <= *s
&& *s
<= '9'))
1303 while ('0' <= *s
&& *s
<= '9')
1305 exp
= strtol(exp_start
, NULL
, 10);
1310 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1311 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1315 /*******************************************
1316 * Compute rounded value of the hex string *
1317 *******************************************/
1319 /* Discard leading zeros, and catch extreme overflow and underflow */
1320 while (ndigits
> 0 && HEX_DIGIT(ndigits
-1) == 0)
1322 if (ndigits
== 0 || exp
< LONG_MIN
/2) {
1326 if (exp
> LONG_MAX
/2)
1327 goto overflow_error
;
1329 /* Adjust exponent for fractional part. */
1330 exp
= exp
- 4*((long)fdigits
);
1332 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1333 top_exp
= exp
+ 4*((long)ndigits
- 1);
1334 for (digit
= HEX_DIGIT(ndigits
-1); digit
!= 0; digit
/= 2)
1337 /* catch almost all nonextreme cases of overflow and underflow here */
1338 if (top_exp
< DBL_MIN_EXP
- DBL_MANT_DIG
) {
1342 if (top_exp
> DBL_MAX_EXP
)
1343 goto overflow_error
;
1345 /* lsb = exponent of least significant bit of the *rounded* value.
1346 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1347 lsb
= MAX(top_exp
, (long)DBL_MIN_EXP
) - DBL_MANT_DIG
;
1351 /* no rounding required */
1352 for (i
= ndigits
-1; i
>= 0; i
--)
1353 x
= 16.0*x
+ HEX_DIGIT(i
);
1354 x
= ldexp(x
, (int)(exp
));
1357 /* rounding required. key_digit is the index of the hex digit
1358 containing the first bit to be rounded away. */
1359 half_eps
= 1 << (int)((lsb
- exp
- 1) % 4);
1360 key_digit
= (lsb
- exp
- 1) / 4;
1361 for (i
= ndigits
-1; i
> key_digit
; i
--)
1362 x
= 16.0*x
+ HEX_DIGIT(i
);
1363 digit
= HEX_DIGIT(key_digit
);
1364 x
= 16.0*x
+ (double)(digit
& (16-2*half_eps
));
1366 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1367 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1368 if ((digit
& half_eps
) != 0) {
1370 if ((digit
& (3*half_eps
-1)) != 0 ||
1371 (half_eps
== 8 && (HEX_DIGIT(key_digit
+1) & 1) != 0))
1374 for (i
= key_digit
-1; i
>= 0; i
--)
1375 if (HEX_DIGIT(i
) != 0) {
1379 if (round_up
== 1) {
1381 if (top_exp
== DBL_MAX_EXP
&&
1382 x
== ldexp((double)(2*half_eps
), DBL_MANT_DIG
))
1383 /* overflow corner case: pre-rounded value <
1384 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1385 goto overflow_error
;
1388 x
= ldexp(x
, (int)(exp
+4*key_digit
));
1391 /* optional trailing whitespace leading to the end of the string */
1392 while (Py_ISSPACE(*s
))
1396 result_as_float
= Py_BuildValue("(d)", sign
* x
);
1397 if (result_as_float
== NULL
)
1399 result
= PyObject_CallObject(cls
, result_as_float
);
1400 Py_DECREF(result_as_float
);
1404 PyErr_SetString(PyExc_OverflowError
,
1405 "hexadecimal value too large to represent as a float");
1409 PyErr_SetString(PyExc_ValueError
,
1410 "invalid hexadecimal floating-point string");
1413 insane_length_error
:
1414 PyErr_SetString(PyExc_ValueError
,
1415 "hexadecimal string too long to convert");
1419 PyDoc_STRVAR(float_fromhex_doc
,
1420 "float.fromhex(string) -> float\n\
1422 Create a floating-point number from a hexadecimal string.\n\
1423 >>> float.fromhex('0x1.ffffp10')\n\
1425 >>> float.fromhex('-0x1p-1074')\n\
1426 -4.9406564584124654e-324");
1430 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
1438 PyObject
*py_exponent
= NULL
;
1439 PyObject
*numerator
= NULL
;
1440 PyObject
*denominator
= NULL
;
1441 PyObject
*result_pair
= NULL
;
1442 PyNumberMethods
*long_methods
= PyLong_Type
.tp_as_number
;
1444 #define INPLACE_UPDATE(obj, call) \
1449 CONVERT_TO_DOUBLE(v, self);
1451 if (Py_IS_INFINITY(self
)) {
1452 PyErr_SetString(PyExc_OverflowError
,
1453 "Cannot pass infinity to float.as_integer_ratio.");
1457 if (Py_IS_NAN(self
)) {
1458 PyErr_SetString(PyExc_ValueError
,
1459 "Cannot pass NaN to float.as_integer_ratio.");
1464 PyFPE_START_PROTECT("as_integer_ratio", goto error
);
1465 float_part
= frexp(self
, &exponent
); /* self == float_part * 2**exponent exactly */
1466 PyFPE_END_PROTECT(float_part
);
1468 for (i
=0; i
<300 && float_part
!= floor(float_part
) ; i
++) {
1472 /* self == float_part * 2**exponent exactly and float_part is integral.
1473 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1474 to be truncated by PyLong_FromDouble(). */
1476 numerator
= PyLong_FromDouble(float_part
);
1477 if (numerator
== NULL
) goto error
;
1479 /* fold in 2**exponent */
1480 denominator
= PyLong_FromLong(1);
1481 py_exponent
= PyLong_FromLong(labs((long)exponent
));
1482 if (py_exponent
== NULL
) goto error
;
1483 INPLACE_UPDATE(py_exponent
,
1484 long_methods
->nb_lshift(denominator
, py_exponent
));
1485 if (py_exponent
== NULL
) goto error
;
1487 INPLACE_UPDATE(numerator
,
1488 long_methods
->nb_multiply(numerator
, py_exponent
));
1489 if (numerator
== NULL
) goto error
;
1492 Py_DECREF(denominator
);
1493 denominator
= py_exponent
;
1497 /* Returns ints instead of longs where possible */
1498 INPLACE_UPDATE(numerator
, PyNumber_Int(numerator
));
1499 if (numerator
== NULL
) goto error
;
1500 INPLACE_UPDATE(denominator
, PyNumber_Int(denominator
));
1501 if (denominator
== NULL
) goto error
;
1503 result_pair
= PyTuple_Pack(2, numerator
, denominator
);
1505 #undef INPLACE_UPDATE
1507 Py_XDECREF(py_exponent
);
1508 Py_XDECREF(denominator
);
1509 Py_XDECREF(numerator
);
1513 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1514 "float.as_integer_ratio() -> (int, int)\n"
1516 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
1517 "float and with a positive denominator.\n"
1518 "Raises OverflowError on infinities and a ValueError on NaNs.\n"
1520 ">>> (10.0).as_integer_ratio()\n"
1522 ">>> (0.0).as_integer_ratio()\n"
1524 ">>> (-.25).as_integer_ratio()\n"
1529 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
1532 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1534 PyObject
*x
= Py_False
; /* Integer zero */
1535 static char *kwlist
[] = {"x", 0};
1537 if (type
!= &PyFloat_Type
)
1538 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
1539 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
1541 /* If it's a string, but not a string subclass, use
1542 PyFloat_FromString. */
1543 if (PyString_CheckExact(x
))
1544 return PyFloat_FromString(x
, NULL
);
1545 return PyNumber_Float(x
);
1548 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1549 first create a regular float from whatever arguments we got,
1550 then allocate a subtype instance and initialize its ob_fval
1551 from the regular float. The regular float is then thrown away.
1554 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1556 PyObject
*tmp
, *newobj
;
1558 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
1559 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
1562 assert(PyFloat_CheckExact(tmp
));
1563 newobj
= type
->tp_alloc(type
, 0);
1564 if (newobj
== NULL
) {
1568 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
1574 float_getnewargs(PyFloatObject
*v
)
1576 return Py_BuildValue("(d)", v
->ob_fval
);
1579 /* this is for the benefit of the pack/unpack routines below */
1582 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
1583 } float_format_type
;
1585 static float_format_type double_format
, float_format
;
1586 static float_format_type detected_double_format
, detected_float_format
;
1589 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1592 float_format_type r
;
1594 if (!PyString_Check(arg
)) {
1595 PyErr_Format(PyExc_TypeError
,
1596 "__getformat__() argument must be string, not %.500s",
1597 Py_TYPE(arg
)->tp_name
);
1600 s
= PyString_AS_STRING(arg
);
1601 if (strcmp(s
, "double") == 0) {
1604 else if (strcmp(s
, "float") == 0) {
1608 PyErr_SetString(PyExc_ValueError
,
1609 "__getformat__() argument 1 must be "
1610 "'double' or 'float'");
1615 case unknown_format
:
1616 return PyString_FromString("unknown");
1617 case ieee_little_endian_format
:
1618 return PyString_FromString("IEEE, little-endian");
1619 case ieee_big_endian_format
:
1620 return PyString_FromString("IEEE, big-endian");
1622 Py_FatalError("insane float_format or double_format");
1627 PyDoc_STRVAR(float_getformat_doc
,
1628 "float.__getformat__(typestr) -> string\n"
1630 "You probably don't want to use this function. It exists mainly to be\n"
1631 "used in Python's test suite.\n"
1633 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1634 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1635 "format of floating point numbers used by the C type named by typestr.");
1638 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1642 float_format_type f
;
1643 float_format_type detected
;
1644 float_format_type
*p
;
1646 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1649 if (strcmp(typestr
, "double") == 0) {
1651 detected
= detected_double_format
;
1653 else if (strcmp(typestr
, "float") == 0) {
1655 detected
= detected_float_format
;
1658 PyErr_SetString(PyExc_ValueError
,
1659 "__setformat__() argument 1 must "
1660 "be 'double' or 'float'");
1664 if (strcmp(format
, "unknown") == 0) {
1667 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1668 f
= ieee_little_endian_format
;
1670 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1671 f
= ieee_big_endian_format
;
1674 PyErr_SetString(PyExc_ValueError
,
1675 "__setformat__() argument 2 must be "
1676 "'unknown', 'IEEE, little-endian' or "
1677 "'IEEE, big-endian'");
1682 if (f
!= unknown_format
&& f
!= detected
) {
1683 PyErr_Format(PyExc_ValueError
,
1684 "can only set %s format to 'unknown' or the "
1685 "detected platform value", typestr
);
1693 PyDoc_STRVAR(float_setformat_doc
,
1694 "float.__setformat__(typestr, fmt) -> None\n"
1696 "You probably don't want to use this function. It exists mainly to be\n"
1697 "used in Python's test suite.\n"
1699 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1700 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1701 "one of the latter two if it appears to match the underlying C reality.\n"
1703 "Overrides the automatic determination of C-level floating point type.\n"
1704 "This affects how floats are converted to and from binary strings.");
1707 float_getzero(PyObject
*v
, void *closure
)
1709 return PyFloat_FromDouble(0.0);
1713 float__format__(PyObject
*self
, PyObject
*args
)
1715 PyObject
*format_spec
;
1717 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1719 if (PyBytes_Check(format_spec
))
1720 return _PyFloat_FormatAdvanced(self
,
1721 PyBytes_AS_STRING(format_spec
),
1722 PyBytes_GET_SIZE(format_spec
));
1723 if (PyUnicode_Check(format_spec
)) {
1724 /* Convert format_spec to a str */
1726 PyObject
*str_spec
= PyObject_Str(format_spec
);
1728 if (str_spec
== NULL
)
1731 result
= _PyFloat_FormatAdvanced(self
,
1732 PyBytes_AS_STRING(str_spec
),
1733 PyBytes_GET_SIZE(str_spec
));
1735 Py_DECREF(str_spec
);
1738 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1742 PyDoc_STRVAR(float__format__doc
,
1743 "float.__format__(format_spec) -> string\n"
1745 "Formats the float according to format_spec.");
1748 static PyMethodDef float_methods
[] = {
1749 {"conjugate", (PyCFunction
)float_float
, METH_NOARGS
,
1750 "Returns self, the complex conjugate of any float."},
1751 {"__trunc__", (PyCFunction
)float_trunc
, METH_NOARGS
,
1752 "Returns the Integral closest to x between 0 and x."},
1753 {"as_integer_ratio", (PyCFunction
)float_as_integer_ratio
, METH_NOARGS
,
1754 float_as_integer_ratio_doc
},
1755 {"fromhex", (PyCFunction
)float_fromhex
,
1756 METH_O
|METH_CLASS
, float_fromhex_doc
},
1757 {"hex", (PyCFunction
)float_hex
,
1758 METH_NOARGS
, float_hex_doc
},
1759 {"is_integer", (PyCFunction
)float_is_integer
, METH_NOARGS
,
1760 "Returns True if the float is an integer."},
1762 {"is_inf", (PyCFunction
)float_is_inf
, METH_NOARGS
,
1763 "Returns True if the float is positive or negative infinite."},
1764 {"is_finite", (PyCFunction
)float_is_finite
, METH_NOARGS
,
1765 "Returns True if the float is finite, neither infinite nor NaN."},
1766 {"is_nan", (PyCFunction
)float_is_nan
, METH_NOARGS
,
1767 "Returns True if the float is not a number (NaN)."},
1769 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
1770 {"__getformat__", (PyCFunction
)float_getformat
,
1771 METH_O
|METH_CLASS
, float_getformat_doc
},
1772 {"__setformat__", (PyCFunction
)float_setformat
,
1773 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
1774 {"__format__", (PyCFunction
)float__format__
,
1775 METH_VARARGS
, float__format__doc
},
1776 {NULL
, NULL
} /* sentinel */
1779 static PyGetSetDef float_getset
[] = {
1781 (getter
)float_float
, (setter
)NULL
,
1782 "the real part of a complex number",
1785 (getter
)float_getzero
, (setter
)NULL
,
1786 "the imaginary part of a complex number",
1788 {NULL
} /* Sentinel */
1791 PyDoc_STRVAR(float_doc
,
1792 "float(x) -> floating point number\n\
1794 Convert a string or number to a floating point number, if possible.");
1797 static PyNumberMethods float_as_number
= {
1798 float_add
, /*nb_add*/
1799 float_sub
, /*nb_subtract*/
1800 float_mul
, /*nb_multiply*/
1801 float_classic_div
, /*nb_divide*/
1802 float_rem
, /*nb_remainder*/
1803 float_divmod
, /*nb_divmod*/
1804 float_pow
, /*nb_power*/
1805 (unaryfunc
)float_neg
, /*nb_negative*/
1806 (unaryfunc
)float_float
, /*nb_positive*/
1807 (unaryfunc
)float_abs
, /*nb_absolute*/
1808 (inquiry
)float_nonzero
, /*nb_nonzero*/
1815 float_coerce
, /*nb_coerce*/
1816 float_trunc
, /*nb_int*/
1817 float_long
, /*nb_long*/
1818 float_float
, /*nb_float*/
1821 0, /* nb_inplace_add */
1822 0, /* nb_inplace_subtract */
1823 0, /* nb_inplace_multiply */
1824 0, /* nb_inplace_divide */
1825 0, /* nb_inplace_remainder */
1826 0, /* nb_inplace_power */
1827 0, /* nb_inplace_lshift */
1828 0, /* nb_inplace_rshift */
1829 0, /* nb_inplace_and */
1830 0, /* nb_inplace_xor */
1831 0, /* nb_inplace_or */
1832 float_floor_div
, /* nb_floor_divide */
1833 float_div
, /* nb_true_divide */
1834 0, /* nb_inplace_floor_divide */
1835 0, /* nb_inplace_true_divide */
1838 PyTypeObject PyFloat_Type
= {
1839 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
1841 sizeof(PyFloatObject
),
1843 (destructor
)float_dealloc
, /* tp_dealloc */
1844 (printfunc
)float_print
, /* tp_print */
1848 (reprfunc
)float_repr
, /* tp_repr */
1849 &float_as_number
, /* tp_as_number */
1850 0, /* tp_as_sequence */
1851 0, /* tp_as_mapping */
1852 (hashfunc
)float_hash
, /* tp_hash */
1854 (reprfunc
)float_str
, /* tp_str */
1855 PyObject_GenericGetAttr
, /* tp_getattro */
1856 0, /* tp_setattro */
1857 0, /* tp_as_buffer */
1858 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
1859 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1860 float_doc
, /* tp_doc */
1861 0, /* tp_traverse */
1863 float_richcompare
, /* tp_richcompare */
1864 0, /* tp_weaklistoffset */
1866 0, /* tp_iternext */
1867 float_methods
, /* tp_methods */
1869 float_getset
, /* tp_getset */
1872 0, /* tp_descr_get */
1873 0, /* tp_descr_set */
1874 0, /* tp_dictoffset */
1877 float_new
, /* tp_new */
1883 /* We attempt to determine if this machine is using IEEE
1884 floating point formats by peering at the bits of some
1885 carefully chosen values. If it looks like we are on an
1886 IEEE platform, the float packing/unpacking routines can
1887 just copy bits, if not they resort to arithmetic & shifts
1888 and masks. The shifts & masks approach works on all finite
1889 values, but what happens to infinities, NaNs and signed
1890 zeroes on packing is an accident, and attempting to unpack
1891 a NaN or an infinity will raise an exception.
1893 Note that if we're on some whacked-out platform which uses
1894 IEEE formats but isn't strictly little-endian or big-
1895 endian, we will fall back to the portable shifts & masks
1898 #if SIZEOF_DOUBLE == 8
1900 double x
= 9006104071832581.0;
1901 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1902 detected_double_format
= ieee_big_endian_format
;
1903 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1904 detected_double_format
= ieee_little_endian_format
;
1906 detected_double_format
= unknown_format
;
1909 detected_double_format
= unknown_format
;
1912 #if SIZEOF_FLOAT == 4
1914 float y
= 16711938.0;
1915 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
1916 detected_float_format
= ieee_big_endian_format
;
1917 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
1918 detected_float_format
= ieee_little_endian_format
;
1920 detected_float_format
= unknown_format
;
1923 detected_float_format
= unknown_format
;
1926 double_format
= detected_double_format
;
1927 float_format
= detected_float_format
;
1929 /* Init float info */
1930 if (FloatInfoType
.tp_name
== 0)
1931 PyStructSequence_InitType(&FloatInfoType
, &floatinfo_desc
);
1935 PyFloat_ClearFreeList(void)
1938 PyFloatBlock
*list
, *next
;
1940 int u
; /* remaining unfreed ints per block */
1941 int freelist_size
= 0;
1946 while (list
!= NULL
) {
1948 for (i
= 0, p
= &list
->objects
[0];
1951 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
1956 list
->next
= block_list
;
1958 for (i
= 0, p
= &list
->objects
[0];
1961 if (!PyFloat_CheckExact(p
) ||
1962 Py_REFCNT(p
) == 0) {
1963 Py_TYPE(p
) = (struct _typeobject
*)
1975 return freelist_size
;
1984 int u
; /* total unfreed floats per block */
1986 u
= PyFloat_ClearFreeList();
1988 if (!Py_VerboseFlag
)
1990 fprintf(stderr
, "# cleanup floats");
1992 fprintf(stderr
, "\n");
1996 ": %d unfreed float%s\n",
1997 u
, u
== 1 ? "" : "s");
1999 if (Py_VerboseFlag
> 1) {
2001 while (list
!= NULL
) {
2002 for (i
= 0, p
= &list
->objects
[0];
2005 if (PyFloat_CheckExact(p
) &&
2006 Py_REFCNT(p
) != 0) {
2007 char *buf
= PyOS_double_to_string(
2008 PyFloat_AS_DOUBLE(p
), 'r',
2011 /* XXX(twouters) cast
2018 "# <float at %p, refcnt=%ld, val=%s>\n",
2019 p
, (long)Py_REFCNT(p
), buf
);
2029 /*----------------------------------------------------------------------------
2030 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
2033 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
2035 if (float_format
== unknown_format
) {
2056 /* Normalize f to be in the range [1.0, 2.0) */
2057 if (0.5 <= f
&& f
< 1.0) {
2064 PyErr_SetString(PyExc_SystemError
,
2065 "frexp() result out of range");
2071 else if (e
< -126) {
2072 /* Gradual underflow */
2073 f
= ldexp(f
, 126 + e
);
2076 else if (!(e
== 0 && f
== 0.0)) {
2078 f
-= 1.0; /* Get rid of leading 1 */
2081 f
*= 8388608.0; /* 2**23 */
2082 fbits
= (unsigned int)(f
+ 0.5); /* Round */
2083 assert(fbits
<= 8388608);
2085 /* The carry propagated out of a string of 23 1 bits. */
2093 *p
= (sign
<< 7) | (e
>> 1);
2097 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
2101 *p
= (fbits
>> 8) & 0xFF;
2113 const char *s
= (char*)&y
;
2116 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
2119 if ((float_format
== ieee_little_endian_format
&& !le
)
2120 || (float_format
== ieee_big_endian_format
&& le
)) {
2125 for (i
= 0; i
< 4; i
++) {
2132 PyErr_SetString(PyExc_OverflowError
,
2133 "float too large to pack with f format");
2138 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
2140 if (double_format
== unknown_format
) {
2144 unsigned int fhi
, flo
;
2161 /* Normalize f to be in the range [1.0, 2.0) */
2162 if (0.5 <= f
&& f
< 1.0) {
2169 PyErr_SetString(PyExc_SystemError
,
2170 "frexp() result out of range");
2176 else if (e
< -1022) {
2177 /* Gradual underflow */
2178 f
= ldexp(f
, 1022 + e
);
2181 else if (!(e
== 0 && f
== 0.0)) {
2183 f
-= 1.0; /* Get rid of leading 1 */
2186 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2187 f
*= 268435456.0; /* 2**28 */
2188 fhi
= (unsigned int)f
; /* Truncate */
2189 assert(fhi
< 268435456);
2192 f
*= 16777216.0; /* 2**24 */
2193 flo
= (unsigned int)(f
+ 0.5); /* Round */
2194 assert(flo
<= 16777216);
2196 /* The carry propagated out of a string of 24 1 bits. */
2200 /* And it also progagated out of the next 28 bits. */
2209 *p
= (sign
<< 7) | (e
>> 4);
2213 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
2217 *p
= (fhi
>> 16) & 0xFF;
2221 *p
= (fhi
>> 8) & 0xFF;
2229 *p
= (flo
>> 16) & 0xFF;
2233 *p
= (flo
>> 8) & 0xFF;
2244 PyErr_SetString(PyExc_OverflowError
,
2245 "float too large to pack with d format");
2249 const char *s
= (char*)&x
;
2252 if ((double_format
== ieee_little_endian_format
&& !le
)
2253 || (double_format
== ieee_big_endian_format
&& le
)) {
2258 for (i
= 0; i
< 8; i
++) {
2267 _PyFloat_Unpack4(const unsigned char *p
, int le
)
2269 if (float_format
== unknown_format
) {
2282 sign
= (*p
>> 7) & 1;
2283 e
= (*p
& 0x7F) << 1;
2288 f
= (*p
& 0x7F) << 16;
2294 "can't unpack IEEE 754 special value "
2295 "on non-IEEE platform");
2306 x
= (double)f
/ 8388608.0;
2308 /* XXX This sadly ignores Inf/NaN issues */
2325 if ((float_format
== ieee_little_endian_format
&& !le
)
2326 || (float_format
== ieee_big_endian_format
&& le
)) {
2331 for (i
= 0; i
< 4; i
++) {
2345 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2347 if (double_format
== unknown_format
) {
2350 unsigned int fhi
, flo
;
2360 sign
= (*p
>> 7) & 1;
2361 e
= (*p
& 0x7F) << 4;
2366 e
|= (*p
>> 4) & 0xF;
2367 fhi
= (*p
& 0xF) << 24;
2373 "can't unpack IEEE 754 special value "
2374 "on non-IEEE platform");
2401 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2402 x
/= 268435456.0; /* 2**28 */
2420 if ((double_format
== ieee_little_endian_format
&& !le
)
2421 || (double_format
== ieee_big_endian_format
&& le
)) {
2426 for (i
= 0; i
< 8; i
++) {