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.floatinfo", /* 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
[256]; /* for objects convertible to a char buffer */
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");
201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
202 PyUnicode_GET_SIZE(v
),
210 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
211 PyErr_SetString(PyExc_TypeError
,
212 "float() argument must be a string or a number");
217 while (*s
&& isspace(Py_CHARMASK(*s
)))
219 /* We don't care about overflow or underflow. If the platform
220 * supports them, infinities and signed zeroes (on underflow) are
223 PyFPE_START_PROTECT("strtod", return NULL
)
224 x
= PyOS_ascii_strtod(s
, (char **)&end
);
230 PyOS_snprintf(buffer
, sizeof(buffer
),
231 "invalid literal for float(): %.200s", s
);
232 PyErr_SetString(PyExc_ValueError
, buffer
);
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
)))
242 PyErr_SetString(PyExc_ValueError
,
243 "null byte in argument for float()");
245 PyOS_snprintf(buffer
, sizeof(buffer
),
246 "invalid literal for float(): %.200s", s
);
247 PyErr_SetString(PyExc_ValueError
, buffer
);
251 return PyFloat_FromDouble(x
);
255 float_dealloc(PyFloatObject
*op
)
257 if (PyFloat_CheckExact(op
)) {
258 Py_TYPE(op
) = (struct _typeobject
*)free_list
;
262 Py_TYPE(op
)->tp_free((PyObject
*)op
);
266 PyFloat_AsDouble(PyObject
*op
)
272 if (op
&& PyFloat_Check(op
))
273 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
280 if ((nb
= Py_TYPE(op
)->tp_as_number
) == NULL
|| nb
->nb_float
== NULL
) {
281 PyErr_SetString(PyExc_TypeError
, "a float is required");
285 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
288 if (!PyFloat_Check(fo
)) {
289 PyErr_SetString(PyExc_TypeError
,
290 "nb_float should return float object");
294 val
= PyFloat_AS_DOUBLE(fo
);
303 format_float(char *buf
, size_t buflen
, PyFloatObject
*v
, int precision
)
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
,
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
)))
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
== '.')
339 /* found something that is neither a digit nor point
340 * it might be a NaN or INF
343 if (Py_IS_NAN(v
->ob_fval
)) {
348 if (Py_IS_INFINITY(v
->ob_fval
)) {
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).
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) \
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()) {
398 Py_INCREF(Py_NotImplemented
);
399 *v
= Py_NotImplemented
;
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
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.
422 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
423 XXX they pass a char buffer without passing a length.
426 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
428 format_float(buf
, 100, v
, PREC_STR
);
432 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
434 format_float(buf
, 100, v
, PREC_REPR
);
439 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
442 format_float(buf
, sizeof(buf
), v
,
443 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
444 Py_BEGIN_ALLOW_THREADS
451 float_repr(PyFloatObject
*v
)
454 format_float(buf
, sizeof(buf
), v
, PREC_REPR
);
456 return PyString_FromString(buf
);
460 float_str(PyFloatObject
*v
)
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.
483 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
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.
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
515 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
517 /* Needs more than 48 bits. Make it take the
521 PyObject
*ww
= PyLong_FromLong(jj
);
525 result
= float_richcompare(v
, ww
, op
);
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
);
540 if (vsign
!= wsign
) {
541 /* Magnitudes are irrelevant -- the signs alone
542 * determine the outcome.
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
565 j
= PyLong_AsDouble(w
);
566 /* It's impossible that <= 48 bits overflowed. */
567 assert(j
!= -1.0 || ! PyErr_Occurred());
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. */
576 /* "Multiply both sides" by -1; this also swaps the
580 op
= _Py_SwappedOp
[op
];
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
) {
592 if ((size_t)exponent
> nbits
) {
597 /* v and w have the same number of bits before the radix
598 * point. Construct two longs that have the same comparison
604 PyObject
*result
= NULL
;
605 PyObject
*one
= NULL
;
610 ww
= PyNumber_Negative(w
);
617 fracpart
= modf(i
, &intpart
);
618 vv
= PyLong_FromDouble(intpart
);
622 if (fracpart
!= 0.0) {
623 /* Shift left, and or a 1 bit into vv
624 * to represent the lost fraction.
628 one
= PyInt_FromLong(1);
632 temp
= PyNumber_Lshift(ww
, one
);
638 temp
= PyNumber_Lshift(vv
, one
);
644 temp
= PyNumber_Or(vv
, one
);
651 r
= PyObject_RichCompareBool(vv
, ww
, op
);
654 result
= PyBool_FromLong(r
);
661 } /* else if (PyLong_Check(w)) */
663 else /* w isn't float, int, or long */
667 PyFPE_START_PROTECT("richcompare", return NULL
)
689 return PyBool_FromLong(r
);
692 Py_INCREF(Py_NotImplemented
);
693 return Py_NotImplemented
;
697 float_hash(PyFloatObject
*v
)
699 return _Py_HashDouble(v
->ob_fval
);
703 float_add(PyObject
*v
, PyObject
*w
)
706 CONVERT_TO_DOUBLE(v
, a
);
707 CONVERT_TO_DOUBLE(w
, b
);
708 PyFPE_START_PROTECT("add", return 0)
711 return PyFloat_FromDouble(a
);
715 float_sub(PyObject
*v
, PyObject
*w
)
718 CONVERT_TO_DOUBLE(v
, a
);
719 CONVERT_TO_DOUBLE(w
, b
);
720 PyFPE_START_PROTECT("subtract", return 0)
723 return PyFloat_FromDouble(a
);
727 float_mul(PyObject
*v
, PyObject
*w
)
730 CONVERT_TO_DOUBLE(v
, a
);
731 CONVERT_TO_DOUBLE(w
, b
);
732 PyFPE_START_PROTECT("multiply", return 0)
735 return PyFloat_FromDouble(a
);
739 float_div(PyObject
*v
, PyObject
*w
)
742 CONVERT_TO_DOUBLE(v
, a
);
743 CONVERT_TO_DOUBLE(w
, b
);
746 PyErr_SetString(PyExc_ZeroDivisionError
,
751 PyFPE_START_PROTECT("divide", return 0)
754 return PyFloat_FromDouble(a
);
758 float_classic_div(PyObject
*v
, PyObject
*w
)
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)
768 PyErr_SetString(PyExc_ZeroDivisionError
,
773 PyFPE_START_PROTECT("divide", return 0)
776 return PyFloat_FromDouble(a
);
780 float_rem(PyObject
*v
, PyObject
*w
)
784 CONVERT_TO_DOUBLE(v
, vx
);
785 CONVERT_TO_DOUBLE(w
, wx
);
788 PyErr_SetString(PyExc_ZeroDivisionError
,
793 PyFPE_START_PROTECT("modulo", return 0)
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))) {
800 PyFPE_END_PROTECT(mod
)
801 return PyFloat_FromDouble(mod
);
805 float_divmod(PyObject
*v
, PyObject
*w
)
808 double div
, mod
, floordiv
;
809 CONVERT_TO_DOUBLE(v
, vx
);
810 CONVERT_TO_DOUBLE(w
, wx
);
812 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
815 PyFPE_START_PROTECT("divmod", return 0)
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
;
825 /* ensure the remainder has the same sign as the denominator */
826 if ((wx
< 0) != (mod
< 0)) {
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 */
840 /* snap quotient to nearest integral value */
842 floordiv
= floor(div
);
843 if (div
- floordiv
> 0.5)
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
);
856 float_floor_div(PyObject
*v
, PyObject
*w
)
860 t
= float_divmod(v
, w
);
861 if (t
== NULL
|| t
== Py_NotImplemented
)
863 assert(PyTuple_CheckExact(t
));
864 r
= PyTuple_GET_ITEM(t
, 0);
871 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
875 if ((PyObject
*)z
!= Py_None
) {
876 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
877 "allowed unless all arguments are integers");
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 */
890 PyErr_SetString(PyExc_ZeroDivisionError
,
891 "0.0 cannot be raised to a negative power");
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);
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");
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
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.
931 PyFPE_START_PROTECT("pow", return NULL
)
933 PyFPE_END_PROTECT(ix
)
934 Py_ADJUST_ERANGE1(ix
);
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
:
943 return PyFloat_FromDouble(ix
);
947 float_neg(PyFloatObject
*v
)
949 return PyFloat_FromDouble(-v
->ob_fval
);
953 float_abs(PyFloatObject
*v
)
955 return PyFloat_FromDouble(fabs(v
->ob_fval
));
959 float_nonzero(PyFloatObject
*v
)
961 return v
->ob_fval
!= 0.0;
965 float_coerce(PyObject
**pv
, PyObject
**pw
)
967 if (PyInt_Check(*pw
)) {
968 long x
= PyInt_AsLong(*pw
);
969 *pw
= PyFloat_FromDouble((double)x
);
973 else if (PyLong_Check(*pw
)) {
974 double x
= PyLong_AsDouble(*pw
);
975 if (x
== -1.0 && PyErr_Occurred())
977 *pw
= PyFloat_FromDouble(x
);
981 else if (PyFloat_Check(*pw
)) {
986 return 1; /* Can't do it */
990 float_is_integer(PyObject
*v
)
992 double x
= PyFloat_AsDouble(v
);
995 if (x
== -1.0 && PyErr_Occurred())
997 if (!Py_IS_FINITE(x
))
1000 PyFPE_START_PROTECT("is_integer", return NULL
)
1001 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
1002 PyFPE_END_PROTECT(x
)
1004 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
1014 float_is_inf(PyObject
*v
)
1016 double x
= PyFloat_AsDouble(v
);
1017 if (x
== -1.0 && PyErr_Occurred())
1019 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
1023 float_is_nan(PyObject
*v
)
1025 double x
= PyFloat_AsDouble(v
);
1026 if (x
== -1.0 && PyErr_Occurred())
1028 return PyBool_FromLong((long)Py_IS_NAN(x
));
1032 float_is_finite(PyObject
*v
)
1034 double x
= PyFloat_AsDouble(v
);
1035 if (x
== -1.0 && PyErr_Occurred())
1037 return PyBool_FromLong((long)Py_IS_FINITE(x
));
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
);
1068 float_long(PyObject
*v
)
1070 double x
= PyFloat_AsDouble(v
);
1071 return PyLong_FromDouble(x
);
1075 float_float(PyObject
*v
)
1077 if (PyFloat_CheckExact(v
))
1080 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1084 /* turn ASCII hex characters into integer values and vice versa */
1087 char_from_hex(int x
)
1089 assert(0 <= x
&& x
< 16);
1090 return "0123456789abcdef"[x
];
1094 hex_from_char(char c
) {
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
1165 float_hex(PyObject
*v
)
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
);
1179 if(copysign(1.0, x
) == -1.0)
1180 return PyString_FromString("-0x0.0p+0");
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
);
1191 s
[si
] = char_from_hex((int)m
);
1196 for (i
=0; i
< (TOHEX_NBITS
-1)/4; i
++) {
1198 s
[si
] = char_from_hex((int)m
);
1212 return PyString_FromFormat("-0x%sp%c%d", s
, esign
, e
);
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\
1222 '-0x1.999999999999ap-4'\n\
1223 >>> 3.14159.hex()\n\
1224 '0x1.921f9f01b866ep+1'");
1226 /* Convert a hexadecimal string to a float. */
1229 float_fromhex(PyObject
*cls
, PyObject
*arg
)
1231 PyObject
*result_as_float
, *result
;
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
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)
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
))
1287 /********************
1288 * Parse the string *
1289 ********************/
1291 /* leading whitespace and optional sign */
1301 /* infinities and nans */
1302 if (PyOS_strnicmp(s
, "nan", 4) == 0) {
1306 if (PyOS_strnicmp(s
, "inf", 4) == 0 ||
1307 PyOS_strnicmp(s
, "infinity", 9) == 0) {
1308 x
= sign
*Py_HUGE_VAL
;
1316 if (tolower(*s
) == (int)'x')
1322 /* coefficient: <integer> [. <fraction>] */
1324 while (hex_from_char(*s
) >= 0)
1329 while (hex_from_char(*s
) >= 0)
1336 /* ndigits = total # of hex digits; fdigits = # after point */
1337 ndigits
= coeff_end
- coeff_start
;
1338 fdigits
= coeff_end
- s_store
;
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') {
1349 if (*s
== '-' || *s
== '+')
1351 if (!('0' <= *s
&& *s
<= '9'))
1354 while ('0' <= *s
&& *s
<= '9')
1356 exp
= strtol(exp_start
, NULL
, 10);
1361 /* optional trailing whitespace leading to the end of the string */
1367 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1368 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
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)
1379 if (ndigits
== 0 || exp
< LONG_MIN
/2) {
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)
1394 /* catch almost all nonextreme cases of overflow and underflow here */
1395 if (top_exp
< DBL_MIN_EXP
- DBL_MANT_DIG
) {
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
;
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
));
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) {
1427 if ((digit
& (3*half_eps
-1)) != 0 ||
1428 (half_eps
== 8 && (HEX_DIGIT(key_digit
+1) & 1) != 0))
1431 for (i
= key_digit
-1; i
>= 0; i
--)
1432 if (HEX_DIGIT(i
) != 0) {
1436 if (round_up
== 1) {
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
));
1448 result_as_float
= Py_BuildValue("(d)", x
);
1449 if (result_as_float
== NULL
)
1451 result
= PyObject_CallObject(cls
, result_as_float
);
1452 Py_DECREF(result_as_float
);
1456 PyErr_SetString(PyExc_OverflowError
,
1457 "hexadecimal value too large to represent as a float");
1461 PyErr_SetString(PyExc_ValueError
,
1462 "invalid hexadecimal floating-point string");
1465 insane_length_error
:
1466 PyErr_SetString(PyExc_ValueError
,
1467 "hexadecimal string too long to convert");
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\
1477 >>> float.fromhex('-0x1p-1074')\n\
1478 -4.9406564584124654e-324");
1482 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
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) \
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.");
1509 if (Py_IS_NAN(self
)) {
1510 PyErr_SetString(PyExc_ValueError
,
1511 "Cannot pass NaN to float.as_integer_ratio.");
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
++) {
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
;
1539 INPLACE_UPDATE(numerator
,
1540 long_methods
->nb_multiply(numerator
, py_exponent
));
1541 if (numerator
== NULL
) goto error
;
1544 Py_DECREF(denominator
);
1545 denominator
= py_exponent
;
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
1559 Py_XDECREF(py_exponent
);
1560 Py_XDECREF(denominator
);
1561 Py_XDECREF(numerator
);
1565 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1566 "float.as_integer_ratio() -> (int, int)\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"
1572 ">>> (10.0).as_integer_ratio()\n"
1574 ">>> (0.0).as_integer_ratio()\n"
1576 ">>> (-.25).as_integer_ratio()\n"
1581 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
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
))
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.
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
);
1614 assert(PyFloat_CheckExact(tmp
));
1615 newobj
= type
->tp_alloc(type
, 0);
1616 if (newobj
== NULL
) {
1620 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
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 */
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
;
1641 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
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
);
1652 s
= PyString_AS_STRING(arg
);
1653 if (strcmp(s
, "double") == 0) {
1656 else if (strcmp(s
, "float") == 0) {
1660 PyErr_SetString(PyExc_ValueError
,
1661 "__getformat__() argument 1 must be "
1662 "'double' or 'float'");
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");
1674 Py_FatalError("insane float_format or double_format");
1679 PyDoc_STRVAR(float_getformat_doc
,
1680 "float.__getformat__(typestr) -> string\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"
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.");
1690 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1694 float_format_type f
;
1695 float_format_type detected
;
1696 float_format_type
*p
;
1698 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1701 if (strcmp(typestr
, "double") == 0) {
1703 detected
= detected_double_format
;
1705 else if (strcmp(typestr
, "float") == 0) {
1707 detected
= detected_float_format
;
1710 PyErr_SetString(PyExc_ValueError
,
1711 "__setformat__() argument 1 must "
1712 "be 'double' or 'float'");
1716 if (strcmp(format
, "unknown") == 0) {
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
;
1726 PyErr_SetString(PyExc_ValueError
,
1727 "__setformat__() argument 2 must be "
1728 "'unknown', 'IEEE, little-endian' or "
1729 "'IEEE, big-endian'");
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
);
1745 PyDoc_STRVAR(float_setformat_doc
,
1746 "float.__setformat__(typestr, fmt) -> None\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"
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"
1755 "Overrides the automatic determination of C-level floating point type.\n"
1756 "This affects how floats are converted to and from binary strings.");
1759 float_getzero(PyObject
*v
, void *closure
)
1761 return PyFloat_FromDouble(0.0);
1765 float__format__(PyObject
*self
, PyObject
*args
)
1767 PyObject
*format_spec
;
1769 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
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 */
1778 PyObject
*str_spec
= PyObject_Str(format_spec
);
1780 if (str_spec
== NULL
)
1783 result
= _PyFloat_FormatAdvanced(self
,
1784 PyBytes_AS_STRING(str_spec
),
1785 PyBytes_GET_SIZE(str_spec
));
1787 Py_DECREF(str_spec
);
1790 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1794 PyDoc_STRVAR(float__format__doc
,
1795 "float.__format__(format_spec) -> string\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."},
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)."},
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
[] = {
1833 (getter
)float_float
, (setter
)NULL
,
1834 "the real part of a complex number",
1837 (getter
)float_getzero
, (setter
)NULL
,
1838 "the imaginary part of a complex number",
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*/
1867 float_coerce
, /*nb_coerce*/
1868 float_trunc
, /*nb_int*/
1869 float_long
, /*nb_long*/
1870 float_float
, /*nb_float*/
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)
1893 sizeof(PyFloatObject
),
1895 (destructor
)float_dealloc
, /* tp_dealloc */
1896 (printfunc
)float_print
, /* tp_print */
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 */
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 */
1915 float_richcompare
, /* tp_richcompare */
1916 0, /* tp_weaklistoffset */
1918 0, /* tp_iternext */
1919 float_methods
, /* tp_methods */
1921 float_getset
, /* tp_getset */
1924 0, /* tp_descr_get */
1925 0, /* tp_descr_set */
1926 0, /* tp_dictoffset */
1929 float_new
, /* tp_new */
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
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
;
1958 detected_double_format
= unknown_format
;
1961 detected_double_format
= unknown_format
;
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
;
1972 detected_float_format
= unknown_format
;
1975 detected_float_format
= unknown_format
;
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)
1990 PyFloatBlock
*list
, *next
;
1992 int u
; /* remaining unfreed ints per block */
1993 int freelist_size
= 0;
1998 while (list
!= NULL
) {
2000 for (i
= 0, p
= &list
->objects
[0];
2003 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
2008 list
->next
= block_list
;
2010 for (i
= 0, p
= &list
->objects
[0];
2013 if (!PyFloat_CheckExact(p
) ||
2014 Py_REFCNT(p
) == 0) {
2015 Py_TYPE(p
) = (struct _typeobject
*)
2027 return freelist_size
;
2036 int u
; /* total unfreed floats per block */
2038 u
= PyFloat_ClearFreeList();
2040 if (!Py_VerboseFlag
)
2042 fprintf(stderr
, "# cleanup floats");
2044 fprintf(stderr
, "\n");
2048 ": %d unfreed float%s\n",
2049 u
, u
== 1 ? "" : "s");
2051 if (Py_VerboseFlag
> 1) {
2053 while (list
!= NULL
) {
2054 for (i
= 0, p
= &list
->objects
[0];
2057 if (PyFloat_CheckExact(p
) &&
2058 Py_REFCNT(p
) != 0) {
2060 PyFloat_AsString(buf
, p
);
2061 /* XXX(twouters) cast refcount to
2062 long until %zd is universally
2066 "# <float at %p, refcnt=%ld, val=%s>\n",
2067 p
, (long)Py_REFCNT(p
), buf
);
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
) {
2102 /* Normalize f to be in the range [1.0, 2.0) */
2103 if (0.5 <= f
&& f
< 1.0) {
2110 PyErr_SetString(PyExc_SystemError
,
2111 "frexp() result out of range");
2117 else if (e
< -126) {
2118 /* Gradual underflow */
2119 f
= ldexp(f
, 126 + e
);
2122 else if (!(e
== 0 && f
== 0.0)) {
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);
2131 /* The carry propagated out of a string of 23 1 bits. */
2139 *p
= (sign
<< 7) | (e
>> 1);
2143 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
2147 *p
= (fbits
>> 8) & 0xFF;
2159 const char *s
= (char*)&y
;
2162 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
2165 if ((float_format
== ieee_little_endian_format
&& !le
)
2166 || (float_format
== ieee_big_endian_format
&& le
)) {
2171 for (i
= 0; i
< 4; i
++) {
2178 PyErr_SetString(PyExc_OverflowError
,
2179 "float too large to pack with f format");
2184 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
2186 if (double_format
== unknown_format
) {
2190 unsigned int fhi
, flo
;
2207 /* Normalize f to be in the range [1.0, 2.0) */
2208 if (0.5 <= f
&& f
< 1.0) {
2215 PyErr_SetString(PyExc_SystemError
,
2216 "frexp() result out of range");
2222 else if (e
< -1022) {
2223 /* Gradual underflow */
2224 f
= ldexp(f
, 1022 + e
);
2227 else if (!(e
== 0 && f
== 0.0)) {
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);
2238 f
*= 16777216.0; /* 2**24 */
2239 flo
= (unsigned int)(f
+ 0.5); /* Round */
2240 assert(flo
<= 16777216);
2242 /* The carry propagated out of a string of 24 1 bits. */
2246 /* And it also progagated out of the next 28 bits. */
2255 *p
= (sign
<< 7) | (e
>> 4);
2259 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
2263 *p
= (fhi
>> 16) & 0xFF;
2267 *p
= (fhi
>> 8) & 0xFF;
2275 *p
= (flo
>> 16) & 0xFF;
2279 *p
= (flo
>> 8) & 0xFF;
2290 PyErr_SetString(PyExc_OverflowError
,
2291 "float too large to pack with d format");
2295 const char *s
= (char*)&x
;
2298 if ((double_format
== ieee_little_endian_format
&& !le
)
2299 || (double_format
== ieee_big_endian_format
&& le
)) {
2304 for (i
= 0; i
< 8; i
++) {
2313 _PyFloat_Unpack4(const unsigned char *p
, int le
)
2315 if (float_format
== unknown_format
) {
2328 sign
= (*p
>> 7) & 1;
2329 e
= (*p
& 0x7F) << 1;
2334 f
= (*p
& 0x7F) << 16;
2340 "can't unpack IEEE 754 special value "
2341 "on non-IEEE platform");
2352 x
= (double)f
/ 8388608.0;
2354 /* XXX This sadly ignores Inf/NaN issues */
2371 if ((float_format
== ieee_little_endian_format
&& !le
)
2372 || (float_format
== ieee_big_endian_format
&& le
)) {
2377 for (i
= 0; i
< 4; i
++) {
2391 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2393 if (double_format
== unknown_format
) {
2396 unsigned int fhi
, flo
;
2406 sign
= (*p
>> 7) & 1;
2407 e
= (*p
& 0x7F) << 4;
2412 e
|= (*p
>> 4) & 0xF;
2413 fhi
= (*p
& 0xF) << 24;
2419 "can't unpack IEEE 754 special value "
2420 "on non-IEEE platform");
2447 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2448 x
/= 268435456.0; /* 2**28 */
2466 if ((double_format
== ieee_little_endian_format
&& !le
)
2467 || (double_format
== ieee_big_endian_format
&& le
)) {
2472 for (i
= 0; i
< 8; i
++) {