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
)) {
274 PyErr_SetString(PyExc_TypeError
,
275 "nb_float should return float object");
279 val
= PyFloat_AS_DOUBLE(fo
);
287 /* Macro and helper that convert PyObject obj to a C double and store
288 the value in dbl; this replaces the functionality of the coercion
289 slot function. If conversion to double raises an exception, obj is
290 set to NULL, and the function invoking this macro returns NULL. If
291 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
292 stored in obj, and returned from the function invoking this macro.
294 #define CONVERT_TO_DOUBLE(obj, dbl) \
295 if (PyFloat_Check(obj)) \
296 dbl = PyFloat_AS_DOUBLE(obj); \
297 else if (convert_to_double(&(obj), &(dbl)) < 0) \
301 convert_to_double(PyObject
**v
, double *dbl
)
303 register PyObject
*obj
= *v
;
305 if (PyInt_Check(obj
)) {
306 *dbl
= (double)PyInt_AS_LONG(obj
);
308 else if (PyLong_Check(obj
)) {
309 *dbl
= PyLong_AsDouble(obj
);
310 if (*dbl
== -1.0 && PyErr_Occurred()) {
316 Py_INCREF(Py_NotImplemented
);
317 *v
= Py_NotImplemented
;
323 /* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
324 XXX they pass a char buffer without passing a length.
327 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
329 char *tmp
= PyOS_double_to_string(v
->ob_fval
, 'g',
330 PyFloat_STR_PRECISION
,
331 Py_DTSF_ADD_DOT_0
, NULL
);
337 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
339 char * tmp
= PyOS_double_to_string(v
->ob_fval
, 'r', 0,
340 Py_DTSF_ADD_DOT_0
, NULL
);
347 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
350 if (flags
& Py_PRINT_RAW
)
351 buf
= PyOS_double_to_string(v
->ob_fval
,
352 'g', PyFloat_STR_PRECISION
,
353 Py_DTSF_ADD_DOT_0
, NULL
);
355 buf
= PyOS_double_to_string(v
->ob_fval
,
356 'r', 0, Py_DTSF_ADD_DOT_0
, NULL
);
357 Py_BEGIN_ALLOW_THREADS
365 float_str_or_repr(PyFloatObject
*v
, int precision
, char format_code
)
368 char *buf
= PyOS_double_to_string(PyFloat_AS_DOUBLE(v
),
369 format_code
, precision
,
373 return PyErr_NoMemory();
374 result
= PyString_FromString(buf
);
380 float_repr(PyFloatObject
*v
)
382 return float_str_or_repr(v
, 0, 'r');
386 float_str(PyFloatObject
*v
)
388 return float_str_or_repr(v
, PyFloat_STR_PRECISION
, 'g');
391 /* Comparison is pretty much a nightmare. When comparing float to float,
392 * we do it as straightforwardly (and long-windedly) as conceivable, so
393 * that, e.g., Python x == y delivers the same result as the platform
394 * C x == y when x and/or y is a NaN.
395 * When mixing float with an integer type, there's no good *uniform* approach.
396 * Converting the double to an integer obviously doesn't work, since we
397 * may lose info from fractional bits. Converting the integer to a double
398 * also has two failure modes: (1) a long int may trigger overflow (too
399 * large to fit in the dynamic range of a C double); (2) even a C long may have
400 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
401 * 63 bits of precision, but a C double probably has only 53), and then
402 * we can falsely claim equality when low-order integer bits are lost by
403 * coercion to double. So this part is painful too.
407 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
412 assert(PyFloat_Check(v
));
413 i
= PyFloat_AS_DOUBLE(v
);
415 /* Switch on the type of w. Set i and j to doubles to be compared,
416 * and op to the richcomp to use.
418 if (PyFloat_Check(w
))
419 j
= PyFloat_AS_DOUBLE(w
);
421 else if (!Py_IS_FINITE(i
)) {
422 if (PyInt_Check(w
) || PyLong_Check(w
))
423 /* If i is an infinity, its magnitude exceeds any
424 * finite integer, so it doesn't matter which int we
425 * compare i with. If i is a NaN, similarly.
432 else if (PyInt_Check(w
)) {
433 long jj
= PyInt_AS_LONG(w
);
434 /* In the worst realistic case I can imagine, C double is a
435 * Cray single with 48 bits of precision, and long has 64
439 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
441 /* Needs more than 48 bits. Make it take the
445 PyObject
*ww
= PyLong_FromLong(jj
);
449 result
= float_richcompare(v
, ww
, op
);
455 assert((long)j
== jj
);
458 else if (PyLong_Check(w
)) {
459 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
460 int wsign
= _PyLong_Sign(w
);
464 if (vsign
!= wsign
) {
465 /* Magnitudes are irrelevant -- the signs alone
466 * determine the outcome.
472 /* The signs are the same. */
473 /* Convert w to a double if it fits. In particular, 0 fits. */
474 nbits
= _PyLong_NumBits(w
);
475 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
476 /* This long is so large that size_t isn't big enough
477 * to hold the # of bits. Replace with little doubles
478 * that give the same outcome -- w is so large that
479 * its magnitude must exceed the magnitude of any
489 j
= PyLong_AsDouble(w
);
490 /* It's impossible that <= 48 bits overflowed. */
491 assert(j
!= -1.0 || ! PyErr_Occurred());
494 assert(wsign
!= 0); /* else nbits was 0 */
495 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
496 * not 0, we would have taken the
497 * vsign != wsign branch at the start */
498 /* We want to work with non-negative numbers. */
500 /* "Multiply both sides" by -1; this also swaps the
504 op
= _Py_SwappedOp
[op
];
507 (void) frexp(i
, &exponent
);
508 /* exponent is the # of bits in v before the radix point;
509 * we know that nbits (the # of bits in w) > 48 at this point
511 if (exponent
< 0 || (size_t)exponent
< nbits
) {
516 if ((size_t)exponent
> nbits
) {
521 /* v and w have the same number of bits before the radix
522 * point. Construct two longs that have the same comparison
528 PyObject
*result
= NULL
;
529 PyObject
*one
= NULL
;
534 ww
= PyNumber_Negative(w
);
541 fracpart
= modf(i
, &intpart
);
542 vv
= PyLong_FromDouble(intpart
);
546 if (fracpart
!= 0.0) {
547 /* Shift left, and or a 1 bit into vv
548 * to represent the lost fraction.
552 one
= PyInt_FromLong(1);
556 temp
= PyNumber_Lshift(ww
, one
);
562 temp
= PyNumber_Lshift(vv
, one
);
568 temp
= PyNumber_Or(vv
, one
);
575 r
= PyObject_RichCompareBool(vv
, ww
, op
);
578 result
= PyBool_FromLong(r
);
585 } /* else if (PyLong_Check(w)) */
587 else /* w isn't float, int, or long */
591 PyFPE_START_PROTECT("richcompare", return NULL
)
613 return PyBool_FromLong(r
);
616 Py_INCREF(Py_NotImplemented
);
617 return Py_NotImplemented
;
621 float_hash(PyFloatObject
*v
)
623 return _Py_HashDouble(v
->ob_fval
);
627 float_add(PyObject
*v
, PyObject
*w
)
630 CONVERT_TO_DOUBLE(v
, a
);
631 CONVERT_TO_DOUBLE(w
, b
);
632 PyFPE_START_PROTECT("add", return 0)
635 return PyFloat_FromDouble(a
);
639 float_sub(PyObject
*v
, PyObject
*w
)
642 CONVERT_TO_DOUBLE(v
, a
);
643 CONVERT_TO_DOUBLE(w
, b
);
644 PyFPE_START_PROTECT("subtract", return 0)
647 return PyFloat_FromDouble(a
);
651 float_mul(PyObject
*v
, PyObject
*w
)
654 CONVERT_TO_DOUBLE(v
, a
);
655 CONVERT_TO_DOUBLE(w
, b
);
656 PyFPE_START_PROTECT("multiply", return 0)
659 return PyFloat_FromDouble(a
);
663 float_div(PyObject
*v
, PyObject
*w
)
666 CONVERT_TO_DOUBLE(v
, a
);
667 CONVERT_TO_DOUBLE(w
, b
);
670 PyErr_SetString(PyExc_ZeroDivisionError
,
675 PyFPE_START_PROTECT("divide", return 0)
678 return PyFloat_FromDouble(a
);
682 float_classic_div(PyObject
*v
, PyObject
*w
)
685 CONVERT_TO_DOUBLE(v
, a
);
686 CONVERT_TO_DOUBLE(w
, b
);
687 if (Py_DivisionWarningFlag
>= 2 &&
688 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
692 PyErr_SetString(PyExc_ZeroDivisionError
,
697 PyFPE_START_PROTECT("divide", return 0)
700 return PyFloat_FromDouble(a
);
704 float_rem(PyObject
*v
, PyObject
*w
)
708 CONVERT_TO_DOUBLE(v
, vx
);
709 CONVERT_TO_DOUBLE(w
, wx
);
712 PyErr_SetString(PyExc_ZeroDivisionError
,
717 PyFPE_START_PROTECT("modulo", return 0)
719 /* note: checking mod*wx < 0 is incorrect -- underflows to
720 0 if wx < sqrt(smallest nonzero double) */
721 if (mod
&& ((wx
< 0) != (mod
< 0))) {
724 PyFPE_END_PROTECT(mod
)
725 return PyFloat_FromDouble(mod
);
729 float_divmod(PyObject
*v
, PyObject
*w
)
732 double div
, mod
, floordiv
;
733 CONVERT_TO_DOUBLE(v
, vx
);
734 CONVERT_TO_DOUBLE(w
, wx
);
736 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
739 PyFPE_START_PROTECT("divmod", return 0)
741 /* fmod is typically exact, so vx-mod is *mathematically* an
742 exact multiple of wx. But this is fp arithmetic, and fp
743 vx - mod is an approximation; the result is that div may
744 not be an exact integral value after the division, although
745 it will always be very close to one.
747 div
= (vx
- mod
) / wx
;
749 /* ensure the remainder has the same sign as the denominator */
750 if ((wx
< 0) != (mod
< 0)) {
756 /* the remainder is zero, and in the presence of signed zeroes
757 fmod returns different results across platforms; ensure
758 it has the same sign as the denominator; we'd like to do
759 "mod = wx * 0.0", but that may get optimized away */
760 mod
*= mod
; /* hide "mod = +0" from optimizer */
764 /* snap quotient to nearest integral value */
766 floordiv
= floor(div
);
767 if (div
- floordiv
> 0.5)
771 /* div is zero - get the same sign as the true quotient */
772 div
*= div
; /* hide "div = +0" from optimizers */
773 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
775 PyFPE_END_PROTECT(floordiv
)
776 return Py_BuildValue("(dd)", floordiv
, mod
);
780 float_floor_div(PyObject
*v
, PyObject
*w
)
784 t
= float_divmod(v
, w
);
785 if (t
== NULL
|| t
== Py_NotImplemented
)
787 assert(PyTuple_CheckExact(t
));
788 r
= PyTuple_GET_ITEM(t
, 0);
795 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
799 if ((PyObject
*)z
!= Py_None
) {
800 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
801 "allowed unless all arguments are integers");
805 CONVERT_TO_DOUBLE(v
, iv
);
806 CONVERT_TO_DOUBLE(w
, iw
);
808 /* Sort out special cases here instead of relying on pow() */
809 if (iw
== 0) { /* v**0 is 1, even 0**0 */
810 return PyFloat_FromDouble(1.0);
812 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
814 PyErr_SetString(PyExc_ZeroDivisionError
,
815 "0.0 cannot be raised to a negative power");
818 return PyFloat_FromDouble(0.0);
820 if (iv
== 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
821 return PyFloat_FromDouble(1.0);
824 /* Whether this is an error is a mess, and bumps into libm
825 * bugs so we have to figure it out ourselves.
827 if (iw
!= floor(iw
)) {
828 PyErr_SetString(PyExc_ValueError
, "negative number "
829 "cannot be raised to a fractional power");
832 /* iw is an exact integer, albeit perhaps a very large one.
833 * -1 raised to an exact integer should never be exceptional.
834 * Alas, some libms (chiefly glibc as of early 2003) return
835 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
836 * happen to be representable in a *C* integer. That's a
837 * bug; we let that slide in math.pow() (which currently
838 * reflects all platform accidents), but not for Python's **.
840 if (iv
== -1.0 && Py_IS_FINITE(iw
)) {
841 /* Return 1 if iw is even, -1 if iw is odd; there's
842 * no guarantee that any C integral type is big
843 * enough to hold iw, so we have to check this
846 ix
= floor(iw
* 0.5) * 2.0;
847 return PyFloat_FromDouble(ix
== iw
? 1.0 : -1.0);
849 /* Else iv != -1.0, and overflow or underflow are possible.
850 * Unless we're to write pow() ourselves, we have to trust
851 * the platform to do this correctly.
855 PyFPE_START_PROTECT("pow", return NULL
)
857 PyFPE_END_PROTECT(ix
)
858 Py_ADJUST_ERANGE1(ix
);
860 /* We don't expect any errno value other than ERANGE, but
861 * the range of libm bugs appears unbounded.
863 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
867 return PyFloat_FromDouble(ix
);
871 float_neg(PyFloatObject
*v
)
873 return PyFloat_FromDouble(-v
->ob_fval
);
877 float_abs(PyFloatObject
*v
)
879 return PyFloat_FromDouble(fabs(v
->ob_fval
));
883 float_nonzero(PyFloatObject
*v
)
885 return v
->ob_fval
!= 0.0;
889 float_coerce(PyObject
**pv
, PyObject
**pw
)
891 if (PyInt_Check(*pw
)) {
892 long x
= PyInt_AsLong(*pw
);
893 *pw
= PyFloat_FromDouble((double)x
);
897 else if (PyLong_Check(*pw
)) {
898 double x
= PyLong_AsDouble(*pw
);
899 if (x
== -1.0 && PyErr_Occurred())
901 *pw
= PyFloat_FromDouble(x
);
905 else if (PyFloat_Check(*pw
)) {
910 return 1; /* Can't do it */
914 float_is_integer(PyObject
*v
)
916 double x
= PyFloat_AsDouble(v
);
919 if (x
== -1.0 && PyErr_Occurred())
921 if (!Py_IS_FINITE(x
))
924 PyFPE_START_PROTECT("is_integer", return NULL
)
925 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
928 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
938 float_is_inf(PyObject
*v
)
940 double x
= PyFloat_AsDouble(v
);
941 if (x
== -1.0 && PyErr_Occurred())
943 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
947 float_is_nan(PyObject
*v
)
949 double x
= PyFloat_AsDouble(v
);
950 if (x
== -1.0 && PyErr_Occurred())
952 return PyBool_FromLong((long)Py_IS_NAN(x
));
956 float_is_finite(PyObject
*v
)
958 double x
= PyFloat_AsDouble(v
);
959 if (x
== -1.0 && PyErr_Occurred())
961 return PyBool_FromLong((long)Py_IS_FINITE(x
));
966 float_trunc(PyObject
*v
)
968 double x
= PyFloat_AsDouble(v
);
969 double wholepart
; /* integral portion of x, rounded toward 0 */
971 (void)modf(x
, &wholepart
);
972 /* Try to get out cheap if this fits in a Python int. The attempt
973 * to cast to long must be protected, as C doesn't define what
974 * happens if the double is too big to fit in a long. Some rare
975 * systems raise an exception then (RISCOS was mentioned as one,
976 * and someone using a non-default option on Sun also bumped into
977 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
978 * still be vulnerable: if a long has more bits of precision than
979 * a double, casting MIN/MAX to double may yield an approximation,
980 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
981 * yield true from the C expression wholepart<=LONG_MAX, despite
982 * that wholepart is actually greater than LONG_MAX.
984 if (LONG_MIN
< wholepart
&& wholepart
< LONG_MAX
) {
985 const long aslong
= (long)wholepart
;
986 return PyInt_FromLong(aslong
);
988 return PyLong_FromDouble(wholepart
);
992 float_long(PyObject
*v
)
994 double x
= PyFloat_AsDouble(v
);
995 return PyLong_FromDouble(x
);
998 /* _Py_double_round: rounds a finite nonzero double to the closest multiple of
999 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1000 ndigits <= 323). Returns a Python float, or sets a Python error and
1001 returns NULL on failure (OverflowError and memory errors are possible). */
1003 #ifndef PY_NO_SHORT_FLOAT_REPR
1004 /* version of _Py_double_round that uses the correctly-rounded string<->double
1005 conversions from Python/dtoa.c */
1007 /* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1008 a double. Since we're using the code in Python/dtoa.c, it should be safe
1009 to assume that C doubles are IEEE 754 binary64 format. To be on the safe
1010 side, we check this. */
1011 #if DBL_MANT_DIG == 53
1012 #define FIVE_POW_LIMIT 22
1014 #error "C doubles do not appear to be IEEE 754 binary64 format"
1018 _Py_double_round(double x
, int ndigits
) {
1021 Py_ssize_t buflen
, mybuflen
=100;
1022 char *buf
, *buf_end
, shortbuf
[100], *mybuf
=shortbuf
;
1023 int decpt
, sign
, val
, halfway_case
;
1024 PyObject
*result
= NULL
;
1026 /* The basic idea is very simple: convert and round the double to a
1027 decimal string using _Py_dg_dtoa, then convert that decimal string
1028 back to a double with _Py_dg_strtod. There's one minor difficulty:
1029 Python 2.x expects round to do round-half-away-from-zero, while
1030 _Py_dg_dtoa does round-half-to-even. So we need some way to detect
1031 and correct the halfway cases.
1033 Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1034 some odd integer k. Or in other words, a rational number x is
1035 exactly halfway between two multiples of 10**-ndigits if its
1036 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1037 -ndigits. For ndigits >= 0 the latter condition is automatically
1038 satisfied for a binary float x, since any such float has
1039 nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
1040 integral multiple of 5**-ndigits; we can check this using fmod.
1041 For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1042 to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1043 23 takes at least 54 bits of precision to represent exactly.
1045 Correction: a simple strategy for dealing with halfway cases is to
1046 (for the halfway cases only) call _Py_dg_dtoa with an argument of
1047 ndigits+1 instead of ndigits (thus doing an exact conversion to
1048 decimal), round the resulting string manually, and then convert
1049 back using _Py_dg_strtod.
1052 /* nans, infinities and zeros should have already been dealt
1053 with by the caller (in this case, builtin_round) */
1054 assert(Py_IS_FINITE(x
) && x
!= 0.0);
1056 /* find 2-valuation val of x */
1058 while (m
!= floor(m
)) {
1063 /* determine whether this is a halfway case */
1064 if (val
== -ndigits
-1) {
1067 else if (ndigits
>= -FIVE_POW_LIMIT
) {
1068 double five_pow
= 1.0;
1070 for (i
=0; i
< -ndigits
; i
++)
1072 halfway_case
= fmod(x
, five_pow
) == 0.0;
1080 /* round to a decimal string; use an extra place for halfway case */
1081 buf
= _Py_dg_dtoa(x
, 3, ndigits
+halfway_case
, &decpt
, &sign
, &buf_end
);
1086 buflen
= buf_end
- buf
;
1088 /* in halfway case, do the round-half-away-from-zero manually */
1091 /* sanity check: _Py_dg_dtoa should not have stripped
1092 any zeros from the result: there should be exactly
1093 ndigits+1 places following the decimal point, and
1094 the last digit in the buffer should be a '5'.*/
1095 assert(buflen
- decpt
== ndigits
+1);
1096 assert(buf
[buflen
-1] == '5');
1098 /* increment and shift right at the same time. */
1101 for (i
=buflen
-1; i
-- > 0;) {
1102 carry
+= buf
[i
] - '0';
1103 buf
[i
+1] = carry
% 10 + '0';
1106 buf
[0] = carry
+ '0';
1109 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
1110 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1111 if (buflen
+ 8 > mybuflen
) {
1112 mybuflen
= buflen
+8;
1113 mybuf
= (char *)PyMem_Malloc(mybuflen
);
1114 if (mybuf
== NULL
) {
1119 /* copy buf to mybuf, adding exponent, sign and leading 0 */
1120 PyOS_snprintf(mybuf
, mybuflen
, "%s0%se%d", (sign
? "-" : ""),
1121 buf
, decpt
- (int)buflen
);
1123 /* and convert the resulting string back to a double */
1125 rounded
= _Py_dg_strtod(mybuf
, NULL
);
1126 if (errno
== ERANGE
&& fabs(rounded
) >= 1.)
1127 PyErr_SetString(PyExc_OverflowError
,
1128 "rounded value too large to represent");
1130 result
= PyFloat_FromDouble(rounded
);
1132 /* done computing value; now clean up */
1133 if (mybuf
!= shortbuf
)
1136 _Py_dg_freedtoa(buf
);
1140 #undef FIVE_POW_LIMIT
1142 #else /* PY_NO_SHORT_FLOAT_REPR */
1144 /* fallback version, to be used when correctly rounded binary<->decimal
1145 conversions aren't available */
1148 _Py_double_round(double x
, int ndigits
) {
1149 double pow1
, pow2
, y
, z
;
1152 /* pow1 and pow2 are each safe from overflow, but
1153 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1154 pow1
= pow(10.0, (double)(ndigits
-22));
1158 pow1
= pow(10.0, (double)ndigits
);
1162 /* if y overflows, then rounded value is exactly x */
1163 if (!Py_IS_FINITE(y
))
1164 return PyFloat_FromDouble(x
);
1167 pow1
= pow(10.0, (double)-ndigits
);
1168 pow2
= 1.0; /* unused; silences a gcc compiler warning */
1173 if (fabs(y
-z
) == 0.5)
1174 /* halfway between two integers; use round-away-from-zero */
1175 z
= y
+ copysign(0.5, y
);
1178 z
= (z
/ pow2
) / pow1
;
1182 /* if computation resulted in overflow, raise OverflowError */
1183 if (!Py_IS_FINITE(z
)) {
1184 PyErr_SetString(PyExc_OverflowError
,
1185 "overflow occurred during round");
1189 return PyFloat_FromDouble(z
);
1192 #endif /* PY_NO_SHORT_FLOAT_REPR */
1195 float_float(PyObject
*v
)
1197 if (PyFloat_CheckExact(v
))
1200 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1204 /* turn ASCII hex characters into integer values and vice versa */
1207 char_from_hex(int x
)
1209 assert(0 <= x
&& x
< 16);
1210 return "0123456789abcdef"[x
];
1214 hex_from_char(char c
) {
1278 /* convert a float to a hexadecimal string */
1280 /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1281 of the form 4k+1. */
1282 #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1285 float_hex(PyObject
*v
)
1288 int e
, shift
, i
, si
, esign
;
1289 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1290 trailing NUL byte. */
1291 char s
[(TOHEX_NBITS
-1)/4+3];
1293 CONVERT_TO_DOUBLE(v
, x
);
1295 if (Py_IS_NAN(x
) || Py_IS_INFINITY(x
))
1296 return float_str((PyFloatObject
*)v
);
1299 if(copysign(1.0, x
) == -1.0)
1300 return PyString_FromString("-0x0.0p+0");
1302 return PyString_FromString("0x0.0p+0");
1305 m
= frexp(fabs(x
), &e
);
1306 shift
= 1 - MAX(DBL_MIN_EXP
- e
, 0);
1307 m
= ldexp(m
, shift
);
1311 s
[si
] = char_from_hex((int)m
);
1316 for (i
=0; i
< (TOHEX_NBITS
-1)/4; i
++) {
1318 s
[si
] = char_from_hex((int)m
);
1332 return PyString_FromFormat("-0x%sp%c%d", s
, esign
, e
);
1334 return PyString_FromFormat("0x%sp%c%d", s
, esign
, e
);
1337 PyDoc_STRVAR(float_hex_doc
,
1338 "float.hex() -> string\n\
1340 Return a hexadecimal representation of a floating-point number.\n\
1342 '-0x1.999999999999ap-4'\n\
1343 >>> 3.14159.hex()\n\
1344 '0x1.921f9f01b866ep+1'");
1346 /* Case-insensitive locale-independent string match used for nan and inf
1347 detection. t should be lower-case and null-terminated. Return a nonzero
1348 result if the first strlen(t) characters of s match t and 0 otherwise. */
1351 case_insensitive_match(const char *s
, const char *t
)
1353 while(*t
&& Py_TOLOWER(*s
) == *t
) {
1360 /* Convert a hexadecimal string to a float. */
1363 float_fromhex(PyObject
*cls
, PyObject
*arg
)
1365 PyObject
*result_as_float
, *result
;
1367 long exp
, top_exp
, lsb
, key_digit
;
1368 char *s
, *coeff_start
, *s_store
, *coeff_end
, *exp_start
, *s_end
;
1369 int half_eps
, digit
, round_up
, sign
=1;
1370 Py_ssize_t length
, ndigits
, fdigits
, i
;
1373 * For the sake of simplicity and correctness, we impose an artificial
1374 * limit on ndigits, the total number of hex digits in the coefficient
1375 * The limit is chosen to ensure that, writing exp for the exponent,
1377 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1378 * guaranteed to overflow (provided it's nonzero)
1380 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1381 * guaranteed to underflow to 0.
1383 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1384 * overflow in the calculation of exp and top_exp below.
1386 * More specifically, ndigits is assumed to satisfy the following
1389 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1390 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1392 * If either of these inequalities is not satisfied, a ValueError is
1393 * raised. Otherwise, write x for the value of the hex string, and
1394 * assume x is nonzero. Then
1396 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1398 * Now if exp > LONG_MAX/2 then:
1400 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1403 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1404 * double, so overflows. If exp < LONG_MIN/2, then
1406 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1407 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1408 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1410 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1411 * when converted to a C double.
1413 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1414 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1417 if (PyString_AsStringAndSize(arg
, &s
, &length
))
1421 /********************
1422 * Parse the string *
1423 ********************/
1425 /* leading whitespace and optional sign */
1426 while (Py_ISSPACE(*s
))
1435 /* infinities and nans */
1436 if (*s
== 'i' || *s
== 'I') {
1437 if (!case_insensitive_match(s
+1, "nf"))
1441 if (case_insensitive_match(s
, "inity"))
1445 if (*s
== 'n' || *s
== 'N') {
1446 if (!case_insensitive_match(s
+1, "an"))
1457 if (*s
== 'x' || *s
== 'X')
1463 /* coefficient: <integer> [. <fraction>] */
1465 while (hex_from_char(*s
) >= 0)
1470 while (hex_from_char(*s
) >= 0)
1477 /* ndigits = total # of hex digits; fdigits = # after point */
1478 ndigits
= coeff_end
- coeff_start
;
1479 fdigits
= coeff_end
- s_store
;
1482 if (ndigits
> MIN(DBL_MIN_EXP
- DBL_MANT_DIG
- LONG_MIN
/2,
1483 LONG_MAX
/2 + 1 - DBL_MAX_EXP
)/4)
1484 goto insane_length_error
;
1486 /* [p <exponent>] */
1487 if (*s
== 'p' || *s
== 'P') {
1490 if (*s
== '-' || *s
== '+')
1492 if (!('0' <= *s
&& *s
<= '9'))
1495 while ('0' <= *s
&& *s
<= '9')
1497 exp
= strtol(exp_start
, NULL
, 10);
1502 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1503 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1507 /*******************************************
1508 * Compute rounded value of the hex string *
1509 *******************************************/
1511 /* Discard leading zeros, and catch extreme overflow and underflow */
1512 while (ndigits
> 0 && HEX_DIGIT(ndigits
-1) == 0)
1514 if (ndigits
== 0 || exp
< LONG_MIN
/2) {
1518 if (exp
> LONG_MAX
/2)
1519 goto overflow_error
;
1521 /* Adjust exponent for fractional part. */
1522 exp
= exp
- 4*((long)fdigits
);
1524 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1525 top_exp
= exp
+ 4*((long)ndigits
- 1);
1526 for (digit
= HEX_DIGIT(ndigits
-1); digit
!= 0; digit
/= 2)
1529 /* catch almost all nonextreme cases of overflow and underflow here */
1530 if (top_exp
< DBL_MIN_EXP
- DBL_MANT_DIG
) {
1534 if (top_exp
> DBL_MAX_EXP
)
1535 goto overflow_error
;
1537 /* lsb = exponent of least significant bit of the *rounded* value.
1538 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1539 lsb
= MAX(top_exp
, (long)DBL_MIN_EXP
) - DBL_MANT_DIG
;
1543 /* no rounding required */
1544 for (i
= ndigits
-1; i
>= 0; i
--)
1545 x
= 16.0*x
+ HEX_DIGIT(i
);
1546 x
= ldexp(x
, (int)(exp
));
1549 /* rounding required. key_digit is the index of the hex digit
1550 containing the first bit to be rounded away. */
1551 half_eps
= 1 << (int)((lsb
- exp
- 1) % 4);
1552 key_digit
= (lsb
- exp
- 1) / 4;
1553 for (i
= ndigits
-1; i
> key_digit
; i
--)
1554 x
= 16.0*x
+ HEX_DIGIT(i
);
1555 digit
= HEX_DIGIT(key_digit
);
1556 x
= 16.0*x
+ (double)(digit
& (16-2*half_eps
));
1558 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1559 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1560 if ((digit
& half_eps
) != 0) {
1562 if ((digit
& (3*half_eps
-1)) != 0 ||
1563 (half_eps
== 8 && (HEX_DIGIT(key_digit
+1) & 1) != 0))
1566 for (i
= key_digit
-1; i
>= 0; i
--)
1567 if (HEX_DIGIT(i
) != 0) {
1571 if (round_up
== 1) {
1573 if (top_exp
== DBL_MAX_EXP
&&
1574 x
== ldexp((double)(2*half_eps
), DBL_MANT_DIG
))
1575 /* overflow corner case: pre-rounded value <
1576 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1577 goto overflow_error
;
1580 x
= ldexp(x
, (int)(exp
+4*key_digit
));
1583 /* optional trailing whitespace leading to the end of the string */
1584 while (Py_ISSPACE(*s
))
1588 result_as_float
= Py_BuildValue("(d)", sign
* x
);
1589 if (result_as_float
== NULL
)
1591 result
= PyObject_CallObject(cls
, result_as_float
);
1592 Py_DECREF(result_as_float
);
1596 PyErr_SetString(PyExc_OverflowError
,
1597 "hexadecimal value too large to represent as a float");
1601 PyErr_SetString(PyExc_ValueError
,
1602 "invalid hexadecimal floating-point string");
1605 insane_length_error
:
1606 PyErr_SetString(PyExc_ValueError
,
1607 "hexadecimal string too long to convert");
1611 PyDoc_STRVAR(float_fromhex_doc
,
1612 "float.fromhex(string) -> float\n\
1614 Create a floating-point number from a hexadecimal string.\n\
1615 >>> float.fromhex('0x1.ffffp10')\n\
1617 >>> float.fromhex('-0x1p-1074')\n\
1618 -4.9406564584124654e-324");
1622 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
1630 PyObject
*py_exponent
= NULL
;
1631 PyObject
*numerator
= NULL
;
1632 PyObject
*denominator
= NULL
;
1633 PyObject
*result_pair
= NULL
;
1634 PyNumberMethods
*long_methods
= PyLong_Type
.tp_as_number
;
1636 #define INPLACE_UPDATE(obj, call) \
1641 CONVERT_TO_DOUBLE(v, self);
1643 if (Py_IS_INFINITY(self
)) {
1644 PyErr_SetString(PyExc_OverflowError
,
1645 "Cannot pass infinity to float.as_integer_ratio.");
1649 if (Py_IS_NAN(self
)) {
1650 PyErr_SetString(PyExc_ValueError
,
1651 "Cannot pass NaN to float.as_integer_ratio.");
1656 PyFPE_START_PROTECT("as_integer_ratio", goto error
);
1657 float_part
= frexp(self
, &exponent
); /* self == float_part * 2**exponent exactly */
1658 PyFPE_END_PROTECT(float_part
);
1660 for (i
=0; i
<300 && float_part
!= floor(float_part
) ; i
++) {
1664 /* self == float_part * 2**exponent exactly and float_part is integral.
1665 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1666 to be truncated by PyLong_FromDouble(). */
1668 numerator
= PyLong_FromDouble(float_part
);
1669 if (numerator
== NULL
) goto error
;
1671 /* fold in 2**exponent */
1672 denominator
= PyLong_FromLong(1);
1673 py_exponent
= PyLong_FromLong(labs((long)exponent
));
1674 if (py_exponent
== NULL
) goto error
;
1675 INPLACE_UPDATE(py_exponent
,
1676 long_methods
->nb_lshift(denominator
, py_exponent
));
1677 if (py_exponent
== NULL
) goto error
;
1679 INPLACE_UPDATE(numerator
,
1680 long_methods
->nb_multiply(numerator
, py_exponent
));
1681 if (numerator
== NULL
) goto error
;
1684 Py_DECREF(denominator
);
1685 denominator
= py_exponent
;
1689 /* Returns ints instead of longs where possible */
1690 INPLACE_UPDATE(numerator
, PyNumber_Int(numerator
));
1691 if (numerator
== NULL
) goto error
;
1692 INPLACE_UPDATE(denominator
, PyNumber_Int(denominator
));
1693 if (denominator
== NULL
) goto error
;
1695 result_pair
= PyTuple_Pack(2, numerator
, denominator
);
1697 #undef INPLACE_UPDATE
1699 Py_XDECREF(py_exponent
);
1700 Py_XDECREF(denominator
);
1701 Py_XDECREF(numerator
);
1705 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1706 "float.as_integer_ratio() -> (int, int)\n"
1708 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
1709 "float and with a positive denominator.\n"
1710 "Raises OverflowError on infinities and a ValueError on NaNs.\n"
1712 ">>> (10.0).as_integer_ratio()\n"
1714 ">>> (0.0).as_integer_ratio()\n"
1716 ">>> (-.25).as_integer_ratio()\n"
1721 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
1724 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1726 PyObject
*x
= Py_False
; /* Integer zero */
1727 static char *kwlist
[] = {"x", 0};
1729 if (type
!= &PyFloat_Type
)
1730 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
1731 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
1733 /* If it's a string, but not a string subclass, use
1734 PyFloat_FromString. */
1735 if (PyString_CheckExact(x
))
1736 return PyFloat_FromString(x
, NULL
);
1737 return PyNumber_Float(x
);
1740 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1741 first create a regular float from whatever arguments we got,
1742 then allocate a subtype instance and initialize its ob_fval
1743 from the regular float. The regular float is then thrown away.
1746 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1748 PyObject
*tmp
, *newobj
;
1750 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
1751 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
1754 assert(PyFloat_CheckExact(tmp
));
1755 newobj
= type
->tp_alloc(type
, 0);
1756 if (newobj
== NULL
) {
1760 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
1766 float_getnewargs(PyFloatObject
*v
)
1768 return Py_BuildValue("(d)", v
->ob_fval
);
1771 /* this is for the benefit of the pack/unpack routines below */
1774 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
1775 } float_format_type
;
1777 static float_format_type double_format
, float_format
;
1778 static float_format_type detected_double_format
, detected_float_format
;
1781 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1784 float_format_type r
;
1786 if (!PyString_Check(arg
)) {
1787 PyErr_Format(PyExc_TypeError
,
1788 "__getformat__() argument must be string, not %.500s",
1789 Py_TYPE(arg
)->tp_name
);
1792 s
= PyString_AS_STRING(arg
);
1793 if (strcmp(s
, "double") == 0) {
1796 else if (strcmp(s
, "float") == 0) {
1800 PyErr_SetString(PyExc_ValueError
,
1801 "__getformat__() argument 1 must be "
1802 "'double' or 'float'");
1807 case unknown_format
:
1808 return PyString_FromString("unknown");
1809 case ieee_little_endian_format
:
1810 return PyString_FromString("IEEE, little-endian");
1811 case ieee_big_endian_format
:
1812 return PyString_FromString("IEEE, big-endian");
1814 Py_FatalError("insane float_format or double_format");
1819 PyDoc_STRVAR(float_getformat_doc
,
1820 "float.__getformat__(typestr) -> string\n"
1822 "You probably don't want to use this function. It exists mainly to be\n"
1823 "used in Python's test suite.\n"
1825 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1826 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1827 "format of floating point numbers used by the C type named by typestr.");
1830 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1834 float_format_type f
;
1835 float_format_type detected
;
1836 float_format_type
*p
;
1838 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1841 if (strcmp(typestr
, "double") == 0) {
1843 detected
= detected_double_format
;
1845 else if (strcmp(typestr
, "float") == 0) {
1847 detected
= detected_float_format
;
1850 PyErr_SetString(PyExc_ValueError
,
1851 "__setformat__() argument 1 must "
1852 "be 'double' or 'float'");
1856 if (strcmp(format
, "unknown") == 0) {
1859 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1860 f
= ieee_little_endian_format
;
1862 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1863 f
= ieee_big_endian_format
;
1866 PyErr_SetString(PyExc_ValueError
,
1867 "__setformat__() argument 2 must be "
1868 "'unknown', 'IEEE, little-endian' or "
1869 "'IEEE, big-endian'");
1874 if (f
!= unknown_format
&& f
!= detected
) {
1875 PyErr_Format(PyExc_ValueError
,
1876 "can only set %s format to 'unknown' or the "
1877 "detected platform value", typestr
);
1885 PyDoc_STRVAR(float_setformat_doc
,
1886 "float.__setformat__(typestr, fmt) -> None\n"
1888 "You probably don't want to use this function. It exists mainly to be\n"
1889 "used in Python's test suite.\n"
1891 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1892 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1893 "one of the latter two if it appears to match the underlying C reality.\n"
1895 "Overrides the automatic determination of C-level floating point type.\n"
1896 "This affects how floats are converted to and from binary strings.");
1899 float_getzero(PyObject
*v
, void *closure
)
1901 return PyFloat_FromDouble(0.0);
1905 float__format__(PyObject
*self
, PyObject
*args
)
1907 PyObject
*format_spec
;
1909 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1911 if (PyBytes_Check(format_spec
))
1912 return _PyFloat_FormatAdvanced(self
,
1913 PyBytes_AS_STRING(format_spec
),
1914 PyBytes_GET_SIZE(format_spec
));
1915 if (PyUnicode_Check(format_spec
)) {
1916 /* Convert format_spec to a str */
1918 PyObject
*str_spec
= PyObject_Str(format_spec
);
1920 if (str_spec
== NULL
)
1923 result
= _PyFloat_FormatAdvanced(self
,
1924 PyBytes_AS_STRING(str_spec
),
1925 PyBytes_GET_SIZE(str_spec
));
1927 Py_DECREF(str_spec
);
1930 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1934 PyDoc_STRVAR(float__format__doc
,
1935 "float.__format__(format_spec) -> string\n"
1937 "Formats the float according to format_spec.");
1940 static PyMethodDef float_methods
[] = {
1941 {"conjugate", (PyCFunction
)float_float
, METH_NOARGS
,
1942 "Returns self, the complex conjugate of any float."},
1943 {"__trunc__", (PyCFunction
)float_trunc
, METH_NOARGS
,
1944 "Returns the Integral closest to x between 0 and x."},
1945 {"as_integer_ratio", (PyCFunction
)float_as_integer_ratio
, METH_NOARGS
,
1946 float_as_integer_ratio_doc
},
1947 {"fromhex", (PyCFunction
)float_fromhex
,
1948 METH_O
|METH_CLASS
, float_fromhex_doc
},
1949 {"hex", (PyCFunction
)float_hex
,
1950 METH_NOARGS
, float_hex_doc
},
1951 {"is_integer", (PyCFunction
)float_is_integer
, METH_NOARGS
,
1952 "Returns True if the float is an integer."},
1954 {"is_inf", (PyCFunction
)float_is_inf
, METH_NOARGS
,
1955 "Returns True if the float is positive or negative infinite."},
1956 {"is_finite", (PyCFunction
)float_is_finite
, METH_NOARGS
,
1957 "Returns True if the float is finite, neither infinite nor NaN."},
1958 {"is_nan", (PyCFunction
)float_is_nan
, METH_NOARGS
,
1959 "Returns True if the float is not a number (NaN)."},
1961 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
1962 {"__getformat__", (PyCFunction
)float_getformat
,
1963 METH_O
|METH_CLASS
, float_getformat_doc
},
1964 {"__setformat__", (PyCFunction
)float_setformat
,
1965 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
1966 {"__format__", (PyCFunction
)float__format__
,
1967 METH_VARARGS
, float__format__doc
},
1968 {NULL
, NULL
} /* sentinel */
1971 static PyGetSetDef float_getset
[] = {
1973 (getter
)float_float
, (setter
)NULL
,
1974 "the real part of a complex number",
1977 (getter
)float_getzero
, (setter
)NULL
,
1978 "the imaginary part of a complex number",
1980 {NULL
} /* Sentinel */
1983 PyDoc_STRVAR(float_doc
,
1984 "float(x) -> floating point number\n\
1986 Convert a string or number to a floating point number, if possible.");
1989 static PyNumberMethods float_as_number
= {
1990 float_add
, /*nb_add*/
1991 float_sub
, /*nb_subtract*/
1992 float_mul
, /*nb_multiply*/
1993 float_classic_div
, /*nb_divide*/
1994 float_rem
, /*nb_remainder*/
1995 float_divmod
, /*nb_divmod*/
1996 float_pow
, /*nb_power*/
1997 (unaryfunc
)float_neg
, /*nb_negative*/
1998 (unaryfunc
)float_float
, /*nb_positive*/
1999 (unaryfunc
)float_abs
, /*nb_absolute*/
2000 (inquiry
)float_nonzero
, /*nb_nonzero*/
2007 float_coerce
, /*nb_coerce*/
2008 float_trunc
, /*nb_int*/
2009 float_long
, /*nb_long*/
2010 float_float
, /*nb_float*/
2013 0, /* nb_inplace_add */
2014 0, /* nb_inplace_subtract */
2015 0, /* nb_inplace_multiply */
2016 0, /* nb_inplace_divide */
2017 0, /* nb_inplace_remainder */
2018 0, /* nb_inplace_power */
2019 0, /* nb_inplace_lshift */
2020 0, /* nb_inplace_rshift */
2021 0, /* nb_inplace_and */
2022 0, /* nb_inplace_xor */
2023 0, /* nb_inplace_or */
2024 float_floor_div
, /* nb_floor_divide */
2025 float_div
, /* nb_true_divide */
2026 0, /* nb_inplace_floor_divide */
2027 0, /* nb_inplace_true_divide */
2030 PyTypeObject PyFloat_Type
= {
2031 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2033 sizeof(PyFloatObject
),
2035 (destructor
)float_dealloc
, /* tp_dealloc */
2036 (printfunc
)float_print
, /* tp_print */
2040 (reprfunc
)float_repr
, /* tp_repr */
2041 &float_as_number
, /* tp_as_number */
2042 0, /* tp_as_sequence */
2043 0, /* tp_as_mapping */
2044 (hashfunc
)float_hash
, /* tp_hash */
2046 (reprfunc
)float_str
, /* tp_str */
2047 PyObject_GenericGetAttr
, /* tp_getattro */
2048 0, /* tp_setattro */
2049 0, /* tp_as_buffer */
2050 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2051 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2052 float_doc
, /* tp_doc */
2053 0, /* tp_traverse */
2055 float_richcompare
, /* tp_richcompare */
2056 0, /* tp_weaklistoffset */
2058 0, /* tp_iternext */
2059 float_methods
, /* tp_methods */
2061 float_getset
, /* tp_getset */
2064 0, /* tp_descr_get */
2065 0, /* tp_descr_set */
2066 0, /* tp_dictoffset */
2069 float_new
, /* tp_new */
2075 /* We attempt to determine if this machine is using IEEE
2076 floating point formats by peering at the bits of some
2077 carefully chosen values. If it looks like we are on an
2078 IEEE platform, the float packing/unpacking routines can
2079 just copy bits, if not they resort to arithmetic & shifts
2080 and masks. The shifts & masks approach works on all finite
2081 values, but what happens to infinities, NaNs and signed
2082 zeroes on packing is an accident, and attempting to unpack
2083 a NaN or an infinity will raise an exception.
2085 Note that if we're on some whacked-out platform which uses
2086 IEEE formats but isn't strictly little-endian or big-
2087 endian, we will fall back to the portable shifts & masks
2090 #if SIZEOF_DOUBLE == 8
2092 double x
= 9006104071832581.0;
2093 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2094 detected_double_format
= ieee_big_endian_format
;
2095 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2096 detected_double_format
= ieee_little_endian_format
;
2098 detected_double_format
= unknown_format
;
2101 detected_double_format
= unknown_format
;
2104 #if SIZEOF_FLOAT == 4
2106 float y
= 16711938.0;
2107 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
2108 detected_float_format
= ieee_big_endian_format
;
2109 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
2110 detected_float_format
= ieee_little_endian_format
;
2112 detected_float_format
= unknown_format
;
2115 detected_float_format
= unknown_format
;
2118 double_format
= detected_double_format
;
2119 float_format
= detected_float_format
;
2121 /* Init float info */
2122 if (FloatInfoType
.tp_name
== 0)
2123 PyStructSequence_InitType(&FloatInfoType
, &floatinfo_desc
);
2127 PyFloat_ClearFreeList(void)
2130 PyFloatBlock
*list
, *next
;
2132 int u
; /* remaining unfreed ints per block */
2133 int freelist_size
= 0;
2138 while (list
!= NULL
) {
2140 for (i
= 0, p
= &list
->objects
[0];
2143 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
2148 list
->next
= block_list
;
2150 for (i
= 0, p
= &list
->objects
[0];
2153 if (!PyFloat_CheckExact(p
) ||
2154 Py_REFCNT(p
) == 0) {
2155 Py_TYPE(p
) = (struct _typeobject
*)
2167 return freelist_size
;
2176 int u
; /* total unfreed floats per block */
2178 u
= PyFloat_ClearFreeList();
2180 if (!Py_VerboseFlag
)
2182 fprintf(stderr
, "# cleanup floats");
2184 fprintf(stderr
, "\n");
2188 ": %d unfreed float%s\n",
2189 u
, u
== 1 ? "" : "s");
2191 if (Py_VerboseFlag
> 1) {
2193 while (list
!= NULL
) {
2194 for (i
= 0, p
= &list
->objects
[0];
2197 if (PyFloat_CheckExact(p
) &&
2198 Py_REFCNT(p
) != 0) {
2199 char *buf
= PyOS_double_to_string(
2200 PyFloat_AS_DOUBLE(p
), 'r',
2203 /* XXX(twouters) cast
2210 "# <float at %p, refcnt=%ld, val=%s>\n",
2211 p
, (long)Py_REFCNT(p
), buf
);
2221 /*----------------------------------------------------------------------------
2222 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
2225 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
2227 if (float_format
== unknown_format
) {
2248 /* Normalize f to be in the range [1.0, 2.0) */
2249 if (0.5 <= f
&& f
< 1.0) {
2256 PyErr_SetString(PyExc_SystemError
,
2257 "frexp() result out of range");
2263 else if (e
< -126) {
2264 /* Gradual underflow */
2265 f
= ldexp(f
, 126 + e
);
2268 else if (!(e
== 0 && f
== 0.0)) {
2270 f
-= 1.0; /* Get rid of leading 1 */
2273 f
*= 8388608.0; /* 2**23 */
2274 fbits
= (unsigned int)(f
+ 0.5); /* Round */
2275 assert(fbits
<= 8388608);
2277 /* The carry propagated out of a string of 23 1 bits. */
2285 *p
= (sign
<< 7) | (e
>> 1);
2289 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
2293 *p
= (fbits
>> 8) & 0xFF;
2305 const char *s
= (char*)&y
;
2308 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
2311 if ((float_format
== ieee_little_endian_format
&& !le
)
2312 || (float_format
== ieee_big_endian_format
&& le
)) {
2317 for (i
= 0; i
< 4; i
++) {
2324 PyErr_SetString(PyExc_OverflowError
,
2325 "float too large to pack with f format");
2330 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
2332 if (double_format
== unknown_format
) {
2336 unsigned int fhi
, flo
;
2353 /* Normalize f to be in the range [1.0, 2.0) */
2354 if (0.5 <= f
&& f
< 1.0) {
2361 PyErr_SetString(PyExc_SystemError
,
2362 "frexp() result out of range");
2368 else if (e
< -1022) {
2369 /* Gradual underflow */
2370 f
= ldexp(f
, 1022 + e
);
2373 else if (!(e
== 0 && f
== 0.0)) {
2375 f
-= 1.0; /* Get rid of leading 1 */
2378 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2379 f
*= 268435456.0; /* 2**28 */
2380 fhi
= (unsigned int)f
; /* Truncate */
2381 assert(fhi
< 268435456);
2384 f
*= 16777216.0; /* 2**24 */
2385 flo
= (unsigned int)(f
+ 0.5); /* Round */
2386 assert(flo
<= 16777216);
2388 /* The carry propagated out of a string of 24 1 bits. */
2392 /* And it also progagated out of the next 28 bits. */
2401 *p
= (sign
<< 7) | (e
>> 4);
2405 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
2409 *p
= (fhi
>> 16) & 0xFF;
2413 *p
= (fhi
>> 8) & 0xFF;
2421 *p
= (flo
>> 16) & 0xFF;
2425 *p
= (flo
>> 8) & 0xFF;
2436 PyErr_SetString(PyExc_OverflowError
,
2437 "float too large to pack with d format");
2441 const char *s
= (char*)&x
;
2444 if ((double_format
== ieee_little_endian_format
&& !le
)
2445 || (double_format
== ieee_big_endian_format
&& le
)) {
2450 for (i
= 0; i
< 8; i
++) {
2459 _PyFloat_Unpack4(const unsigned char *p
, int le
)
2461 if (float_format
== unknown_format
) {
2474 sign
= (*p
>> 7) & 1;
2475 e
= (*p
& 0x7F) << 1;
2480 f
= (*p
& 0x7F) << 16;
2486 "can't unpack IEEE 754 special value "
2487 "on non-IEEE platform");
2498 x
= (double)f
/ 8388608.0;
2500 /* XXX This sadly ignores Inf/NaN issues */
2517 if ((float_format
== ieee_little_endian_format
&& !le
)
2518 || (float_format
== ieee_big_endian_format
&& le
)) {
2523 for (i
= 0; i
< 4; i
++) {
2537 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2539 if (double_format
== unknown_format
) {
2542 unsigned int fhi
, flo
;
2552 sign
= (*p
>> 7) & 1;
2553 e
= (*p
& 0x7F) << 4;
2558 e
|= (*p
>> 4) & 0xF;
2559 fhi
= (*p
& 0xF) << 24;
2565 "can't unpack IEEE 754 special value "
2566 "on non-IEEE platform");
2593 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2594 x
/= 268435456.0; /* 2**28 */
2612 if ((double_format
== ieee_little_endian_format
&& !le
)
2613 || (double_format
== ieee_big_endian_format
&& le
)) {
2618 for (i
= 0; i
< 8; i
++) {