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))
19 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20 extern int finite(double);
23 /* Special free list -- see comments for same code in intobject.c. */
24 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
25 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
26 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
29 struct _floatblock
*next
;
30 PyFloatObject objects
[N_FLOATOBJECTS
];
33 typedef struct _floatblock PyFloatBlock
;
35 static PyFloatBlock
*block_list
= NULL
;
36 static PyFloatObject
*free_list
= NULL
;
38 static PyFloatObject
*
42 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
43 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
45 return (PyFloatObject
*) PyErr_NoMemory();
46 ((PyFloatBlock
*)p
)->next
= block_list
;
47 block_list
= (PyFloatBlock
*)p
;
48 p
= &((PyFloatBlock
*)p
)->objects
[0];
49 q
= p
+ N_FLOATOBJECTS
;
51 Py_TYPE(q
) = (struct _typeobject
*)(q
-1);
53 return p
+ N_FLOATOBJECTS
- 1;
68 static PyTypeObject FloatInfoType
= {0, 0, 0, 0, 0, 0};
70 PyDoc_STRVAR(floatinfo__doc__
,
73 A structseq holding information about the float type. It contains low level\n\
74 information about the precision and internal representation. Please study\n\
75 your system's :file:`float.h` for more information.");
77 static PyStructSequence_Field floatinfo_fields
[] = {
78 {"max", "DBL_MAX -- maximum representable finite float"},
79 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 {"min", "DBL_MIN -- Minimum positive normalizer float"},
84 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
85 "is a normalized float"},
86 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 {"dig", "DBL_DIG -- digits"},
89 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
90 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
91 "representable float"},
92 {"radix", "FLT_RADIX -- radix of exponent"},
93 {"rounds", "FLT_ROUNDS -- addition rounds"},
97 static PyStructSequence_Desc floatinfo_desc
= {
98 "sys.float_info", /* name */
99 floatinfo__doc__
, /* doc */
100 floatinfo_fields
, /* fields */
105 PyFloat_GetInfo(void)
110 floatinfo
= PyStructSequence_New(&FloatInfoType
);
111 if (floatinfo
== NULL
) {
115 #define SetIntFlag(flag) \
116 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
117 #define SetDblFlag(flag) \
118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
121 SetIntFlag(DBL_MAX_EXP
);
122 SetIntFlag(DBL_MAX_10_EXP
);
124 SetIntFlag(DBL_MIN_EXP
);
125 SetIntFlag(DBL_MIN_10_EXP
);
127 SetIntFlag(DBL_MANT_DIG
);
128 SetDblFlag(DBL_EPSILON
);
129 SetIntFlag(FLT_RADIX
);
130 SetIntFlag(FLT_ROUNDS
);
134 if (PyErr_Occurred()) {
142 PyFloat_FromDouble(double fval
)
144 register PyFloatObject
*op
;
145 if (free_list
== NULL
) {
146 if ((free_list
= fill_free_list()) == NULL
)
149 /* Inline PyObject_New */
151 free_list
= (PyFloatObject
*)Py_TYPE(op
);
152 PyObject_INIT(op
, &PyFloat_Type
);
154 return (PyObject
*) op
;
157 /**************************************************************************
158 RED_FLAG 22-Sep-2000 tim
159 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
161 1. If v was a regular string, *pend was set to point to its terminating
162 null byte. That's useless (the caller can find that without any
163 help from this function!).
165 2. If v was a Unicode string, or an object convertible to a character
166 buffer, *pend was set to point into stack trash (the auto temp
167 vector holding the character buffer). That was downright dangerous.
169 Since we can't change the interface of a public API function, pend is
170 still supported but now *officially* useless: if pend is not NULL,
171 *pend is set to NULL.
172 **************************************************************************/
174 PyFloat_FromString(PyObject
*v
, char **pend
)
176 const char *s
, *last
, *end
;
178 char buffer
[256]; /* for errors */
179 #ifdef Py_USING_UNICODE
180 char *s_buffer
= NULL
;
183 PyObject
*result
= NULL
;
187 if (PyString_Check(v
)) {
188 s
= PyString_AS_STRING(v
);
189 len
= PyString_GET_SIZE(v
);
191 #ifdef Py_USING_UNICODE
192 else if (PyUnicode_Check(v
)) {
193 s_buffer
= (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v
)+1);
194 if (s_buffer
== NULL
)
195 return PyErr_NoMemory();
196 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
197 PyUnicode_GET_SIZE(v
),
205 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
206 PyErr_SetString(PyExc_TypeError
,
207 "float() argument must be a string or a number");
212 while (Py_ISSPACE(*s
))
214 /* We don't care about overflow or underflow. If the platform
215 * supports them, infinities and signed zeroes (on underflow) are
217 x
= PyOS_string_to_double(s
, (char **)&end
, NULL
);
218 if (x
== -1.0 && PyErr_Occurred())
220 while (Py_ISSPACE(*end
))
223 result
= PyFloat_FromDouble(x
);
225 PyOS_snprintf(buffer
, sizeof(buffer
),
226 "invalid literal for float(): %.200s", s
);
227 PyErr_SetString(PyExc_ValueError
, buffer
);
232 #ifdef Py_USING_UNICODE
234 PyMem_FREE(s_buffer
);
240 float_dealloc(PyFloatObject
*op
)
242 if (PyFloat_CheckExact(op
)) {
243 Py_TYPE(op
) = (struct _typeobject
*)free_list
;
247 Py_TYPE(op
)->tp_free((PyObject
*)op
);
251 PyFloat_AsDouble(PyObject
*op
)
257 if (op
&& PyFloat_Check(op
))
258 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
265 if ((nb
= Py_TYPE(op
)->tp_as_number
) == NULL
|| nb
->nb_float
== NULL
) {
266 PyErr_SetString(PyExc_TypeError
, "a float is required");
270 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
273 if (!PyFloat_Check(fo
)) {
275 PyErr_SetString(PyExc_TypeError
,
276 "nb_float should return float object");
280 val
= PyFloat_AS_DOUBLE(fo
);
288 /* Macro and helper that convert PyObject obj to a C double and store
289 the value in dbl; this replaces the functionality of the coercion
290 slot function. If conversion to double raises an exception, obj is
291 set to NULL, and the function invoking this macro returns NULL. If
292 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
293 stored in obj, and returned from the function invoking this macro.
295 #define CONVERT_TO_DOUBLE(obj, dbl) \
296 if (PyFloat_Check(obj)) \
297 dbl = PyFloat_AS_DOUBLE(obj); \
298 else if (convert_to_double(&(obj), &(dbl)) < 0) \
302 convert_to_double(PyObject
**v
, double *dbl
)
304 register PyObject
*obj
= *v
;
306 if (PyInt_Check(obj
)) {
307 *dbl
= (double)PyInt_AS_LONG(obj
);
309 else if (PyLong_Check(obj
)) {
310 *dbl
= PyLong_AsDouble(obj
);
311 if (*dbl
== -1.0 && PyErr_Occurred()) {
317 Py_INCREF(Py_NotImplemented
);
318 *v
= Py_NotImplemented
;
324 /* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
325 XXX they pass a char buffer without passing a length.
328 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
330 char *tmp
= PyOS_double_to_string(v
->ob_fval
, 'g',
331 PyFloat_STR_PRECISION
,
332 Py_DTSF_ADD_DOT_0
, NULL
);
338 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
340 char * tmp
= PyOS_double_to_string(v
->ob_fval
, 'r', 0,
341 Py_DTSF_ADD_DOT_0
, NULL
);
348 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
351 if (flags
& Py_PRINT_RAW
)
352 buf
= PyOS_double_to_string(v
->ob_fval
,
353 'g', PyFloat_STR_PRECISION
,
354 Py_DTSF_ADD_DOT_0
, NULL
);
356 buf
= PyOS_double_to_string(v
->ob_fval
,
357 'r', 0, Py_DTSF_ADD_DOT_0
, NULL
);
358 Py_BEGIN_ALLOW_THREADS
366 float_str_or_repr(PyFloatObject
*v
, int precision
, char format_code
)
369 char *buf
= PyOS_double_to_string(PyFloat_AS_DOUBLE(v
),
370 format_code
, precision
,
374 return PyErr_NoMemory();
375 result
= PyString_FromString(buf
);
381 float_repr(PyFloatObject
*v
)
383 return float_str_or_repr(v
, 0, 'r');
387 float_str(PyFloatObject
*v
)
389 return float_str_or_repr(v
, PyFloat_STR_PRECISION
, 'g');
392 /* Comparison is pretty much a nightmare. When comparing float to float,
393 * we do it as straightforwardly (and long-windedly) as conceivable, so
394 * that, e.g., Python x == y delivers the same result as the platform
395 * C x == y when x and/or y is a NaN.
396 * When mixing float with an integer type, there's no good *uniform* approach.
397 * Converting the double to an integer obviously doesn't work, since we
398 * may lose info from fractional bits. Converting the integer to a double
399 * also has two failure modes: (1) a long int may trigger overflow (too
400 * large to fit in the dynamic range of a C double); (2) even a C long may have
401 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
402 * 63 bits of precision, but a C double probably has only 53), and then
403 * we can falsely claim equality when low-order integer bits are lost by
404 * coercion to double. So this part is painful too.
408 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
413 assert(PyFloat_Check(v
));
414 i
= PyFloat_AS_DOUBLE(v
);
416 /* Switch on the type of w. Set i and j to doubles to be compared,
417 * and op to the richcomp to use.
419 if (PyFloat_Check(w
))
420 j
= PyFloat_AS_DOUBLE(w
);
422 else if (!Py_IS_FINITE(i
)) {
423 if (PyInt_Check(w
) || PyLong_Check(w
))
424 /* If i is an infinity, its magnitude exceeds any
425 * finite integer, so it doesn't matter which int we
426 * compare i with. If i is a NaN, similarly.
433 else if (PyInt_Check(w
)) {
434 long jj
= PyInt_AS_LONG(w
);
435 /* In the worst realistic case I can imagine, C double is a
436 * Cray single with 48 bits of precision, and long has 64
440 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
442 /* Needs more than 48 bits. Make it take the
446 PyObject
*ww
= PyLong_FromLong(jj
);
450 result
= float_richcompare(v
, ww
, op
);
456 assert((long)j
== jj
);
459 else if (PyLong_Check(w
)) {
460 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
461 int wsign
= _PyLong_Sign(w
);
465 if (vsign
!= wsign
) {
466 /* Magnitudes are irrelevant -- the signs alone
467 * determine the outcome.
473 /* The signs are the same. */
474 /* Convert w to a double if it fits. In particular, 0 fits. */
475 nbits
= _PyLong_NumBits(w
);
476 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
477 /* This long is so large that size_t isn't big enough
478 * to hold the # of bits. Replace with little doubles
479 * that give the same outcome -- w is so large that
480 * its magnitude must exceed the magnitude of any
490 j
= PyLong_AsDouble(w
);
491 /* It's impossible that <= 48 bits overflowed. */
492 assert(j
!= -1.0 || ! PyErr_Occurred());
495 assert(wsign
!= 0); /* else nbits was 0 */
496 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
497 * not 0, we would have taken the
498 * vsign != wsign branch at the start */
499 /* We want to work with non-negative numbers. */
501 /* "Multiply both sides" by -1; this also swaps the
505 op
= _Py_SwappedOp
[op
];
508 (void) frexp(i
, &exponent
);
509 /* exponent is the # of bits in v before the radix point;
510 * we know that nbits (the # of bits in w) > 48 at this point
512 if (exponent
< 0 || (size_t)exponent
< nbits
) {
517 if ((size_t)exponent
> nbits
) {
522 /* v and w have the same number of bits before the radix
523 * point. Construct two longs that have the same comparison
529 PyObject
*result
= NULL
;
530 PyObject
*one
= NULL
;
535 ww
= PyNumber_Negative(w
);
542 fracpart
= modf(i
, &intpart
);
543 vv
= PyLong_FromDouble(intpart
);
547 if (fracpart
!= 0.0) {
548 /* Shift left, and or a 1 bit into vv
549 * to represent the lost fraction.
553 one
= PyInt_FromLong(1);
557 temp
= PyNumber_Lshift(ww
, one
);
563 temp
= PyNumber_Lshift(vv
, one
);
569 temp
= PyNumber_Or(vv
, one
);
576 r
= PyObject_RichCompareBool(vv
, ww
, op
);
579 result
= PyBool_FromLong(r
);
586 } /* else if (PyLong_Check(w)) */
588 else /* w isn't float, int, or long */
592 PyFPE_START_PROTECT("richcompare", return NULL
)
614 return PyBool_FromLong(r
);
617 Py_INCREF(Py_NotImplemented
);
618 return Py_NotImplemented
;
622 float_hash(PyFloatObject
*v
)
624 return _Py_HashDouble(v
->ob_fval
);
628 float_add(PyObject
*v
, PyObject
*w
)
631 CONVERT_TO_DOUBLE(v
, a
);
632 CONVERT_TO_DOUBLE(w
, b
);
633 PyFPE_START_PROTECT("add", return 0)
636 return PyFloat_FromDouble(a
);
640 float_sub(PyObject
*v
, PyObject
*w
)
643 CONVERT_TO_DOUBLE(v
, a
);
644 CONVERT_TO_DOUBLE(w
, b
);
645 PyFPE_START_PROTECT("subtract", return 0)
648 return PyFloat_FromDouble(a
);
652 float_mul(PyObject
*v
, PyObject
*w
)
655 CONVERT_TO_DOUBLE(v
, a
);
656 CONVERT_TO_DOUBLE(w
, b
);
657 PyFPE_START_PROTECT("multiply", return 0)
660 return PyFloat_FromDouble(a
);
664 float_div(PyObject
*v
, PyObject
*w
)
667 CONVERT_TO_DOUBLE(v
, a
);
668 CONVERT_TO_DOUBLE(w
, b
);
671 PyErr_SetString(PyExc_ZeroDivisionError
,
672 "float division by zero");
676 PyFPE_START_PROTECT("divide", return 0)
679 return PyFloat_FromDouble(a
);
683 float_classic_div(PyObject
*v
, PyObject
*w
)
686 CONVERT_TO_DOUBLE(v
, a
);
687 CONVERT_TO_DOUBLE(w
, b
);
688 if (Py_DivisionWarningFlag
>= 2 &&
689 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
693 PyErr_SetString(PyExc_ZeroDivisionError
,
694 "float division by zero");
698 PyFPE_START_PROTECT("divide", return 0)
701 return PyFloat_FromDouble(a
);
705 float_rem(PyObject
*v
, PyObject
*w
)
709 CONVERT_TO_DOUBLE(v
, vx
);
710 CONVERT_TO_DOUBLE(w
, wx
);
713 PyErr_SetString(PyExc_ZeroDivisionError
,
718 PyFPE_START_PROTECT("modulo", return 0)
721 /* ensure the remainder has the same sign as the denominator */
722 if ((wx
< 0) != (mod
< 0)) {
727 /* the remainder is zero, and in the presence of signed zeroes
728 fmod returns different results across platforms; ensure
729 it has the same sign as the denominator; we'd like to do
730 "mod = wx * 0.0", but that may get optimized away */
731 mod
*= mod
; /* hide "mod = +0" from optimizer */
735 PyFPE_END_PROTECT(mod
)
736 return PyFloat_FromDouble(mod
);
740 float_divmod(PyObject
*v
, PyObject
*w
)
743 double div
, mod
, floordiv
;
744 CONVERT_TO_DOUBLE(v
, vx
);
745 CONVERT_TO_DOUBLE(w
, wx
);
747 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
750 PyFPE_START_PROTECT("divmod", return 0)
752 /* fmod is typically exact, so vx-mod is *mathematically* an
753 exact multiple of wx. But this is fp arithmetic, and fp
754 vx - mod is an approximation; the result is that div may
755 not be an exact integral value after the division, although
756 it will always be very close to one.
758 div
= (vx
- mod
) / wx
;
760 /* ensure the remainder has the same sign as the denominator */
761 if ((wx
< 0) != (mod
< 0)) {
767 /* the remainder is zero, and in the presence of signed zeroes
768 fmod returns different results across platforms; ensure
769 it has the same sign as the denominator; we'd like to do
770 "mod = wx * 0.0", but that may get optimized away */
771 mod
*= mod
; /* hide "mod = +0" from optimizer */
775 /* snap quotient to nearest integral value */
777 floordiv
= floor(div
);
778 if (div
- floordiv
> 0.5)
782 /* div is zero - get the same sign as the true quotient */
783 div
*= div
; /* hide "div = +0" from optimizers */
784 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
786 PyFPE_END_PROTECT(floordiv
)
787 return Py_BuildValue("(dd)", floordiv
, mod
);
791 float_floor_div(PyObject
*v
, PyObject
*w
)
795 t
= float_divmod(v
, w
);
796 if (t
== NULL
|| t
== Py_NotImplemented
)
798 assert(PyTuple_CheckExact(t
));
799 r
= PyTuple_GET_ITEM(t
, 0);
805 /* determine whether x is an odd integer or not; assumes that
806 x is not an infinity or nan. */
807 #define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
810 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
813 int negate_result
= 0;
815 if ((PyObject
*)z
!= Py_None
) {
816 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
817 "allowed unless all arguments are integers");
821 CONVERT_TO_DOUBLE(v
, iv
);
822 CONVERT_TO_DOUBLE(w
, iw
);
824 /* Sort out special cases here instead of relying on pow() */
825 if (iw
== 0) { /* v**0 is 1, even 0**0 */
826 return PyFloat_FromDouble(1.0);
828 if (Py_IS_NAN(iv
)) { /* nan**w = nan, unless w == 0 */
829 return PyFloat_FromDouble(iv
);
831 if (Py_IS_NAN(iw
)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
832 return PyFloat_FromDouble(iv
== 1.0 ? 1.0 : iw
);
834 if (Py_IS_INFINITY(iw
)) {
835 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
836 * abs(v) > 1 (including case where v infinite)
838 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
839 * abs(v) > 1 (including case where v infinite)
843 return PyFloat_FromDouble(1.0);
844 else if ((iw
> 0.0) == (iv
> 1.0))
845 return PyFloat_FromDouble(fabs(iw
)); /* return inf */
847 return PyFloat_FromDouble(0.0);
849 if (Py_IS_INFINITY(iv
)) {
850 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
851 * both cases, we need to add the appropriate sign if w is
854 int iw_is_odd
= DOUBLE_IS_ODD_INTEGER(iw
);
856 return PyFloat_FromDouble(iw_is_odd
? iv
: fabs(iv
));
858 return PyFloat_FromDouble(iw_is_odd
?
859 copysign(0.0, iv
) : 0.0);
861 if (iv
== 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
862 (already dealt with above), and an error
864 int iw_is_odd
= DOUBLE_IS_ODD_INTEGER(iw
);
866 PyErr_SetString(PyExc_ZeroDivisionError
,
867 "0.0 cannot be raised to a "
871 /* use correct sign if iw is odd */
872 return PyFloat_FromDouble(iw_is_odd
? iv
: 0.0);
876 /* Whether this is an error is a mess, and bumps into libm
877 * bugs so we have to figure it out ourselves.
879 if (iw
!= floor(iw
)) {
880 PyErr_SetString(PyExc_ValueError
, "negative number "
881 "cannot be raised to a fractional power");
884 /* iw is an exact integer, albeit perhaps a very large
885 * one. Replace iv by its absolute value and remember
886 * to negate the pow result if iw is odd.
889 negate_result
= DOUBLE_IS_ODD_INTEGER(iw
);
892 if (iv
== 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
893 /* (-1) ** large_integer also ends up here. Here's an
894 * extract from the comments for the previous
895 * implementation explaining why this special case is
898 * -1 raised to an exact integer should never be exceptional.
899 * Alas, some libms (chiefly glibc as of early 2003) return
900 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
901 * happen to be representable in a *C* integer. That's a
904 return PyFloat_FromDouble(negate_result
? -1.0 : 1.0);
907 /* Now iv and iw are finite, iw is nonzero, and iv is
908 * positive and not equal to 1.0. We finally allow
909 * the platform pow to step in and do the rest.
912 PyFPE_START_PROTECT("pow", return NULL
)
914 PyFPE_END_PROTECT(ix
)
915 Py_ADJUST_ERANGE1(ix
);
920 /* We don't expect any errno value other than ERANGE, but
921 * the range of libm bugs appears unbounded.
923 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
927 return PyFloat_FromDouble(ix
);
930 #undef DOUBLE_IS_ODD_INTEGER
933 float_neg(PyFloatObject
*v
)
935 return PyFloat_FromDouble(-v
->ob_fval
);
939 float_abs(PyFloatObject
*v
)
941 return PyFloat_FromDouble(fabs(v
->ob_fval
));
945 float_nonzero(PyFloatObject
*v
)
947 return v
->ob_fval
!= 0.0;
951 float_coerce(PyObject
**pv
, PyObject
**pw
)
953 if (PyInt_Check(*pw
)) {
954 long x
= PyInt_AsLong(*pw
);
955 *pw
= PyFloat_FromDouble((double)x
);
959 else if (PyLong_Check(*pw
)) {
960 double x
= PyLong_AsDouble(*pw
);
961 if (x
== -1.0 && PyErr_Occurred())
963 *pw
= PyFloat_FromDouble(x
);
967 else if (PyFloat_Check(*pw
)) {
972 return 1; /* Can't do it */
976 float_is_integer(PyObject
*v
)
978 double x
= PyFloat_AsDouble(v
);
981 if (x
== -1.0 && PyErr_Occurred())
983 if (!Py_IS_FINITE(x
))
986 PyFPE_START_PROTECT("is_integer", return NULL
)
987 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
990 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
1000 float_is_inf(PyObject
*v
)
1002 double x
= PyFloat_AsDouble(v
);
1003 if (x
== -1.0 && PyErr_Occurred())
1005 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
1009 float_is_nan(PyObject
*v
)
1011 double x
= PyFloat_AsDouble(v
);
1012 if (x
== -1.0 && PyErr_Occurred())
1014 return PyBool_FromLong((long)Py_IS_NAN(x
));
1018 float_is_finite(PyObject
*v
)
1020 double x
= PyFloat_AsDouble(v
);
1021 if (x
== -1.0 && PyErr_Occurred())
1023 return PyBool_FromLong((long)Py_IS_FINITE(x
));
1028 float_trunc(PyObject
*v
)
1030 double x
= PyFloat_AsDouble(v
);
1031 double wholepart
; /* integral portion of x, rounded toward 0 */
1033 (void)modf(x
, &wholepart
);
1034 /* Try to get out cheap if this fits in a Python int. The attempt
1035 * to cast to long must be protected, as C doesn't define what
1036 * happens if the double is too big to fit in a long. Some rare
1037 * systems raise an exception then (RISCOS was mentioned as one,
1038 * and someone using a non-default option on Sun also bumped into
1039 * that). Note that checking for <= LONG_MAX is unsafe: if a long
1040 * has more bits of precision than a double, casting LONG_MAX to
1041 * double may yield an approximation, and if that's rounded up,
1042 * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
1043 * expression wholepart<=LONG_MAX, despite that wholepart is
1044 * actually greater than LONG_MAX. However, assuming a two's complement
1045 * machine with no trap representation, LONG_MIN will be a power of 2 (and
1046 * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
1047 * the comparisons with (double)LONG_MIN below should be safe.
1049 if ((double)LONG_MIN
<= wholepart
&& wholepart
< -(double)LONG_MIN
) {
1050 const long aslong
= (long)wholepart
;
1051 return PyInt_FromLong(aslong
);
1053 return PyLong_FromDouble(wholepart
);
1057 float_long(PyObject
*v
)
1059 double x
= PyFloat_AsDouble(v
);
1060 return PyLong_FromDouble(x
);
1063 /* _Py_double_round: rounds a finite nonzero double to the closest multiple of
1064 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1065 ndigits <= 323). Returns a Python float, or sets a Python error and
1066 returns NULL on failure (OverflowError and memory errors are possible). */
1068 #ifndef PY_NO_SHORT_FLOAT_REPR
1069 /* version of _Py_double_round that uses the correctly-rounded string<->double
1070 conversions from Python/dtoa.c */
1072 /* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1073 a double. Since we're using the code in Python/dtoa.c, it should be safe
1074 to assume that C doubles are IEEE 754 binary64 format. To be on the safe
1075 side, we check this. */
1076 #if DBL_MANT_DIG == 53
1077 #define FIVE_POW_LIMIT 22
1079 #error "C doubles do not appear to be IEEE 754 binary64 format"
1083 _Py_double_round(double x
, int ndigits
) {
1086 Py_ssize_t buflen
, mybuflen
=100;
1087 char *buf
, *buf_end
, shortbuf
[100], *mybuf
=shortbuf
;
1088 int decpt
, sign
, val
, halfway_case
;
1089 PyObject
*result
= NULL
;
1090 _Py_SET_53BIT_PRECISION_HEADER
;
1092 /* Easy path for the common case ndigits == 0. */
1095 if (fabs(rounded
- x
) == 0.5)
1096 /* halfway between two integers; use round-away-from-zero */
1097 rounded
= x
+ (x
> 0.0 ? 0.5 : -0.5);
1098 return PyFloat_FromDouble(rounded
);
1101 /* The basic idea is very simple: convert and round the double to a
1102 decimal string using _Py_dg_dtoa, then convert that decimal string
1103 back to a double with _Py_dg_strtod. There's one minor difficulty:
1104 Python 2.x expects round to do round-half-away-from-zero, while
1105 _Py_dg_dtoa does round-half-to-even. So we need some way to detect
1106 and correct the halfway cases.
1108 Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1109 some odd integer k. Or in other words, a rational number x is
1110 exactly halfway between two multiples of 10**-ndigits if its
1111 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1112 -ndigits. For ndigits >= 0 the latter condition is automatically
1113 satisfied for a binary float x, since any such float has
1114 nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
1115 integral multiple of 5**-ndigits; we can check this using fmod.
1116 For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1117 to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1118 23 takes at least 54 bits of precision to represent exactly.
1120 Correction: a simple strategy for dealing with halfway cases is to
1121 (for the halfway cases only) call _Py_dg_dtoa with an argument of
1122 ndigits+1 instead of ndigits (thus doing an exact conversion to
1123 decimal), round the resulting string manually, and then convert
1124 back using _Py_dg_strtod.
1127 /* nans, infinities and zeros should have already been dealt
1128 with by the caller (in this case, builtin_round) */
1129 assert(Py_IS_FINITE(x
) && x
!= 0.0);
1131 /* find 2-valuation val of x */
1133 while (m
!= floor(m
)) {
1138 /* determine whether this is a halfway case */
1139 if (val
== -ndigits
-1) {
1142 else if (ndigits
>= -FIVE_POW_LIMIT
) {
1143 double five_pow
= 1.0;
1145 for (i
=0; i
< -ndigits
; i
++)
1147 halfway_case
= fmod(x
, five_pow
) == 0.0;
1155 /* round to a decimal string; use an extra place for halfway case */
1156 _Py_SET_53BIT_PRECISION_START
;
1157 buf
= _Py_dg_dtoa(x
, 3, ndigits
+halfway_case
, &decpt
, &sign
, &buf_end
);
1158 _Py_SET_53BIT_PRECISION_END
;
1163 buflen
= buf_end
- buf
;
1165 /* in halfway case, do the round-half-away-from-zero manually */
1168 /* sanity check: _Py_dg_dtoa should not have stripped
1169 any zeros from the result: there should be exactly
1170 ndigits+1 places following the decimal point, and
1171 the last digit in the buffer should be a '5'.*/
1172 assert(buflen
- decpt
== ndigits
+1);
1173 assert(buf
[buflen
-1] == '5');
1175 /* increment and shift right at the same time. */
1178 for (i
=buflen
-1; i
-- > 0;) {
1179 carry
+= buf
[i
] - '0';
1180 buf
[i
+1] = carry
% 10 + '0';
1183 buf
[0] = carry
+ '0';
1186 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
1187 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1188 if (buflen
+ 8 > mybuflen
) {
1189 mybuflen
= buflen
+8;
1190 mybuf
= (char *)PyMem_Malloc(mybuflen
);
1191 if (mybuf
== NULL
) {
1196 /* copy buf to mybuf, adding exponent, sign and leading 0 */
1197 PyOS_snprintf(mybuf
, mybuflen
, "%s0%se%d", (sign
? "-" : ""),
1198 buf
, decpt
- (int)buflen
);
1200 /* and convert the resulting string back to a double */
1202 _Py_SET_53BIT_PRECISION_START
;
1203 rounded
= _Py_dg_strtod(mybuf
, NULL
);
1204 _Py_SET_53BIT_PRECISION_END
;
1205 if (errno
== ERANGE
&& fabs(rounded
) >= 1.)
1206 PyErr_SetString(PyExc_OverflowError
,
1207 "rounded value too large to represent");
1209 result
= PyFloat_FromDouble(rounded
);
1211 /* done computing value; now clean up */
1212 if (mybuf
!= shortbuf
)
1215 _Py_dg_freedtoa(buf
);
1219 #undef FIVE_POW_LIMIT
1221 #else /* PY_NO_SHORT_FLOAT_REPR */
1223 /* fallback version, to be used when correctly rounded binary<->decimal
1224 conversions aren't available */
1227 _Py_double_round(double x
, int ndigits
) {
1228 double pow1
, pow2
, y
, z
;
1231 /* pow1 and pow2 are each safe from overflow, but
1232 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1233 pow1
= pow(10.0, (double)(ndigits
-22));
1237 pow1
= pow(10.0, (double)ndigits
);
1241 /* if y overflows, then rounded value is exactly x */
1242 if (!Py_IS_FINITE(y
))
1243 return PyFloat_FromDouble(x
);
1246 pow1
= pow(10.0, (double)-ndigits
);
1247 pow2
= 1.0; /* unused; silences a gcc compiler warning */
1252 if (fabs(y
-z
) == 0.5)
1253 /* halfway between two integers; use round-away-from-zero */
1254 z
= y
+ copysign(0.5, y
);
1257 z
= (z
/ pow2
) / pow1
;
1261 /* if computation resulted in overflow, raise OverflowError */
1262 if (!Py_IS_FINITE(z
)) {
1263 PyErr_SetString(PyExc_OverflowError
,
1264 "overflow occurred during round");
1268 return PyFloat_FromDouble(z
);
1271 #endif /* PY_NO_SHORT_FLOAT_REPR */
1274 float_float(PyObject
*v
)
1276 if (PyFloat_CheckExact(v
))
1279 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1283 /* turn ASCII hex characters into integer values and vice versa */
1286 char_from_hex(int x
)
1288 assert(0 <= x
&& x
< 16);
1289 return "0123456789abcdef"[x
];
1293 hex_from_char(char c
) {
1357 /* convert a float to a hexadecimal string */
1359 /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1360 of the form 4k+1. */
1361 #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1364 float_hex(PyObject
*v
)
1367 int e
, shift
, i
, si
, esign
;
1368 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1369 trailing NUL byte. */
1370 char s
[(TOHEX_NBITS
-1)/4+3];
1372 CONVERT_TO_DOUBLE(v
, x
);
1374 if (Py_IS_NAN(x
) || Py_IS_INFINITY(x
))
1375 return float_str((PyFloatObject
*)v
);
1378 if (copysign(1.0, x
) == -1.0)
1379 return PyString_FromString("-0x0.0p+0");
1381 return PyString_FromString("0x0.0p+0");
1384 m
= frexp(fabs(x
), &e
);
1385 shift
= 1 - MAX(DBL_MIN_EXP
- e
, 0);
1386 m
= ldexp(m
, shift
);
1390 s
[si
] = char_from_hex((int)m
);
1395 for (i
=0; i
< (TOHEX_NBITS
-1)/4; i
++) {
1397 s
[si
] = char_from_hex((int)m
);
1411 return PyString_FromFormat("-0x%sp%c%d", s
, esign
, e
);
1413 return PyString_FromFormat("0x%sp%c%d", s
, esign
, e
);
1416 PyDoc_STRVAR(float_hex_doc
,
1417 "float.hex() -> string\n\
1419 Return a hexadecimal representation of a floating-point number.\n\
1421 '-0x1.999999999999ap-4'\n\
1422 >>> 3.14159.hex()\n\
1423 '0x1.921f9f01b866ep+1'");
1425 /* Case-insensitive locale-independent string match used for nan and inf
1426 detection. t should be lower-case and null-terminated. Return a nonzero
1427 result if the first strlen(t) characters of s match t and 0 otherwise. */
1430 case_insensitive_match(const char *s
, const char *t
)
1432 while(*t
&& Py_TOLOWER(*s
) == *t
) {
1439 /* Convert a hexadecimal string to a float. */
1442 float_fromhex(PyObject
*cls
, PyObject
*arg
)
1444 PyObject
*result_as_float
, *result
;
1446 long exp
, top_exp
, lsb
, key_digit
;
1447 char *s
, *coeff_start
, *s_store
, *coeff_end
, *exp_start
, *s_end
;
1448 int half_eps
, digit
, round_up
, sign
=1;
1449 Py_ssize_t length
, ndigits
, fdigits
, i
;
1452 * For the sake of simplicity and correctness, we impose an artificial
1453 * limit on ndigits, the total number of hex digits in the coefficient
1454 * The limit is chosen to ensure that, writing exp for the exponent,
1456 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1457 * guaranteed to overflow (provided it's nonzero)
1459 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1460 * guaranteed to underflow to 0.
1462 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1463 * overflow in the calculation of exp and top_exp below.
1465 * More specifically, ndigits is assumed to satisfy the following
1468 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1469 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1471 * If either of these inequalities is not satisfied, a ValueError is
1472 * raised. Otherwise, write x for the value of the hex string, and
1473 * assume x is nonzero. Then
1475 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1477 * Now if exp > LONG_MAX/2 then:
1479 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1482 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1483 * double, so overflows. If exp < LONG_MIN/2, then
1485 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1486 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1487 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1489 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1490 * when converted to a C double.
1492 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1493 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1496 if (PyString_AsStringAndSize(arg
, &s
, &length
))
1500 /********************
1501 * Parse the string *
1502 ********************/
1504 /* leading whitespace and optional sign */
1505 while (Py_ISSPACE(*s
))
1514 /* infinities and nans */
1515 if (*s
== 'i' || *s
== 'I') {
1516 if (!case_insensitive_match(s
+1, "nf"))
1520 if (case_insensitive_match(s
, "inity"))
1524 if (*s
== 'n' || *s
== 'N') {
1525 if (!case_insensitive_match(s
+1, "an"))
1536 if (*s
== 'x' || *s
== 'X')
1542 /* coefficient: <integer> [. <fraction>] */
1544 while (hex_from_char(*s
) >= 0)
1549 while (hex_from_char(*s
) >= 0)
1556 /* ndigits = total # of hex digits; fdigits = # after point */
1557 ndigits
= coeff_end
- coeff_start
;
1558 fdigits
= coeff_end
- s_store
;
1561 if (ndigits
> MIN(DBL_MIN_EXP
- DBL_MANT_DIG
- LONG_MIN
/2,
1562 LONG_MAX
/2 + 1 - DBL_MAX_EXP
)/4)
1563 goto insane_length_error
;
1565 /* [p <exponent>] */
1566 if (*s
== 'p' || *s
== 'P') {
1569 if (*s
== '-' || *s
== '+')
1571 if (!('0' <= *s
&& *s
<= '9'))
1574 while ('0' <= *s
&& *s
<= '9')
1576 exp
= strtol(exp_start
, NULL
, 10);
1581 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1582 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1586 /*******************************************
1587 * Compute rounded value of the hex string *
1588 *******************************************/
1590 /* Discard leading zeros, and catch extreme overflow and underflow */
1591 while (ndigits
> 0 && HEX_DIGIT(ndigits
-1) == 0)
1593 if (ndigits
== 0 || exp
< LONG_MIN
/2) {
1597 if (exp
> LONG_MAX
/2)
1598 goto overflow_error
;
1600 /* Adjust exponent for fractional part. */
1601 exp
= exp
- 4*((long)fdigits
);
1603 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1604 top_exp
= exp
+ 4*((long)ndigits
- 1);
1605 for (digit
= HEX_DIGIT(ndigits
-1); digit
!= 0; digit
/= 2)
1608 /* catch almost all nonextreme cases of overflow and underflow here */
1609 if (top_exp
< DBL_MIN_EXP
- DBL_MANT_DIG
) {
1613 if (top_exp
> DBL_MAX_EXP
)
1614 goto overflow_error
;
1616 /* lsb = exponent of least significant bit of the *rounded* value.
1617 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1618 lsb
= MAX(top_exp
, (long)DBL_MIN_EXP
) - DBL_MANT_DIG
;
1622 /* no rounding required */
1623 for (i
= ndigits
-1; i
>= 0; i
--)
1624 x
= 16.0*x
+ HEX_DIGIT(i
);
1625 x
= ldexp(x
, (int)(exp
));
1628 /* rounding required. key_digit is the index of the hex digit
1629 containing the first bit to be rounded away. */
1630 half_eps
= 1 << (int)((lsb
- exp
- 1) % 4);
1631 key_digit
= (lsb
- exp
- 1) / 4;
1632 for (i
= ndigits
-1; i
> key_digit
; i
--)
1633 x
= 16.0*x
+ HEX_DIGIT(i
);
1634 digit
= HEX_DIGIT(key_digit
);
1635 x
= 16.0*x
+ (double)(digit
& (16-2*half_eps
));
1637 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1638 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1639 if ((digit
& half_eps
) != 0) {
1641 if ((digit
& (3*half_eps
-1)) != 0 ||
1642 (half_eps
== 8 && (HEX_DIGIT(key_digit
+1) & 1) != 0))
1645 for (i
= key_digit
-1; i
>= 0; i
--)
1646 if (HEX_DIGIT(i
) != 0) {
1650 if (round_up
== 1) {
1652 if (top_exp
== DBL_MAX_EXP
&&
1653 x
== ldexp((double)(2*half_eps
), DBL_MANT_DIG
))
1654 /* overflow corner case: pre-rounded value <
1655 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1656 goto overflow_error
;
1659 x
= ldexp(x
, (int)(exp
+4*key_digit
));
1662 /* optional trailing whitespace leading to the end of the string */
1663 while (Py_ISSPACE(*s
))
1667 result_as_float
= Py_BuildValue("(d)", sign
* x
);
1668 if (result_as_float
== NULL
)
1670 result
= PyObject_CallObject(cls
, result_as_float
);
1671 Py_DECREF(result_as_float
);
1675 PyErr_SetString(PyExc_OverflowError
,
1676 "hexadecimal value too large to represent as a float");
1680 PyErr_SetString(PyExc_ValueError
,
1681 "invalid hexadecimal floating-point string");
1684 insane_length_error
:
1685 PyErr_SetString(PyExc_ValueError
,
1686 "hexadecimal string too long to convert");
1690 PyDoc_STRVAR(float_fromhex_doc
,
1691 "float.fromhex(string) -> float\n\
1693 Create a floating-point number from a hexadecimal string.\n\
1694 >>> float.fromhex('0x1.ffffp10')\n\
1696 >>> float.fromhex('-0x1p-1074')\n\
1697 -4.9406564584124654e-324");
1701 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
1709 PyObject
*py_exponent
= NULL
;
1710 PyObject
*numerator
= NULL
;
1711 PyObject
*denominator
= NULL
;
1712 PyObject
*result_pair
= NULL
;
1713 PyNumberMethods
*long_methods
= PyLong_Type
.tp_as_number
;
1715 #define INPLACE_UPDATE(obj, call) \
1720 CONVERT_TO_DOUBLE(v, self);
1722 if (Py_IS_INFINITY(self
)) {
1723 PyErr_SetString(PyExc_OverflowError
,
1724 "Cannot pass infinity to float.as_integer_ratio.");
1728 if (Py_IS_NAN(self
)) {
1729 PyErr_SetString(PyExc_ValueError
,
1730 "Cannot pass NaN to float.as_integer_ratio.");
1735 PyFPE_START_PROTECT("as_integer_ratio", goto error
);
1736 float_part
= frexp(self
, &exponent
); /* self == float_part * 2**exponent exactly */
1737 PyFPE_END_PROTECT(float_part
);
1739 for (i
=0; i
<300 && float_part
!= floor(float_part
) ; i
++) {
1743 /* self == float_part * 2**exponent exactly and float_part is integral.
1744 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1745 to be truncated by PyLong_FromDouble(). */
1747 numerator
= PyLong_FromDouble(float_part
);
1748 if (numerator
== NULL
) goto error
;
1750 /* fold in 2**exponent */
1751 denominator
= PyLong_FromLong(1);
1752 py_exponent
= PyLong_FromLong(labs((long)exponent
));
1753 if (py_exponent
== NULL
) goto error
;
1754 INPLACE_UPDATE(py_exponent
,
1755 long_methods
->nb_lshift(denominator
, py_exponent
));
1756 if (py_exponent
== NULL
) goto error
;
1758 INPLACE_UPDATE(numerator
,
1759 long_methods
->nb_multiply(numerator
, py_exponent
));
1760 if (numerator
== NULL
) goto error
;
1763 Py_DECREF(denominator
);
1764 denominator
= py_exponent
;
1768 /* Returns ints instead of longs where possible */
1769 INPLACE_UPDATE(numerator
, PyNumber_Int(numerator
));
1770 if (numerator
== NULL
) goto error
;
1771 INPLACE_UPDATE(denominator
, PyNumber_Int(denominator
));
1772 if (denominator
== NULL
) goto error
;
1774 result_pair
= PyTuple_Pack(2, numerator
, denominator
);
1776 #undef INPLACE_UPDATE
1778 Py_XDECREF(py_exponent
);
1779 Py_XDECREF(denominator
);
1780 Py_XDECREF(numerator
);
1784 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1785 "float.as_integer_ratio() -> (int, int)\n"
1787 "Return a pair of integers, whose ratio is exactly equal to the original\n"
1788 "float and with a positive denominator.\n"
1789 "Raise OverflowError on infinities and a ValueError on NaNs.\n"
1791 ">>> (10.0).as_integer_ratio()\n"
1793 ">>> (0.0).as_integer_ratio()\n"
1795 ">>> (-.25).as_integer_ratio()\n"
1800 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
1803 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1805 PyObject
*x
= Py_False
; /* Integer zero */
1806 static char *kwlist
[] = {"x", 0};
1808 if (type
!= &PyFloat_Type
)
1809 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
1810 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
1812 /* If it's a string, but not a string subclass, use
1813 PyFloat_FromString. */
1814 if (PyString_CheckExact(x
))
1815 return PyFloat_FromString(x
, NULL
);
1816 return PyNumber_Float(x
);
1819 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1820 first create a regular float from whatever arguments we got,
1821 then allocate a subtype instance and initialize its ob_fval
1822 from the regular float. The regular float is then thrown away.
1825 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1827 PyObject
*tmp
, *newobj
;
1829 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
1830 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
1833 assert(PyFloat_CheckExact(tmp
));
1834 newobj
= type
->tp_alloc(type
, 0);
1835 if (newobj
== NULL
) {
1839 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
1845 float_getnewargs(PyFloatObject
*v
)
1847 return Py_BuildValue("(d)", v
->ob_fval
);
1850 /* this is for the benefit of the pack/unpack routines below */
1853 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
1854 } float_format_type
;
1856 static float_format_type double_format
, float_format
;
1857 static float_format_type detected_double_format
, detected_float_format
;
1860 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1863 float_format_type r
;
1865 if (!PyString_Check(arg
)) {
1866 PyErr_Format(PyExc_TypeError
,
1867 "__getformat__() argument must be string, not %.500s",
1868 Py_TYPE(arg
)->tp_name
);
1871 s
= PyString_AS_STRING(arg
);
1872 if (strcmp(s
, "double") == 0) {
1875 else if (strcmp(s
, "float") == 0) {
1879 PyErr_SetString(PyExc_ValueError
,
1880 "__getformat__() argument 1 must be "
1881 "'double' or 'float'");
1886 case unknown_format
:
1887 return PyString_FromString("unknown");
1888 case ieee_little_endian_format
:
1889 return PyString_FromString("IEEE, little-endian");
1890 case ieee_big_endian_format
:
1891 return PyString_FromString("IEEE, big-endian");
1893 Py_FatalError("insane float_format or double_format");
1898 PyDoc_STRVAR(float_getformat_doc
,
1899 "float.__getformat__(typestr) -> string\n"
1901 "You probably don't want to use this function. It exists mainly to be\n"
1902 "used in Python's test suite.\n"
1904 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1905 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1906 "format of floating point numbers used by the C type named by typestr.");
1909 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1913 float_format_type f
;
1914 float_format_type detected
;
1915 float_format_type
*p
;
1917 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1920 if (strcmp(typestr
, "double") == 0) {
1922 detected
= detected_double_format
;
1924 else if (strcmp(typestr
, "float") == 0) {
1926 detected
= detected_float_format
;
1929 PyErr_SetString(PyExc_ValueError
,
1930 "__setformat__() argument 1 must "
1931 "be 'double' or 'float'");
1935 if (strcmp(format
, "unknown") == 0) {
1938 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1939 f
= ieee_little_endian_format
;
1941 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1942 f
= ieee_big_endian_format
;
1945 PyErr_SetString(PyExc_ValueError
,
1946 "__setformat__() argument 2 must be "
1947 "'unknown', 'IEEE, little-endian' or "
1948 "'IEEE, big-endian'");
1953 if (f
!= unknown_format
&& f
!= detected
) {
1954 PyErr_Format(PyExc_ValueError
,
1955 "can only set %s format to 'unknown' or the "
1956 "detected platform value", typestr
);
1964 PyDoc_STRVAR(float_setformat_doc
,
1965 "float.__setformat__(typestr, fmt) -> None\n"
1967 "You probably don't want to use this function. It exists mainly to be\n"
1968 "used in Python's test suite.\n"
1970 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1971 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1972 "one of the latter two if it appears to match the underlying C reality.\n"
1974 "Override the automatic determination of C-level floating point type.\n"
1975 "This affects how floats are converted to and from binary strings.");
1978 float_getzero(PyObject
*v
, void *closure
)
1980 return PyFloat_FromDouble(0.0);
1984 float__format__(PyObject
*self
, PyObject
*args
)
1986 PyObject
*format_spec
;
1988 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1990 if (PyBytes_Check(format_spec
))
1991 return _PyFloat_FormatAdvanced(self
,
1992 PyBytes_AS_STRING(format_spec
),
1993 PyBytes_GET_SIZE(format_spec
));
1994 if (PyUnicode_Check(format_spec
)) {
1995 /* Convert format_spec to a str */
1997 PyObject
*str_spec
= PyObject_Str(format_spec
);
1999 if (str_spec
== NULL
)
2002 result
= _PyFloat_FormatAdvanced(self
,
2003 PyBytes_AS_STRING(str_spec
),
2004 PyBytes_GET_SIZE(str_spec
));
2006 Py_DECREF(str_spec
);
2009 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
2013 PyDoc_STRVAR(float__format__doc
,
2014 "float.__format__(format_spec) -> string\n"
2016 "Formats the float according to format_spec.");
2019 static PyMethodDef float_methods
[] = {
2020 {"conjugate", (PyCFunction
)float_float
, METH_NOARGS
,
2021 "Return self, the complex conjugate of any float."},
2022 {"__trunc__", (PyCFunction
)float_trunc
, METH_NOARGS
,
2023 "Return the Integral closest to x between 0 and x."},
2024 {"as_integer_ratio", (PyCFunction
)float_as_integer_ratio
, METH_NOARGS
,
2025 float_as_integer_ratio_doc
},
2026 {"fromhex", (PyCFunction
)float_fromhex
,
2027 METH_O
|METH_CLASS
, float_fromhex_doc
},
2028 {"hex", (PyCFunction
)float_hex
,
2029 METH_NOARGS
, float_hex_doc
},
2030 {"is_integer", (PyCFunction
)float_is_integer
, METH_NOARGS
,
2031 "Return True if the float is an integer."},
2033 {"is_inf", (PyCFunction
)float_is_inf
, METH_NOARGS
,
2034 "Return True if the float is positive or negative infinite."},
2035 {"is_finite", (PyCFunction
)float_is_finite
, METH_NOARGS
,
2036 "Return True if the float is finite, neither infinite nor NaN."},
2037 {"is_nan", (PyCFunction
)float_is_nan
, METH_NOARGS
,
2038 "Return True if the float is not a number (NaN)."},
2040 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
2041 {"__getformat__", (PyCFunction
)float_getformat
,
2042 METH_O
|METH_CLASS
, float_getformat_doc
},
2043 {"__setformat__", (PyCFunction
)float_setformat
,
2044 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
2045 {"__format__", (PyCFunction
)float__format__
,
2046 METH_VARARGS
, float__format__doc
},
2047 {NULL
, NULL
} /* sentinel */
2050 static PyGetSetDef float_getset
[] = {
2052 (getter
)float_float
, (setter
)NULL
,
2053 "the real part of a complex number",
2056 (getter
)float_getzero
, (setter
)NULL
,
2057 "the imaginary part of a complex number",
2059 {NULL
} /* Sentinel */
2062 PyDoc_STRVAR(float_doc
,
2063 "float(x) -> floating point number\n\
2065 Convert a string or number to a floating point number, if possible.");
2068 static PyNumberMethods float_as_number
= {
2069 float_add
, /*nb_add*/
2070 float_sub
, /*nb_subtract*/
2071 float_mul
, /*nb_multiply*/
2072 float_classic_div
, /*nb_divide*/
2073 float_rem
, /*nb_remainder*/
2074 float_divmod
, /*nb_divmod*/
2075 float_pow
, /*nb_power*/
2076 (unaryfunc
)float_neg
, /*nb_negative*/
2077 (unaryfunc
)float_float
, /*nb_positive*/
2078 (unaryfunc
)float_abs
, /*nb_absolute*/
2079 (inquiry
)float_nonzero
, /*nb_nonzero*/
2086 float_coerce
, /*nb_coerce*/
2087 float_trunc
, /*nb_int*/
2088 float_long
, /*nb_long*/
2089 float_float
, /*nb_float*/
2092 0, /* nb_inplace_add */
2093 0, /* nb_inplace_subtract */
2094 0, /* nb_inplace_multiply */
2095 0, /* nb_inplace_divide */
2096 0, /* nb_inplace_remainder */
2097 0, /* nb_inplace_power */
2098 0, /* nb_inplace_lshift */
2099 0, /* nb_inplace_rshift */
2100 0, /* nb_inplace_and */
2101 0, /* nb_inplace_xor */
2102 0, /* nb_inplace_or */
2103 float_floor_div
, /* nb_floor_divide */
2104 float_div
, /* nb_true_divide */
2105 0, /* nb_inplace_floor_divide */
2106 0, /* nb_inplace_true_divide */
2109 PyTypeObject PyFloat_Type
= {
2110 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2112 sizeof(PyFloatObject
),
2114 (destructor
)float_dealloc
, /* tp_dealloc */
2115 (printfunc
)float_print
, /* tp_print */
2119 (reprfunc
)float_repr
, /* tp_repr */
2120 &float_as_number
, /* tp_as_number */
2121 0, /* tp_as_sequence */
2122 0, /* tp_as_mapping */
2123 (hashfunc
)float_hash
, /* tp_hash */
2125 (reprfunc
)float_str
, /* tp_str */
2126 PyObject_GenericGetAttr
, /* tp_getattro */
2127 0, /* tp_setattro */
2128 0, /* tp_as_buffer */
2129 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2130 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2131 float_doc
, /* tp_doc */
2132 0, /* tp_traverse */
2134 float_richcompare
, /* tp_richcompare */
2135 0, /* tp_weaklistoffset */
2137 0, /* tp_iternext */
2138 float_methods
, /* tp_methods */
2140 float_getset
, /* tp_getset */
2143 0, /* tp_descr_get */
2144 0, /* tp_descr_set */
2145 0, /* tp_dictoffset */
2148 float_new
, /* tp_new */
2154 /* We attempt to determine if this machine is using IEEE
2155 floating point formats by peering at the bits of some
2156 carefully chosen values. If it looks like we are on an
2157 IEEE platform, the float packing/unpacking routines can
2158 just copy bits, if not they resort to arithmetic & shifts
2159 and masks. The shifts & masks approach works on all finite
2160 values, but what happens to infinities, NaNs and signed
2161 zeroes on packing is an accident, and attempting to unpack
2162 a NaN or an infinity will raise an exception.
2164 Note that if we're on some whacked-out platform which uses
2165 IEEE formats but isn't strictly little-endian or big-
2166 endian, we will fall back to the portable shifts & masks
2169 #if SIZEOF_DOUBLE == 8
2171 double x
= 9006104071832581.0;
2172 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2173 detected_double_format
= ieee_big_endian_format
;
2174 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2175 detected_double_format
= ieee_little_endian_format
;
2177 detected_double_format
= unknown_format
;
2180 detected_double_format
= unknown_format
;
2183 #if SIZEOF_FLOAT == 4
2185 float y
= 16711938.0;
2186 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
2187 detected_float_format
= ieee_big_endian_format
;
2188 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
2189 detected_float_format
= ieee_little_endian_format
;
2191 detected_float_format
= unknown_format
;
2194 detected_float_format
= unknown_format
;
2197 double_format
= detected_double_format
;
2198 float_format
= detected_float_format
;
2200 /* Init float info */
2201 if (FloatInfoType
.tp_name
== 0)
2202 PyStructSequence_InitType(&FloatInfoType
, &floatinfo_desc
);
2206 PyFloat_ClearFreeList(void)
2209 PyFloatBlock
*list
, *next
;
2211 int u
; /* remaining unfreed ints per block */
2212 int freelist_size
= 0;
2217 while (list
!= NULL
) {
2219 for (i
= 0, p
= &list
->objects
[0];
2222 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
2227 list
->next
= block_list
;
2229 for (i
= 0, p
= &list
->objects
[0];
2232 if (!PyFloat_CheckExact(p
) ||
2233 Py_REFCNT(p
) == 0) {
2234 Py_TYPE(p
) = (struct _typeobject
*)
2246 return freelist_size
;
2255 int u
; /* total unfreed floats per block */
2257 u
= PyFloat_ClearFreeList();
2259 if (!Py_VerboseFlag
)
2261 fprintf(stderr
, "# cleanup floats");
2263 fprintf(stderr
, "\n");
2267 ": %d unfreed float%s\n",
2268 u
, u
== 1 ? "" : "s");
2270 if (Py_VerboseFlag
> 1) {
2272 while (list
!= NULL
) {
2273 for (i
= 0, p
= &list
->objects
[0];
2276 if (PyFloat_CheckExact(p
) &&
2277 Py_REFCNT(p
) != 0) {
2278 char *buf
= PyOS_double_to_string(
2279 PyFloat_AS_DOUBLE(p
), 'r',
2282 /* XXX(twouters) cast
2289 "# <float at %p, refcnt=%ld, val=%s>\n",
2290 p
, (long)Py_REFCNT(p
), buf
);
2300 /*----------------------------------------------------------------------------
2301 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
2304 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
2306 if (float_format
== unknown_format
) {
2327 /* Normalize f to be in the range [1.0, 2.0) */
2328 if (0.5 <= f
&& f
< 1.0) {
2335 PyErr_SetString(PyExc_SystemError
,
2336 "frexp() result out of range");
2342 else if (e
< -126) {
2343 /* Gradual underflow */
2344 f
= ldexp(f
, 126 + e
);
2347 else if (!(e
== 0 && f
== 0.0)) {
2349 f
-= 1.0; /* Get rid of leading 1 */
2352 f
*= 8388608.0; /* 2**23 */
2353 fbits
= (unsigned int)(f
+ 0.5); /* Round */
2354 assert(fbits
<= 8388608);
2356 /* The carry propagated out of a string of 23 1 bits. */
2364 *p
= (sign
<< 7) | (e
>> 1);
2368 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
2372 *p
= (fbits
>> 8) & 0xFF;
2384 const char *s
= (char*)&y
;
2387 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
2390 if ((float_format
== ieee_little_endian_format
&& !le
)
2391 || (float_format
== ieee_big_endian_format
&& le
)) {
2396 for (i
= 0; i
< 4; i
++) {
2403 PyErr_SetString(PyExc_OverflowError
,
2404 "float too large to pack with f format");
2409 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
2411 if (double_format
== unknown_format
) {
2415 unsigned int fhi
, flo
;
2432 /* Normalize f to be in the range [1.0, 2.0) */
2433 if (0.5 <= f
&& f
< 1.0) {
2440 PyErr_SetString(PyExc_SystemError
,
2441 "frexp() result out of range");
2447 else if (e
< -1022) {
2448 /* Gradual underflow */
2449 f
= ldexp(f
, 1022 + e
);
2452 else if (!(e
== 0 && f
== 0.0)) {
2454 f
-= 1.0; /* Get rid of leading 1 */
2457 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2458 f
*= 268435456.0; /* 2**28 */
2459 fhi
= (unsigned int)f
; /* Truncate */
2460 assert(fhi
< 268435456);
2463 f
*= 16777216.0; /* 2**24 */
2464 flo
= (unsigned int)(f
+ 0.5); /* Round */
2465 assert(flo
<= 16777216);
2467 /* The carry propagated out of a string of 24 1 bits. */
2471 /* And it also progagated out of the next 28 bits. */
2480 *p
= (sign
<< 7) | (e
>> 4);
2484 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
2488 *p
= (fhi
>> 16) & 0xFF;
2492 *p
= (fhi
>> 8) & 0xFF;
2500 *p
= (flo
>> 16) & 0xFF;
2504 *p
= (flo
>> 8) & 0xFF;
2509 /* p += incr; Unneeded (for now) */
2515 PyErr_SetString(PyExc_OverflowError
,
2516 "float too large to pack with d format");
2520 const char *s
= (char*)&x
;
2523 if ((double_format
== ieee_little_endian_format
&& !le
)
2524 || (double_format
== ieee_big_endian_format
&& le
)) {
2529 for (i
= 0; i
< 8; i
++) {
2538 _PyFloat_Unpack4(const unsigned char *p
, int le
)
2540 if (float_format
== unknown_format
) {
2553 sign
= (*p
>> 7) & 1;
2554 e
= (*p
& 0x7F) << 1;
2559 f
= (*p
& 0x7F) << 16;
2565 "can't unpack IEEE 754 special value "
2566 "on non-IEEE platform");
2577 x
= (double)f
/ 8388608.0;
2579 /* XXX This sadly ignores Inf/NaN issues */
2596 if ((float_format
== ieee_little_endian_format
&& !le
)
2597 || (float_format
== ieee_big_endian_format
&& le
)) {
2602 for (i
= 0; i
< 4; i
++) {
2616 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2618 if (double_format
== unknown_format
) {
2621 unsigned int fhi
, flo
;
2631 sign
= (*p
>> 7) & 1;
2632 e
= (*p
& 0x7F) << 4;
2637 e
|= (*p
>> 4) & 0xF;
2638 fhi
= (*p
& 0xF) << 24;
2644 "can't unpack IEEE 754 special value "
2645 "on non-IEEE platform");
2672 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2673 x
/= 268435456.0; /* 2**28 */
2691 if ((double_format
== ieee_little_endian_format
&& !le
)
2692 || (double_format
== ieee_big_endian_format
&& le
)) {
2697 for (i
= 0; i
< 8; i
++) {