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
[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 (Py_ISSPACE(*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 (Py_ISSPACE(*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
);
302 /* XXX PyFloat_AsStringEx should not be a public API function (for one
303 XXX thing, its signature passes a buffer without a length; for another,
304 XXX it isn't useful outside this file).
307 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
309 _PyOS_double_to_string(buf
, 100, v
->ob_fval
, 'g', precision
,
310 Py_DTSF_ADD_DOT_0
, NULL
);
313 /* Macro and helper that convert PyObject obj to a C double and store
314 the value in dbl; this replaces the functionality of the coercion
315 slot function. If conversion to double raises an exception, obj is
316 set to NULL, and the function invoking this macro returns NULL. If
317 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
318 stored in obj, and returned from the function invoking this macro.
320 #define CONVERT_TO_DOUBLE(obj, dbl) \
321 if (PyFloat_Check(obj)) \
322 dbl = PyFloat_AS_DOUBLE(obj); \
323 else if (convert_to_double(&(obj), &(dbl)) < 0) \
327 convert_to_double(PyObject
**v
, double *dbl
)
329 register PyObject
*obj
= *v
;
331 if (PyInt_Check(obj
)) {
332 *dbl
= (double)PyInt_AS_LONG(obj
);
334 else if (PyLong_Check(obj
)) {
335 *dbl
= PyLong_AsDouble(obj
);
336 if (*dbl
== -1.0 && PyErr_Occurred()) {
342 Py_INCREF(Py_NotImplemented
);
343 *v
= Py_NotImplemented
;
349 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
350 XXX they pass a char buffer without passing a length.
353 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
355 _PyOS_double_to_string(buf
, 100, v
->ob_fval
, 'g', PyFloat_STR_PRECISION
,
356 Py_DTSF_ADD_DOT_0
, NULL
);
360 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
362 _PyOS_double_to_string(buf
, 100, v
->ob_fval
, 'r', 0,
363 Py_DTSF_ADD_DOT_0
, NULL
);
368 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
371 if (flags
& Py_PRINT_RAW
)
372 _PyOS_double_to_string(buf
, sizeof(buf
), v
->ob_fval
,
373 'g', PyFloat_STR_PRECISION
,
374 Py_DTSF_ADD_DOT_0
, NULL
);
376 _PyOS_double_to_string(buf
, sizeof(buf
), v
->ob_fval
,
377 'r', 0, Py_DTSF_ADD_DOT_0
, NULL
);
378 Py_BEGIN_ALLOW_THREADS
385 float_repr(PyFloatObject
*v
)
388 _PyOS_double_to_string(buf
, sizeof(buf
), v
->ob_fval
, 'r', 0,
389 Py_DTSF_ADD_DOT_0
, NULL
);
390 return PyString_FromString(buf
);
394 float_str(PyFloatObject
*v
)
397 _PyOS_double_to_string(buf
, sizeof(buf
), v
->ob_fval
, 'g',
398 PyFloat_STR_PRECISION
,
399 Py_DTSF_ADD_DOT_0
, NULL
);
400 return PyString_FromString(buf
);
403 /* Comparison is pretty much a nightmare. When comparing float to float,
404 * we do it as straightforwardly (and long-windedly) as conceivable, so
405 * that, e.g., Python x == y delivers the same result as the platform
406 * C x == y when x and/or y is a NaN.
407 * When mixing float with an integer type, there's no good *uniform* approach.
408 * Converting the double to an integer obviously doesn't work, since we
409 * may lose info from fractional bits. Converting the integer to a double
410 * also has two failure modes: (1) a long int may trigger overflow (too
411 * large to fit in the dynamic range of a C double); (2) even a C long may have
412 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
413 * 63 bits of precision, but a C double probably has only 53), and then
414 * we can falsely claim equality when low-order integer bits are lost by
415 * coercion to double. So this part is painful too.
419 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
424 assert(PyFloat_Check(v
));
425 i
= PyFloat_AS_DOUBLE(v
);
427 /* Switch on the type of w. Set i and j to doubles to be compared,
428 * and op to the richcomp to use.
430 if (PyFloat_Check(w
))
431 j
= PyFloat_AS_DOUBLE(w
);
433 else if (!Py_IS_FINITE(i
)) {
434 if (PyInt_Check(w
) || PyLong_Check(w
))
435 /* If i is an infinity, its magnitude exceeds any
436 * finite integer, so it doesn't matter which int we
437 * compare i with. If i is a NaN, similarly.
444 else if (PyInt_Check(w
)) {
445 long jj
= PyInt_AS_LONG(w
);
446 /* In the worst realistic case I can imagine, C double is a
447 * Cray single with 48 bits of precision, and long has 64
451 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
453 /* Needs more than 48 bits. Make it take the
457 PyObject
*ww
= PyLong_FromLong(jj
);
461 result
= float_richcompare(v
, ww
, op
);
467 assert((long)j
== jj
);
470 else if (PyLong_Check(w
)) {
471 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
472 int wsign
= _PyLong_Sign(w
);
476 if (vsign
!= wsign
) {
477 /* Magnitudes are irrelevant -- the signs alone
478 * determine the outcome.
484 /* The signs are the same. */
485 /* Convert w to a double if it fits. In particular, 0 fits. */
486 nbits
= _PyLong_NumBits(w
);
487 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
488 /* This long is so large that size_t isn't big enough
489 * to hold the # of bits. Replace with little doubles
490 * that give the same outcome -- w is so large that
491 * its magnitude must exceed the magnitude of any
501 j
= PyLong_AsDouble(w
);
502 /* It's impossible that <= 48 bits overflowed. */
503 assert(j
!= -1.0 || ! PyErr_Occurred());
506 assert(wsign
!= 0); /* else nbits was 0 */
507 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
508 * not 0, we would have taken the
509 * vsign != wsign branch at the start */
510 /* We want to work with non-negative numbers. */
512 /* "Multiply both sides" by -1; this also swaps the
516 op
= _Py_SwappedOp
[op
];
519 (void) frexp(i
, &exponent
);
520 /* exponent is the # of bits in v before the radix point;
521 * we know that nbits (the # of bits in w) > 48 at this point
523 if (exponent
< 0 || (size_t)exponent
< nbits
) {
528 if ((size_t)exponent
> nbits
) {
533 /* v and w have the same number of bits before the radix
534 * point. Construct two longs that have the same comparison
540 PyObject
*result
= NULL
;
541 PyObject
*one
= NULL
;
546 ww
= PyNumber_Negative(w
);
553 fracpart
= modf(i
, &intpart
);
554 vv
= PyLong_FromDouble(intpart
);
558 if (fracpart
!= 0.0) {
559 /* Shift left, and or a 1 bit into vv
560 * to represent the lost fraction.
564 one
= PyInt_FromLong(1);
568 temp
= PyNumber_Lshift(ww
, one
);
574 temp
= PyNumber_Lshift(vv
, one
);
580 temp
= PyNumber_Or(vv
, one
);
587 r
= PyObject_RichCompareBool(vv
, ww
, op
);
590 result
= PyBool_FromLong(r
);
597 } /* else if (PyLong_Check(w)) */
599 else /* w isn't float, int, or long */
603 PyFPE_START_PROTECT("richcompare", return NULL
)
625 return PyBool_FromLong(r
);
628 Py_INCREF(Py_NotImplemented
);
629 return Py_NotImplemented
;
633 float_hash(PyFloatObject
*v
)
635 return _Py_HashDouble(v
->ob_fval
);
639 float_add(PyObject
*v
, PyObject
*w
)
642 CONVERT_TO_DOUBLE(v
, a
);
643 CONVERT_TO_DOUBLE(w
, b
);
644 PyFPE_START_PROTECT("add", return 0)
647 return PyFloat_FromDouble(a
);
651 float_sub(PyObject
*v
, PyObject
*w
)
654 CONVERT_TO_DOUBLE(v
, a
);
655 CONVERT_TO_DOUBLE(w
, b
);
656 PyFPE_START_PROTECT("subtract", return 0)
659 return PyFloat_FromDouble(a
);
663 float_mul(PyObject
*v
, PyObject
*w
)
666 CONVERT_TO_DOUBLE(v
, a
);
667 CONVERT_TO_DOUBLE(w
, b
);
668 PyFPE_START_PROTECT("multiply", return 0)
671 return PyFloat_FromDouble(a
);
675 float_div(PyObject
*v
, PyObject
*w
)
678 CONVERT_TO_DOUBLE(v
, a
);
679 CONVERT_TO_DOUBLE(w
, b
);
682 PyErr_SetString(PyExc_ZeroDivisionError
,
687 PyFPE_START_PROTECT("divide", return 0)
690 return PyFloat_FromDouble(a
);
694 float_classic_div(PyObject
*v
, PyObject
*w
)
697 CONVERT_TO_DOUBLE(v
, a
);
698 CONVERT_TO_DOUBLE(w
, b
);
699 if (Py_DivisionWarningFlag
>= 2 &&
700 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
704 PyErr_SetString(PyExc_ZeroDivisionError
,
709 PyFPE_START_PROTECT("divide", return 0)
712 return PyFloat_FromDouble(a
);
716 float_rem(PyObject
*v
, PyObject
*w
)
720 CONVERT_TO_DOUBLE(v
, vx
);
721 CONVERT_TO_DOUBLE(w
, wx
);
724 PyErr_SetString(PyExc_ZeroDivisionError
,
729 PyFPE_START_PROTECT("modulo", return 0)
731 /* note: checking mod*wx < 0 is incorrect -- underflows to
732 0 if wx < sqrt(smallest nonzero double) */
733 if (mod
&& ((wx
< 0) != (mod
< 0))) {
736 PyFPE_END_PROTECT(mod
)
737 return PyFloat_FromDouble(mod
);
741 float_divmod(PyObject
*v
, PyObject
*w
)
744 double div
, mod
, floordiv
;
745 CONVERT_TO_DOUBLE(v
, vx
);
746 CONVERT_TO_DOUBLE(w
, wx
);
748 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
751 PyFPE_START_PROTECT("divmod", return 0)
753 /* fmod is typically exact, so vx-mod is *mathematically* an
754 exact multiple of wx. But this is fp arithmetic, and fp
755 vx - mod is an approximation; the result is that div may
756 not be an exact integral value after the division, although
757 it will always be very close to one.
759 div
= (vx
- mod
) / wx
;
761 /* ensure the remainder has the same sign as the denominator */
762 if ((wx
< 0) != (mod
< 0)) {
768 /* the remainder is zero, and in the presence of signed zeroes
769 fmod returns different results across platforms; ensure
770 it has the same sign as the denominator; we'd like to do
771 "mod = wx * 0.0", but that may get optimized away */
772 mod
*= mod
; /* hide "mod = +0" from optimizer */
776 /* snap quotient to nearest integral value */
778 floordiv
= floor(div
);
779 if (div
- floordiv
> 0.5)
783 /* div is zero - get the same sign as the true quotient */
784 div
*= div
; /* hide "div = +0" from optimizers */
785 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
787 PyFPE_END_PROTECT(floordiv
)
788 return Py_BuildValue("(dd)", floordiv
, mod
);
792 float_floor_div(PyObject
*v
, PyObject
*w
)
796 t
= float_divmod(v
, w
);
797 if (t
== NULL
|| t
== Py_NotImplemented
)
799 assert(PyTuple_CheckExact(t
));
800 r
= PyTuple_GET_ITEM(t
, 0);
807 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
811 if ((PyObject
*)z
!= Py_None
) {
812 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
813 "allowed unless all arguments are integers");
817 CONVERT_TO_DOUBLE(v
, iv
);
818 CONVERT_TO_DOUBLE(w
, iw
);
820 /* Sort out special cases here instead of relying on pow() */
821 if (iw
== 0) { /* v**0 is 1, even 0**0 */
822 return PyFloat_FromDouble(1.0);
824 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
826 PyErr_SetString(PyExc_ZeroDivisionError
,
827 "0.0 cannot be raised to a negative power");
830 return PyFloat_FromDouble(0.0);
832 if (iv
== 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
833 return PyFloat_FromDouble(1.0);
836 /* Whether this is an error is a mess, and bumps into libm
837 * bugs so we have to figure it out ourselves.
839 if (iw
!= floor(iw
)) {
840 PyErr_SetString(PyExc_ValueError
, "negative number "
841 "cannot be raised to a fractional power");
844 /* iw is an exact integer, albeit perhaps a very large one.
845 * -1 raised to an exact integer should never be exceptional.
846 * Alas, some libms (chiefly glibc as of early 2003) return
847 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
848 * happen to be representable in a *C* integer. That's a
849 * bug; we let that slide in math.pow() (which currently
850 * reflects all platform accidents), but not for Python's **.
852 if (iv
== -1.0 && Py_IS_FINITE(iw
)) {
853 /* Return 1 if iw is even, -1 if iw is odd; there's
854 * no guarantee that any C integral type is big
855 * enough to hold iw, so we have to check this
858 ix
= floor(iw
* 0.5) * 2.0;
859 return PyFloat_FromDouble(ix
== iw
? 1.0 : -1.0);
861 /* Else iv != -1.0, and overflow or underflow are possible.
862 * Unless we're to write pow() ourselves, we have to trust
863 * the platform to do this correctly.
867 PyFPE_START_PROTECT("pow", return NULL
)
869 PyFPE_END_PROTECT(ix
)
870 Py_ADJUST_ERANGE1(ix
);
872 /* We don't expect any errno value other than ERANGE, but
873 * the range of libm bugs appears unbounded.
875 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
879 return PyFloat_FromDouble(ix
);
883 float_neg(PyFloatObject
*v
)
885 return PyFloat_FromDouble(-v
->ob_fval
);
889 float_abs(PyFloatObject
*v
)
891 return PyFloat_FromDouble(fabs(v
->ob_fval
));
895 float_nonzero(PyFloatObject
*v
)
897 return v
->ob_fval
!= 0.0;
901 float_coerce(PyObject
**pv
, PyObject
**pw
)
903 if (PyInt_Check(*pw
)) {
904 long x
= PyInt_AsLong(*pw
);
905 *pw
= PyFloat_FromDouble((double)x
);
909 else if (PyLong_Check(*pw
)) {
910 double x
= PyLong_AsDouble(*pw
);
911 if (x
== -1.0 && PyErr_Occurred())
913 *pw
= PyFloat_FromDouble(x
);
917 else if (PyFloat_Check(*pw
)) {
922 return 1; /* Can't do it */
926 float_is_integer(PyObject
*v
)
928 double x
= PyFloat_AsDouble(v
);
931 if (x
== -1.0 && PyErr_Occurred())
933 if (!Py_IS_FINITE(x
))
936 PyFPE_START_PROTECT("is_integer", return NULL
)
937 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
940 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
950 float_is_inf(PyObject
*v
)
952 double x
= PyFloat_AsDouble(v
);
953 if (x
== -1.0 && PyErr_Occurred())
955 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
959 float_is_nan(PyObject
*v
)
961 double x
= PyFloat_AsDouble(v
);
962 if (x
== -1.0 && PyErr_Occurred())
964 return PyBool_FromLong((long)Py_IS_NAN(x
));
968 float_is_finite(PyObject
*v
)
970 double x
= PyFloat_AsDouble(v
);
971 if (x
== -1.0 && PyErr_Occurred())
973 return PyBool_FromLong((long)Py_IS_FINITE(x
));
978 float_trunc(PyObject
*v
)
980 double x
= PyFloat_AsDouble(v
);
981 double wholepart
; /* integral portion of x, rounded toward 0 */
983 (void)modf(x
, &wholepart
);
984 /* Try to get out cheap if this fits in a Python int. The attempt
985 * to cast to long must be protected, as C doesn't define what
986 * happens if the double is too big to fit in a long. Some rare
987 * systems raise an exception then (RISCOS was mentioned as one,
988 * and someone using a non-default option on Sun also bumped into
989 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
990 * still be vulnerable: if a long has more bits of precision than
991 * a double, casting MIN/MAX to double may yield an approximation,
992 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
993 * yield true from the C expression wholepart<=LONG_MAX, despite
994 * that wholepart is actually greater than LONG_MAX.
996 if (LONG_MIN
< wholepart
&& wholepart
< LONG_MAX
) {
997 const long aslong
= (long)wholepart
;
998 return PyInt_FromLong(aslong
);
1000 return PyLong_FromDouble(wholepart
);
1004 float_long(PyObject
*v
)
1006 double x
= PyFloat_AsDouble(v
);
1007 return PyLong_FromDouble(x
);
1011 float_float(PyObject
*v
)
1013 if (PyFloat_CheckExact(v
))
1016 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1020 /* turn ASCII hex characters into integer values and vice versa */
1023 char_from_hex(int x
)
1025 assert(0 <= x
&& x
< 16);
1026 return "0123456789abcdef"[x
];
1030 hex_from_char(char c
) {
1094 /* convert a float to a hexadecimal string */
1096 /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1097 of the form 4k+1. */
1098 #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1101 float_hex(PyObject
*v
)
1104 int e
, shift
, i
, si
, esign
;
1105 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1106 trailing NUL byte. */
1107 char s
[(TOHEX_NBITS
-1)/4+3];
1109 CONVERT_TO_DOUBLE(v
, x
);
1111 if (Py_IS_NAN(x
) || Py_IS_INFINITY(x
))
1112 return float_str((PyFloatObject
*)v
);
1115 if(copysign(1.0, x
) == -1.0)
1116 return PyString_FromString("-0x0.0p+0");
1118 return PyString_FromString("0x0.0p+0");
1121 m
= frexp(fabs(x
), &e
);
1122 shift
= 1 - MAX(DBL_MIN_EXP
- e
, 0);
1123 m
= ldexp(m
, shift
);
1127 s
[si
] = char_from_hex((int)m
);
1132 for (i
=0; i
< (TOHEX_NBITS
-1)/4; i
++) {
1134 s
[si
] = char_from_hex((int)m
);
1148 return PyString_FromFormat("-0x%sp%c%d", s
, esign
, e
);
1150 return PyString_FromFormat("0x%sp%c%d", s
, esign
, e
);
1153 PyDoc_STRVAR(float_hex_doc
,
1154 "float.hex() -> string\n\
1156 Return a hexadecimal representation of a floating-point number.\n\
1158 '-0x1.999999999999ap-4'\n\
1159 >>> 3.14159.hex()\n\
1160 '0x1.921f9f01b866ep+1'");
1162 /* Case-insensitive locale-independent string match used for nan and inf
1163 detection. t should be lower-case and null-terminated. Return a nonzero
1164 result if the first strlen(t) characters of s match t and 0 otherwise. */
1167 case_insensitive_match(const char *s
, const char *t
)
1169 while(*t
&& Py_TOLOWER(*s
) == *t
) {
1176 /* Convert a hexadecimal string to a float. */
1179 float_fromhex(PyObject
*cls
, PyObject
*arg
)
1181 PyObject
*result_as_float
, *result
;
1183 long exp
, top_exp
, lsb
, key_digit
;
1184 char *s
, *coeff_start
, *s_store
, *coeff_end
, *exp_start
, *s_end
;
1185 int half_eps
, digit
, round_up
, sign
=1;
1186 Py_ssize_t length
, ndigits
, fdigits
, i
;
1189 * For the sake of simplicity and correctness, we impose an artificial
1190 * limit on ndigits, the total number of hex digits in the coefficient
1191 * The limit is chosen to ensure that, writing exp for the exponent,
1193 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1194 * guaranteed to overflow (provided it's nonzero)
1196 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1197 * guaranteed to underflow to 0.
1199 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1200 * overflow in the calculation of exp and top_exp below.
1202 * More specifically, ndigits is assumed to satisfy the following
1205 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1206 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1208 * If either of these inequalities is not satisfied, a ValueError is
1209 * raised. Otherwise, write x for the value of the hex string, and
1210 * assume x is nonzero. Then
1212 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1214 * Now if exp > LONG_MAX/2 then:
1216 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1219 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1220 * double, so overflows. If exp < LONG_MIN/2, then
1222 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1223 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1224 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1226 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1227 * when converted to a C double.
1229 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1230 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1233 if (PyString_AsStringAndSize(arg
, &s
, &length
))
1237 /********************
1238 * Parse the string *
1239 ********************/
1241 /* leading whitespace and optional sign */
1242 while (Py_ISSPACE(*s
))
1251 /* infinities and nans */
1252 if (*s
== 'i' || *s
== 'I') {
1253 if (!case_insensitive_match(s
+1, "nf"))
1257 if (case_insensitive_match(s
, "inity"))
1261 if (*s
== 'n' || *s
== 'N') {
1262 if (!case_insensitive_match(s
+1, "an"))
1273 if (*s
== 'x' || *s
== 'X')
1279 /* coefficient: <integer> [. <fraction>] */
1281 while (hex_from_char(*s
) >= 0)
1286 while (hex_from_char(*s
) >= 0)
1293 /* ndigits = total # of hex digits; fdigits = # after point */
1294 ndigits
= coeff_end
- coeff_start
;
1295 fdigits
= coeff_end
- s_store
;
1298 if (ndigits
> MIN(DBL_MIN_EXP
- DBL_MANT_DIG
- LONG_MIN
/2,
1299 LONG_MAX
/2 + 1 - DBL_MAX_EXP
)/4)
1300 goto insane_length_error
;
1302 /* [p <exponent>] */
1303 if (*s
== 'p' || *s
== 'P') {
1306 if (*s
== '-' || *s
== '+')
1308 if (!('0' <= *s
&& *s
<= '9'))
1311 while ('0' <= *s
&& *s
<= '9')
1313 exp
= strtol(exp_start
, NULL
, 10);
1318 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1319 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1323 /*******************************************
1324 * Compute rounded value of the hex string *
1325 *******************************************/
1327 /* Discard leading zeros, and catch extreme overflow and underflow */
1328 while (ndigits
> 0 && HEX_DIGIT(ndigits
-1) == 0)
1330 if (ndigits
== 0 || exp
< LONG_MIN
/2) {
1334 if (exp
> LONG_MAX
/2)
1335 goto overflow_error
;
1337 /* Adjust exponent for fractional part. */
1338 exp
= exp
- 4*((long)fdigits
);
1340 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1341 top_exp
= exp
+ 4*((long)ndigits
- 1);
1342 for (digit
= HEX_DIGIT(ndigits
-1); digit
!= 0; digit
/= 2)
1345 /* catch almost all nonextreme cases of overflow and underflow here */
1346 if (top_exp
< DBL_MIN_EXP
- DBL_MANT_DIG
) {
1350 if (top_exp
> DBL_MAX_EXP
)
1351 goto overflow_error
;
1353 /* lsb = exponent of least significant bit of the *rounded* value.
1354 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1355 lsb
= MAX(top_exp
, (long)DBL_MIN_EXP
) - DBL_MANT_DIG
;
1359 /* no rounding required */
1360 for (i
= ndigits
-1; i
>= 0; i
--)
1361 x
= 16.0*x
+ HEX_DIGIT(i
);
1362 x
= ldexp(x
, (int)(exp
));
1365 /* rounding required. key_digit is the index of the hex digit
1366 containing the first bit to be rounded away. */
1367 half_eps
= 1 << (int)((lsb
- exp
- 1) % 4);
1368 key_digit
= (lsb
- exp
- 1) / 4;
1369 for (i
= ndigits
-1; i
> key_digit
; i
--)
1370 x
= 16.0*x
+ HEX_DIGIT(i
);
1371 digit
= HEX_DIGIT(key_digit
);
1372 x
= 16.0*x
+ (double)(digit
& (16-2*half_eps
));
1374 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1375 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1376 if ((digit
& half_eps
) != 0) {
1378 if ((digit
& (3*half_eps
-1)) != 0 ||
1379 (half_eps
== 8 && (HEX_DIGIT(key_digit
+1) & 1) != 0))
1382 for (i
= key_digit
-1; i
>= 0; i
--)
1383 if (HEX_DIGIT(i
) != 0) {
1387 if (round_up
== 1) {
1389 if (top_exp
== DBL_MAX_EXP
&&
1390 x
== ldexp((double)(2*half_eps
), DBL_MANT_DIG
))
1391 /* overflow corner case: pre-rounded value <
1392 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1393 goto overflow_error
;
1396 x
= ldexp(x
, (int)(exp
+4*key_digit
));
1399 /* optional trailing whitespace leading to the end of the string */
1400 while (Py_ISSPACE(*s
))
1404 result_as_float
= Py_BuildValue("(d)", sign
* x
);
1405 if (result_as_float
== NULL
)
1407 result
= PyObject_CallObject(cls
, result_as_float
);
1408 Py_DECREF(result_as_float
);
1412 PyErr_SetString(PyExc_OverflowError
,
1413 "hexadecimal value too large to represent as a float");
1417 PyErr_SetString(PyExc_ValueError
,
1418 "invalid hexadecimal floating-point string");
1421 insane_length_error
:
1422 PyErr_SetString(PyExc_ValueError
,
1423 "hexadecimal string too long to convert");
1427 PyDoc_STRVAR(float_fromhex_doc
,
1428 "float.fromhex(string) -> float\n\
1430 Create a floating-point number from a hexadecimal string.\n\
1431 >>> float.fromhex('0x1.ffffp10')\n\
1433 >>> float.fromhex('-0x1p-1074')\n\
1434 -4.9406564584124654e-324");
1438 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
1446 PyObject
*py_exponent
= NULL
;
1447 PyObject
*numerator
= NULL
;
1448 PyObject
*denominator
= NULL
;
1449 PyObject
*result_pair
= NULL
;
1450 PyNumberMethods
*long_methods
= PyLong_Type
.tp_as_number
;
1452 #define INPLACE_UPDATE(obj, call) \
1457 CONVERT_TO_DOUBLE(v, self);
1459 if (Py_IS_INFINITY(self
)) {
1460 PyErr_SetString(PyExc_OverflowError
,
1461 "Cannot pass infinity to float.as_integer_ratio.");
1465 if (Py_IS_NAN(self
)) {
1466 PyErr_SetString(PyExc_ValueError
,
1467 "Cannot pass NaN to float.as_integer_ratio.");
1472 PyFPE_START_PROTECT("as_integer_ratio", goto error
);
1473 float_part
= frexp(self
, &exponent
); /* self == float_part * 2**exponent exactly */
1474 PyFPE_END_PROTECT(float_part
);
1476 for (i
=0; i
<300 && float_part
!= floor(float_part
) ; i
++) {
1480 /* self == float_part * 2**exponent exactly and float_part is integral.
1481 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1482 to be truncated by PyLong_FromDouble(). */
1484 numerator
= PyLong_FromDouble(float_part
);
1485 if (numerator
== NULL
) goto error
;
1487 /* fold in 2**exponent */
1488 denominator
= PyLong_FromLong(1);
1489 py_exponent
= PyLong_FromLong(labs((long)exponent
));
1490 if (py_exponent
== NULL
) goto error
;
1491 INPLACE_UPDATE(py_exponent
,
1492 long_methods
->nb_lshift(denominator
, py_exponent
));
1493 if (py_exponent
== NULL
) goto error
;
1495 INPLACE_UPDATE(numerator
,
1496 long_methods
->nb_multiply(numerator
, py_exponent
));
1497 if (numerator
== NULL
) goto error
;
1500 Py_DECREF(denominator
);
1501 denominator
= py_exponent
;
1505 /* Returns ints instead of longs where possible */
1506 INPLACE_UPDATE(numerator
, PyNumber_Int(numerator
));
1507 if (numerator
== NULL
) goto error
;
1508 INPLACE_UPDATE(denominator
, PyNumber_Int(denominator
));
1509 if (denominator
== NULL
) goto error
;
1511 result_pair
= PyTuple_Pack(2, numerator
, denominator
);
1513 #undef INPLACE_UPDATE
1515 Py_XDECREF(py_exponent
);
1516 Py_XDECREF(denominator
);
1517 Py_XDECREF(numerator
);
1521 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1522 "float.as_integer_ratio() -> (int, int)\n"
1524 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
1525 "float and with a positive denominator.\n"
1526 "Raises OverflowError on infinities and a ValueError on NaNs.\n"
1528 ">>> (10.0).as_integer_ratio()\n"
1530 ">>> (0.0).as_integer_ratio()\n"
1532 ">>> (-.25).as_integer_ratio()\n"
1537 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
1540 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1542 PyObject
*x
= Py_False
; /* Integer zero */
1543 static char *kwlist
[] = {"x", 0};
1545 if (type
!= &PyFloat_Type
)
1546 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
1547 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
1549 /* If it's a string, but not a string subclass, use
1550 PyFloat_FromString. */
1551 if (PyString_CheckExact(x
))
1552 return PyFloat_FromString(x
, NULL
);
1553 return PyNumber_Float(x
);
1556 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1557 first create a regular float from whatever arguments we got,
1558 then allocate a subtype instance and initialize its ob_fval
1559 from the regular float. The regular float is then thrown away.
1562 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1564 PyObject
*tmp
, *newobj
;
1566 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
1567 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
1570 assert(PyFloat_CheckExact(tmp
));
1571 newobj
= type
->tp_alloc(type
, 0);
1572 if (newobj
== NULL
) {
1576 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
1582 float_getnewargs(PyFloatObject
*v
)
1584 return Py_BuildValue("(d)", v
->ob_fval
);
1587 /* this is for the benefit of the pack/unpack routines below */
1590 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
1591 } float_format_type
;
1593 static float_format_type double_format
, float_format
;
1594 static float_format_type detected_double_format
, detected_float_format
;
1597 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1600 float_format_type r
;
1602 if (!PyString_Check(arg
)) {
1603 PyErr_Format(PyExc_TypeError
,
1604 "__getformat__() argument must be string, not %.500s",
1605 Py_TYPE(arg
)->tp_name
);
1608 s
= PyString_AS_STRING(arg
);
1609 if (strcmp(s
, "double") == 0) {
1612 else if (strcmp(s
, "float") == 0) {
1616 PyErr_SetString(PyExc_ValueError
,
1617 "__getformat__() argument 1 must be "
1618 "'double' or 'float'");
1623 case unknown_format
:
1624 return PyString_FromString("unknown");
1625 case ieee_little_endian_format
:
1626 return PyString_FromString("IEEE, little-endian");
1627 case ieee_big_endian_format
:
1628 return PyString_FromString("IEEE, big-endian");
1630 Py_FatalError("insane float_format or double_format");
1635 PyDoc_STRVAR(float_getformat_doc
,
1636 "float.__getformat__(typestr) -> string\n"
1638 "You probably don't want to use this function. It exists mainly to be\n"
1639 "used in Python's test suite.\n"
1641 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1642 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1643 "format of floating point numbers used by the C type named by typestr.");
1646 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1650 float_format_type f
;
1651 float_format_type detected
;
1652 float_format_type
*p
;
1654 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1657 if (strcmp(typestr
, "double") == 0) {
1659 detected
= detected_double_format
;
1661 else if (strcmp(typestr
, "float") == 0) {
1663 detected
= detected_float_format
;
1666 PyErr_SetString(PyExc_ValueError
,
1667 "__setformat__() argument 1 must "
1668 "be 'double' or 'float'");
1672 if (strcmp(format
, "unknown") == 0) {
1675 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1676 f
= ieee_little_endian_format
;
1678 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1679 f
= ieee_big_endian_format
;
1682 PyErr_SetString(PyExc_ValueError
,
1683 "__setformat__() argument 2 must be "
1684 "'unknown', 'IEEE, little-endian' or "
1685 "'IEEE, big-endian'");
1690 if (f
!= unknown_format
&& f
!= detected
) {
1691 PyErr_Format(PyExc_ValueError
,
1692 "can only set %s format to 'unknown' or the "
1693 "detected platform value", typestr
);
1701 PyDoc_STRVAR(float_setformat_doc
,
1702 "float.__setformat__(typestr, fmt) -> None\n"
1704 "You probably don't want to use this function. It exists mainly to be\n"
1705 "used in Python's test suite.\n"
1707 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1708 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1709 "one of the latter two if it appears to match the underlying C reality.\n"
1711 "Overrides the automatic determination of C-level floating point type.\n"
1712 "This affects how floats are converted to and from binary strings.");
1715 float_getzero(PyObject
*v
, void *closure
)
1717 return PyFloat_FromDouble(0.0);
1721 float__format__(PyObject
*self
, PyObject
*args
)
1723 PyObject
*format_spec
;
1725 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1727 if (PyBytes_Check(format_spec
))
1728 return _PyFloat_FormatAdvanced(self
,
1729 PyBytes_AS_STRING(format_spec
),
1730 PyBytes_GET_SIZE(format_spec
));
1731 if (PyUnicode_Check(format_spec
)) {
1732 /* Convert format_spec to a str */
1734 PyObject
*str_spec
= PyObject_Str(format_spec
);
1736 if (str_spec
== NULL
)
1739 result
= _PyFloat_FormatAdvanced(self
,
1740 PyBytes_AS_STRING(str_spec
),
1741 PyBytes_GET_SIZE(str_spec
));
1743 Py_DECREF(str_spec
);
1746 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1750 PyDoc_STRVAR(float__format__doc
,
1751 "float.__format__(format_spec) -> string\n"
1753 "Formats the float according to format_spec.");
1756 static PyMethodDef float_methods
[] = {
1757 {"conjugate", (PyCFunction
)float_float
, METH_NOARGS
,
1758 "Returns self, the complex conjugate of any float."},
1759 {"__trunc__", (PyCFunction
)float_trunc
, METH_NOARGS
,
1760 "Returns the Integral closest to x between 0 and x."},
1761 {"as_integer_ratio", (PyCFunction
)float_as_integer_ratio
, METH_NOARGS
,
1762 float_as_integer_ratio_doc
},
1763 {"fromhex", (PyCFunction
)float_fromhex
,
1764 METH_O
|METH_CLASS
, float_fromhex_doc
},
1765 {"hex", (PyCFunction
)float_hex
,
1766 METH_NOARGS
, float_hex_doc
},
1767 {"is_integer", (PyCFunction
)float_is_integer
, METH_NOARGS
,
1768 "Returns True if the float is an integer."},
1770 {"is_inf", (PyCFunction
)float_is_inf
, METH_NOARGS
,
1771 "Returns True if the float is positive or negative infinite."},
1772 {"is_finite", (PyCFunction
)float_is_finite
, METH_NOARGS
,
1773 "Returns True if the float is finite, neither infinite nor NaN."},
1774 {"is_nan", (PyCFunction
)float_is_nan
, METH_NOARGS
,
1775 "Returns True if the float is not a number (NaN)."},
1777 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
1778 {"__getformat__", (PyCFunction
)float_getformat
,
1779 METH_O
|METH_CLASS
, float_getformat_doc
},
1780 {"__setformat__", (PyCFunction
)float_setformat
,
1781 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
1782 {"__format__", (PyCFunction
)float__format__
,
1783 METH_VARARGS
, float__format__doc
},
1784 {NULL
, NULL
} /* sentinel */
1787 static PyGetSetDef float_getset
[] = {
1789 (getter
)float_float
, (setter
)NULL
,
1790 "the real part of a complex number",
1793 (getter
)float_getzero
, (setter
)NULL
,
1794 "the imaginary part of a complex number",
1796 {NULL
} /* Sentinel */
1799 PyDoc_STRVAR(float_doc
,
1800 "float(x) -> floating point number\n\
1802 Convert a string or number to a floating point number, if possible.");
1805 static PyNumberMethods float_as_number
= {
1806 float_add
, /*nb_add*/
1807 float_sub
, /*nb_subtract*/
1808 float_mul
, /*nb_multiply*/
1809 float_classic_div
, /*nb_divide*/
1810 float_rem
, /*nb_remainder*/
1811 float_divmod
, /*nb_divmod*/
1812 float_pow
, /*nb_power*/
1813 (unaryfunc
)float_neg
, /*nb_negative*/
1814 (unaryfunc
)float_float
, /*nb_positive*/
1815 (unaryfunc
)float_abs
, /*nb_absolute*/
1816 (inquiry
)float_nonzero
, /*nb_nonzero*/
1823 float_coerce
, /*nb_coerce*/
1824 float_trunc
, /*nb_int*/
1825 float_long
, /*nb_long*/
1826 float_float
, /*nb_float*/
1829 0, /* nb_inplace_add */
1830 0, /* nb_inplace_subtract */
1831 0, /* nb_inplace_multiply */
1832 0, /* nb_inplace_divide */
1833 0, /* nb_inplace_remainder */
1834 0, /* nb_inplace_power */
1835 0, /* nb_inplace_lshift */
1836 0, /* nb_inplace_rshift */
1837 0, /* nb_inplace_and */
1838 0, /* nb_inplace_xor */
1839 0, /* nb_inplace_or */
1840 float_floor_div
, /* nb_floor_divide */
1841 float_div
, /* nb_true_divide */
1842 0, /* nb_inplace_floor_divide */
1843 0, /* nb_inplace_true_divide */
1846 PyTypeObject PyFloat_Type
= {
1847 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
1849 sizeof(PyFloatObject
),
1851 (destructor
)float_dealloc
, /* tp_dealloc */
1852 (printfunc
)float_print
, /* tp_print */
1856 (reprfunc
)float_repr
, /* tp_repr */
1857 &float_as_number
, /* tp_as_number */
1858 0, /* tp_as_sequence */
1859 0, /* tp_as_mapping */
1860 (hashfunc
)float_hash
, /* tp_hash */
1862 (reprfunc
)float_str
, /* tp_str */
1863 PyObject_GenericGetAttr
, /* tp_getattro */
1864 0, /* tp_setattro */
1865 0, /* tp_as_buffer */
1866 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
1867 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1868 float_doc
, /* tp_doc */
1869 0, /* tp_traverse */
1871 float_richcompare
, /* tp_richcompare */
1872 0, /* tp_weaklistoffset */
1874 0, /* tp_iternext */
1875 float_methods
, /* tp_methods */
1877 float_getset
, /* tp_getset */
1880 0, /* tp_descr_get */
1881 0, /* tp_descr_set */
1882 0, /* tp_dictoffset */
1885 float_new
, /* tp_new */
1891 /* We attempt to determine if this machine is using IEEE
1892 floating point formats by peering at the bits of some
1893 carefully chosen values. If it looks like we are on an
1894 IEEE platform, the float packing/unpacking routines can
1895 just copy bits, if not they resort to arithmetic & shifts
1896 and masks. The shifts & masks approach works on all finite
1897 values, but what happens to infinities, NaNs and signed
1898 zeroes on packing is an accident, and attempting to unpack
1899 a NaN or an infinity will raise an exception.
1901 Note that if we're on some whacked-out platform which uses
1902 IEEE formats but isn't strictly little-endian or big-
1903 endian, we will fall back to the portable shifts & masks
1906 #if SIZEOF_DOUBLE == 8
1908 double x
= 9006104071832581.0;
1909 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1910 detected_double_format
= ieee_big_endian_format
;
1911 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1912 detected_double_format
= ieee_little_endian_format
;
1914 detected_double_format
= unknown_format
;
1917 detected_double_format
= unknown_format
;
1920 #if SIZEOF_FLOAT == 4
1922 float y
= 16711938.0;
1923 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
1924 detected_float_format
= ieee_big_endian_format
;
1925 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
1926 detected_float_format
= ieee_little_endian_format
;
1928 detected_float_format
= unknown_format
;
1931 detected_float_format
= unknown_format
;
1934 double_format
= detected_double_format
;
1935 float_format
= detected_float_format
;
1937 /* Init float info */
1938 if (FloatInfoType
.tp_name
== 0)
1939 PyStructSequence_InitType(&FloatInfoType
, &floatinfo_desc
);
1943 PyFloat_ClearFreeList(void)
1946 PyFloatBlock
*list
, *next
;
1948 int u
; /* remaining unfreed ints per block */
1949 int freelist_size
= 0;
1954 while (list
!= NULL
) {
1956 for (i
= 0, p
= &list
->objects
[0];
1959 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
1964 list
->next
= block_list
;
1966 for (i
= 0, p
= &list
->objects
[0];
1969 if (!PyFloat_CheckExact(p
) ||
1970 Py_REFCNT(p
) == 0) {
1971 Py_TYPE(p
) = (struct _typeobject
*)
1983 return freelist_size
;
1992 int u
; /* total unfreed floats per block */
1994 u
= PyFloat_ClearFreeList();
1996 if (!Py_VerboseFlag
)
1998 fprintf(stderr
, "# cleanup floats");
2000 fprintf(stderr
, "\n");
2004 ": %d unfreed float%s\n",
2005 u
, u
== 1 ? "" : "s");
2007 if (Py_VerboseFlag
> 1) {
2009 while (list
!= NULL
) {
2010 for (i
= 0, p
= &list
->objects
[0];
2013 if (PyFloat_CheckExact(p
) &&
2014 Py_REFCNT(p
) != 0) {
2016 PyFloat_AsString(buf
, p
);
2017 /* XXX(twouters) cast refcount to
2018 long until %zd is universally
2022 "# <float at %p, refcnt=%ld, val=%s>\n",
2023 p
, (long)Py_REFCNT(p
), buf
);
2031 /*----------------------------------------------------------------------------
2032 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
2035 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
2037 if (float_format
== unknown_format
) {
2058 /* Normalize f to be in the range [1.0, 2.0) */
2059 if (0.5 <= f
&& f
< 1.0) {
2066 PyErr_SetString(PyExc_SystemError
,
2067 "frexp() result out of range");
2073 else if (e
< -126) {
2074 /* Gradual underflow */
2075 f
= ldexp(f
, 126 + e
);
2078 else if (!(e
== 0 && f
== 0.0)) {
2080 f
-= 1.0; /* Get rid of leading 1 */
2083 f
*= 8388608.0; /* 2**23 */
2084 fbits
= (unsigned int)(f
+ 0.5); /* Round */
2085 assert(fbits
<= 8388608);
2087 /* The carry propagated out of a string of 23 1 bits. */
2095 *p
= (sign
<< 7) | (e
>> 1);
2099 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
2103 *p
= (fbits
>> 8) & 0xFF;
2115 const char *s
= (char*)&y
;
2118 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
2121 if ((float_format
== ieee_little_endian_format
&& !le
)
2122 || (float_format
== ieee_big_endian_format
&& le
)) {
2127 for (i
= 0; i
< 4; i
++) {
2134 PyErr_SetString(PyExc_OverflowError
,
2135 "float too large to pack with f format");
2140 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
2142 if (double_format
== unknown_format
) {
2146 unsigned int fhi
, flo
;
2163 /* Normalize f to be in the range [1.0, 2.0) */
2164 if (0.5 <= f
&& f
< 1.0) {
2171 PyErr_SetString(PyExc_SystemError
,
2172 "frexp() result out of range");
2178 else if (e
< -1022) {
2179 /* Gradual underflow */
2180 f
= ldexp(f
, 1022 + e
);
2183 else if (!(e
== 0 && f
== 0.0)) {
2185 f
-= 1.0; /* Get rid of leading 1 */
2188 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2189 f
*= 268435456.0; /* 2**28 */
2190 fhi
= (unsigned int)f
; /* Truncate */
2191 assert(fhi
< 268435456);
2194 f
*= 16777216.0; /* 2**24 */
2195 flo
= (unsigned int)(f
+ 0.5); /* Round */
2196 assert(flo
<= 16777216);
2198 /* The carry propagated out of a string of 24 1 bits. */
2202 /* And it also progagated out of the next 28 bits. */
2211 *p
= (sign
<< 7) | (e
>> 4);
2215 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
2219 *p
= (fhi
>> 16) & 0xFF;
2223 *p
= (fhi
>> 8) & 0xFF;
2231 *p
= (flo
>> 16) & 0xFF;
2235 *p
= (flo
>> 8) & 0xFF;
2246 PyErr_SetString(PyExc_OverflowError
,
2247 "float too large to pack with d format");
2251 const char *s
= (char*)&x
;
2254 if ((double_format
== ieee_little_endian_format
&& !le
)
2255 || (double_format
== ieee_big_endian_format
&& le
)) {
2260 for (i
= 0; i
< 8; i
++) {
2269 _PyFloat_Unpack4(const unsigned char *p
, int le
)
2271 if (float_format
== unknown_format
) {
2284 sign
= (*p
>> 7) & 1;
2285 e
= (*p
& 0x7F) << 1;
2290 f
= (*p
& 0x7F) << 16;
2296 "can't unpack IEEE 754 special value "
2297 "on non-IEEE platform");
2308 x
= (double)f
/ 8388608.0;
2310 /* XXX This sadly ignores Inf/NaN issues */
2327 if ((float_format
== ieee_little_endian_format
&& !le
)
2328 || (float_format
== ieee_big_endian_format
&& le
)) {
2333 for (i
= 0; i
< 4; i
++) {
2347 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2349 if (double_format
== unknown_format
) {
2352 unsigned int fhi
, flo
;
2362 sign
= (*p
>> 7) & 1;
2363 e
= (*p
& 0x7F) << 4;
2368 e
|= (*p
>> 4) & 0xF;
2369 fhi
= (*p
& 0xF) << 24;
2375 "can't unpack IEEE 754 special value "
2376 "on non-IEEE platform");
2403 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2404 x
/= 268435456.0; /* 2**28 */
2422 if ((double_format
== ieee_little_endian_format
&& !le
)
2423 || (double_format
== ieee_big_endian_format
&& le
)) {
2428 for (i
= 0; i
< 8; i
++) {