2 /* Float object implementation */
4 /* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
15 #define MAX(x, y) ((x) < (y) ? (y) : (x))
16 #define MIN(x, y) ((x) < (y) ? (x) : (y))
23 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24 extern int finite(double);
27 /* Special free list -- see comments for same code in intobject.c. */
28 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
29 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
30 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
33 struct _floatblock
*next
;
34 PyFloatObject objects
[N_FLOATOBJECTS
];
37 typedef struct _floatblock PyFloatBlock
;
39 static PyFloatBlock
*block_list
= NULL
;
40 static PyFloatObject
*free_list
= NULL
;
42 static PyFloatObject
*
46 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
49 return (PyFloatObject
*) PyErr_NoMemory();
50 ((PyFloatBlock
*)p
)->next
= block_list
;
51 block_list
= (PyFloatBlock
*)p
;
52 p
= &((PyFloatBlock
*)p
)->objects
[0];
53 q
= p
+ N_FLOATOBJECTS
;
55 Py_TYPE(q
) = (struct _typeobject
*)(q
-1);
57 return p
+ N_FLOATOBJECTS
- 1;
72 static PyTypeObject FloatInfoType
= {0, 0, 0, 0, 0, 0};
74 PyDoc_STRVAR(floatinfo__doc__
,
77 A structseq holding information about the float type. It contains low level\n\
78 information about the precision and internal representation. Please study\n\
79 your system's :file:`float.h` for more information.");
81 static PyStructSequence_Field floatinfo_fields
[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
101 static PyStructSequence_Desc floatinfo_desc
= {
102 "sys.floatinfo", /* name */
103 floatinfo__doc__
, /* doc */
104 floatinfo_fields
, /* fields */
109 PyFloat_GetInfo(void)
114 floatinfo
= PyStructSequence_New(&FloatInfoType
);
115 if (floatinfo
== NULL
) {
119 #define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121 #define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
125 SetIntFlag(DBL_MAX_EXP
);
126 SetIntFlag(DBL_MAX_10_EXP
);
128 SetIntFlag(DBL_MIN_EXP
);
129 SetIntFlag(DBL_MIN_10_EXP
);
131 SetIntFlag(DBL_MANT_DIG
);
132 SetDblFlag(DBL_EPSILON
);
133 SetIntFlag(FLT_RADIX
);
134 SetIntFlag(FLT_ROUNDS
);
138 if (PyErr_Occurred()) {
146 PyFloat_FromDouble(double fval
)
148 register PyFloatObject
*op
;
149 if (free_list
== NULL
) {
150 if ((free_list
= fill_free_list()) == NULL
)
153 /* Inline PyObject_New */
155 free_list
= (PyFloatObject
*)Py_TYPE(op
);
156 PyObject_INIT(op
, &PyFloat_Type
);
158 return (PyObject
*) op
;
161 /**************************************************************************
162 RED_FLAG 22-Sep-2000 tim
163 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
165 1. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
169 2. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
173 Since we can't change the interface of a public API function, pend is
174 still supported but now *officially* useless: if pend is not NULL,
175 *pend is set to NULL.
176 **************************************************************************/
178 PyFloat_FromString(PyObject
*v
, char **pend
)
180 const char *s
, *last
, *end
, *sp
;
182 char buffer
[256]; /* for errors */
183 #ifdef Py_USING_UNICODE
184 char s_buffer
[256]; /* for objects convertible to a char buffer */
190 if (PyString_Check(v
)) {
191 s
= PyString_AS_STRING(v
);
192 len
= PyString_GET_SIZE(v
);
194 #ifdef Py_USING_UNICODE
195 else if (PyUnicode_Check(v
)) {
196 if (PyUnicode_GET_SIZE(v
) >= (Py_ssize_t
)sizeof(s_buffer
)) {
197 PyErr_SetString(PyExc_ValueError
,
198 "Unicode float() literal too long to convert");
201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
202 PyUnicode_GET_SIZE(v
),
210 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
211 PyErr_SetString(PyExc_TypeError
,
212 "float() argument must be a string or a number");
217 while (*s
&& isspace(Py_CHARMASK(*s
)))
220 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
224 /* We don't care about overflow or underflow. If the platform supports
225 * them, infinities and signed zeroes (on underflow) are fine.
226 * However, strtod can return 0 for denormalized numbers, where atof
227 * does not. So (alas!) we special-case a zero result. Note that
228 * whether strtod sets errno on underflow is not defined, so we can't
231 PyFPE_START_PROTECT("strtod", return NULL
)
232 x
= PyOS_ascii_strtod(s
, (char **)&end
);
235 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
236 byte at the end of the string, when the input is inf(inity). */
239 /* Check for inf and nan. This is done late because it rarely happens. */
251 if (PyOS_strnicmp(p
, "inf", 4) == 0) {
254 if (PyOS_strnicmp(p
, "infinity", 9) == 0) {
258 if(PyOS_strnicmp(p
, "nan", 4) == 0) {
262 PyOS_snprintf(buffer
, sizeof(buffer
),
263 "invalid literal for float(): %.200s", s
);
264 PyErr_SetString(PyExc_ValueError
, buffer
);
267 /* Since end != s, the platform made *some* kind of sense out
268 of the input. Trust it. */
269 while (*end
&& isspace(Py_CHARMASK(*end
)))
272 PyOS_snprintf(buffer
, sizeof(buffer
),
273 "invalid literal for float(): %.200s", s
);
274 PyErr_SetString(PyExc_ValueError
, buffer
);
277 else if (end
!= last
) {
278 PyErr_SetString(PyExc_ValueError
,
279 "null byte in argument for float()");
283 /* See above -- may have been strtod being anal
285 PyFPE_START_PROTECT("atof", return NULL
)
286 x
= PyOS_ascii_atof(s
);
288 errno
= 0; /* whether atof ever set errno is undefined */
290 return PyFloat_FromDouble(x
);
294 float_dealloc(PyFloatObject
*op
)
296 if (PyFloat_CheckExact(op
)) {
297 Py_TYPE(op
) = (struct _typeobject
*)free_list
;
301 Py_TYPE(op
)->tp_free((PyObject
*)op
);
305 PyFloat_AsDouble(PyObject
*op
)
311 if (op
&& PyFloat_Check(op
))
312 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
319 if ((nb
= Py_TYPE(op
)->tp_as_number
) == NULL
|| nb
->nb_float
== NULL
) {
320 PyErr_SetString(PyExc_TypeError
, "a float is required");
324 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
327 if (!PyFloat_Check(fo
)) {
328 PyErr_SetString(PyExc_TypeError
,
329 "nb_float should return float object");
333 val
= PyFloat_AS_DOUBLE(fo
);
342 format_float(char *buf
, size_t buflen
, PyFloatObject
*v
, int precision
)
348 /* Subroutine for float_repr and float_print.
349 We want float numbers to be recognizable as such,
350 i.e., they should contain a decimal point or an exponent.
351 However, %g may print the number as an integer;
352 in such cases, we append ".0" to the string. */
354 assert(PyFloat_Check(v
));
355 PyOS_snprintf(format
, 32, "%%.%ig", precision
);
356 PyOS_ascii_formatd(buf
, buflen
, format
, v
->ob_fval
);
360 for (; *cp
!= '\0'; cp
++) {
361 /* Any non-digit means it's not an integer;
362 this takes care of NAN and INF as well. */
363 if (!isdigit(Py_CHARMASK(*cp
)))
372 /* Checking the next three chars should be more than enough to
373 * detect inf or nan, even on Windows. We check for inf or nan
374 * at last because they are rare cases.
376 for (i
=0; *cp
!= '\0' && i
<3; cp
++, i
++) {
377 if (isdigit(Py_CHARMASK(*cp
)) || *cp
== '.')
379 /* found something that is neither a digit nor point
380 * it might be a NaN or INF
383 if (Py_IS_NAN(v
->ob_fval
)) {
388 if (Py_IS_INFINITY(v
->ob_fval
)) {
399 /* XXX PyFloat_AsStringEx should not be a public API function (for one
400 XXX thing, its signature passes a buffer without a length; for another,
401 XXX it isn't useful outside this file).
404 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
406 format_float(buf
, 100, v
, precision
);
409 /* Macro and helper that convert PyObject obj to a C double and store
410 the value in dbl; this replaces the functionality of the coercion
411 slot function. If conversion to double raises an exception, obj is
412 set to NULL, and the function invoking this macro returns NULL. If
413 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
414 stored in obj, and returned from the function invoking this macro.
416 #define CONVERT_TO_DOUBLE(obj, dbl) \
417 if (PyFloat_Check(obj)) \
418 dbl = PyFloat_AS_DOUBLE(obj); \
419 else if (convert_to_double(&(obj), &(dbl)) < 0) \
423 convert_to_double(PyObject
**v
, double *dbl
)
425 register PyObject
*obj
= *v
;
427 if (PyInt_Check(obj
)) {
428 *dbl
= (double)PyInt_AS_LONG(obj
);
430 else if (PyLong_Check(obj
)) {
431 *dbl
= PyLong_AsDouble(obj
);
432 if (*dbl
== -1.0 && PyErr_Occurred()) {
438 Py_INCREF(Py_NotImplemented
);
439 *v
= Py_NotImplemented
;
445 /* Precisions used by repr() and str(), respectively.
447 The repr() precision (17 significant decimal digits) is the minimal number
448 that is guaranteed to have enough precision so that if the number is read
449 back in the exact same binary value is recreated. This is true for IEEE
450 floating point by design, and also happens to work for all other modern
453 The str() precision is chosen so that in most cases, the rounding noise
454 created by various operations is suppressed, while giving plenty of
455 precision for practical use.
462 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
463 XXX they pass a char buffer without passing a length.
466 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
468 format_float(buf
, 100, v
, PREC_STR
);
472 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
474 format_float(buf
, 100, v
, PREC_REPR
);
479 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
482 format_float(buf
, sizeof(buf
), v
,
483 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
484 Py_BEGIN_ALLOW_THREADS
491 float_repr(PyFloatObject
*v
)
494 format_float(buf
, sizeof(buf
), v
, PREC_REPR
);
496 return PyString_FromString(buf
);
500 float_str(PyFloatObject
*v
)
503 format_float(buf
, sizeof(buf
), v
, PREC_STR
);
504 return PyString_FromString(buf
);
507 /* Comparison is pretty much a nightmare. When comparing float to float,
508 * we do it as straightforwardly (and long-windedly) as conceivable, so
509 * that, e.g., Python x == y delivers the same result as the platform
510 * C x == y when x and/or y is a NaN.
511 * When mixing float with an integer type, there's no good *uniform* approach.
512 * Converting the double to an integer obviously doesn't work, since we
513 * may lose info from fractional bits. Converting the integer to a double
514 * also has two failure modes: (1) a long int may trigger overflow (too
515 * large to fit in the dynamic range of a C double); (2) even a C long may have
516 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
517 * 63 bits of precision, but a C double probably has only 53), and then
518 * we can falsely claim equality when low-order integer bits are lost by
519 * coercion to double. So this part is painful too.
523 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
528 assert(PyFloat_Check(v
));
529 i
= PyFloat_AS_DOUBLE(v
);
531 /* Switch on the type of w. Set i and j to doubles to be compared,
532 * and op to the richcomp to use.
534 if (PyFloat_Check(w
))
535 j
= PyFloat_AS_DOUBLE(w
);
537 else if (!Py_IS_FINITE(i
)) {
538 if (PyInt_Check(w
) || PyLong_Check(w
))
539 /* If i is an infinity, its magnitude exceeds any
540 * finite integer, so it doesn't matter which int we
541 * compare i with. If i is a NaN, similarly.
548 else if (PyInt_Check(w
)) {
549 long jj
= PyInt_AS_LONG(w
);
550 /* In the worst realistic case I can imagine, C double is a
551 * Cray single with 48 bits of precision, and long has 64
555 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
557 /* Needs more than 48 bits. Make it take the
561 PyObject
*ww
= PyLong_FromLong(jj
);
565 result
= float_richcompare(v
, ww
, op
);
571 assert((long)j
== jj
);
574 else if (PyLong_Check(w
)) {
575 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
576 int wsign
= _PyLong_Sign(w
);
580 if (vsign
!= wsign
) {
581 /* Magnitudes are irrelevant -- the signs alone
582 * determine the outcome.
588 /* The signs are the same. */
589 /* Convert w to a double if it fits. In particular, 0 fits. */
590 nbits
= _PyLong_NumBits(w
);
591 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
592 /* This long is so large that size_t isn't big enough
593 * to hold the # of bits. Replace with little doubles
594 * that give the same outcome -- w is so large that
595 * its magnitude must exceed the magnitude of any
605 j
= PyLong_AsDouble(w
);
606 /* It's impossible that <= 48 bits overflowed. */
607 assert(j
!= -1.0 || ! PyErr_Occurred());
610 assert(wsign
!= 0); /* else nbits was 0 */
611 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
612 * not 0, we would have taken the
613 * vsign != wsign branch at the start */
614 /* We want to work with non-negative numbers. */
616 /* "Multiply both sides" by -1; this also swaps the
620 op
= _Py_SwappedOp
[op
];
623 (void) frexp(i
, &exponent
);
624 /* exponent is the # of bits in v before the radix point;
625 * we know that nbits (the # of bits in w) > 48 at this point
627 if (exponent
< 0 || (size_t)exponent
< nbits
) {
632 if ((size_t)exponent
> nbits
) {
637 /* v and w have the same number of bits before the radix
638 * point. Construct two longs that have the same comparison
644 PyObject
*result
= NULL
;
645 PyObject
*one
= NULL
;
650 ww
= PyNumber_Negative(w
);
657 fracpart
= modf(i
, &intpart
);
658 vv
= PyLong_FromDouble(intpart
);
662 if (fracpart
!= 0.0) {
663 /* Shift left, and or a 1 bit into vv
664 * to represent the lost fraction.
668 one
= PyInt_FromLong(1);
672 temp
= PyNumber_Lshift(ww
, one
);
678 temp
= PyNumber_Lshift(vv
, one
);
684 temp
= PyNumber_Or(vv
, one
);
691 r
= PyObject_RichCompareBool(vv
, ww
, op
);
694 result
= PyBool_FromLong(r
);
701 } /* else if (PyLong_Check(w)) */
703 else /* w isn't float, int, or long */
707 PyFPE_START_PROTECT("richcompare", return NULL
)
729 return PyBool_FromLong(r
);
732 Py_INCREF(Py_NotImplemented
);
733 return Py_NotImplemented
;
737 float_hash(PyFloatObject
*v
)
739 return _Py_HashDouble(v
->ob_fval
);
743 float_add(PyObject
*v
, PyObject
*w
)
746 CONVERT_TO_DOUBLE(v
, a
);
747 CONVERT_TO_DOUBLE(w
, b
);
748 PyFPE_START_PROTECT("add", return 0)
751 return PyFloat_FromDouble(a
);
755 float_sub(PyObject
*v
, PyObject
*w
)
758 CONVERT_TO_DOUBLE(v
, a
);
759 CONVERT_TO_DOUBLE(w
, b
);
760 PyFPE_START_PROTECT("subtract", return 0)
763 return PyFloat_FromDouble(a
);
767 float_mul(PyObject
*v
, PyObject
*w
)
770 CONVERT_TO_DOUBLE(v
, a
);
771 CONVERT_TO_DOUBLE(w
, b
);
772 PyFPE_START_PROTECT("multiply", return 0)
775 return PyFloat_FromDouble(a
);
779 float_div(PyObject
*v
, PyObject
*w
)
782 CONVERT_TO_DOUBLE(v
, a
);
783 CONVERT_TO_DOUBLE(w
, b
);
786 PyErr_SetString(PyExc_ZeroDivisionError
,
791 PyFPE_START_PROTECT("divide", return 0)
794 return PyFloat_FromDouble(a
);
798 float_classic_div(PyObject
*v
, PyObject
*w
)
801 CONVERT_TO_DOUBLE(v
, a
);
802 CONVERT_TO_DOUBLE(w
, b
);
803 if (Py_DivisionWarningFlag
>= 2 &&
804 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
808 PyErr_SetString(PyExc_ZeroDivisionError
,
813 PyFPE_START_PROTECT("divide", return 0)
816 return PyFloat_FromDouble(a
);
820 float_rem(PyObject
*v
, PyObject
*w
)
824 CONVERT_TO_DOUBLE(v
, vx
);
825 CONVERT_TO_DOUBLE(w
, wx
);
828 PyErr_SetString(PyExc_ZeroDivisionError
,
833 PyFPE_START_PROTECT("modulo", return 0)
835 /* note: checking mod*wx < 0 is incorrect -- underflows to
836 0 if wx < sqrt(smallest nonzero double) */
837 if (mod
&& ((wx
< 0) != (mod
< 0))) {
840 PyFPE_END_PROTECT(mod
)
841 return PyFloat_FromDouble(mod
);
845 float_divmod(PyObject
*v
, PyObject
*w
)
848 double div
, mod
, floordiv
;
849 CONVERT_TO_DOUBLE(v
, vx
);
850 CONVERT_TO_DOUBLE(w
, wx
);
852 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
855 PyFPE_START_PROTECT("divmod", return 0)
857 /* fmod is typically exact, so vx-mod is *mathematically* an
858 exact multiple of wx. But this is fp arithmetic, and fp
859 vx - mod is an approximation; the result is that div may
860 not be an exact integral value after the division, although
861 it will always be very close to one.
863 div
= (vx
- mod
) / wx
;
865 /* ensure the remainder has the same sign as the denominator */
866 if ((wx
< 0) != (mod
< 0)) {
872 /* the remainder is zero, and in the presence of signed zeroes
873 fmod returns different results across platforms; ensure
874 it has the same sign as the denominator; we'd like to do
875 "mod = wx * 0.0", but that may get optimized away */
876 mod
*= mod
; /* hide "mod = +0" from optimizer */
880 /* snap quotient to nearest integral value */
882 floordiv
= floor(div
);
883 if (div
- floordiv
> 0.5)
887 /* div is zero - get the same sign as the true quotient */
888 div
*= div
; /* hide "div = +0" from optimizers */
889 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
891 PyFPE_END_PROTECT(floordiv
)
892 return Py_BuildValue("(dd)", floordiv
, mod
);
896 float_floor_div(PyObject
*v
, PyObject
*w
)
900 t
= float_divmod(v
, w
);
901 if (t
== NULL
|| t
== Py_NotImplemented
)
903 assert(PyTuple_CheckExact(t
));
904 r
= PyTuple_GET_ITEM(t
, 0);
911 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
915 if ((PyObject
*)z
!= Py_None
) {
916 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
917 "allowed unless all arguments are integers");
921 CONVERT_TO_DOUBLE(v
, iv
);
922 CONVERT_TO_DOUBLE(w
, iw
);
924 /* Sort out special cases here instead of relying on pow() */
925 if (iw
== 0) { /* v**0 is 1, even 0**0 */
926 return PyFloat_FromDouble(1.0);
928 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
930 PyErr_SetString(PyExc_ZeroDivisionError
,
931 "0.0 cannot be raised to a negative power");
934 return PyFloat_FromDouble(0.0);
936 if (iv
== 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
937 return PyFloat_FromDouble(1.0);
940 /* Whether this is an error is a mess, and bumps into libm
941 * bugs so we have to figure it out ourselves.
943 if (iw
!= floor(iw
)) {
944 PyErr_SetString(PyExc_ValueError
, "negative number "
945 "cannot be raised to a fractional power");
948 /* iw is an exact integer, albeit perhaps a very large one.
949 * -1 raised to an exact integer should never be exceptional.
950 * Alas, some libms (chiefly glibc as of early 2003) return
951 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
952 * happen to be representable in a *C* integer. That's a
953 * bug; we let that slide in math.pow() (which currently
954 * reflects all platform accidents), but not for Python's **.
956 if (iv
== -1.0 && Py_IS_FINITE(iw
)) {
957 /* Return 1 if iw is even, -1 if iw is odd; there's
958 * no guarantee that any C integral type is big
959 * enough to hold iw, so we have to check this
962 ix
= floor(iw
* 0.5) * 2.0;
963 return PyFloat_FromDouble(ix
== iw
? 1.0 : -1.0);
965 /* Else iv != -1.0, and overflow or underflow are possible.
966 * Unless we're to write pow() ourselves, we have to trust
967 * the platform to do this correctly.
971 PyFPE_START_PROTECT("pow", return NULL
)
973 PyFPE_END_PROTECT(ix
)
974 Py_ADJUST_ERANGE1(ix
);
976 /* We don't expect any errno value other than ERANGE, but
977 * the range of libm bugs appears unbounded.
979 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
983 return PyFloat_FromDouble(ix
);
987 float_neg(PyFloatObject
*v
)
989 return PyFloat_FromDouble(-v
->ob_fval
);
993 float_abs(PyFloatObject
*v
)
995 return PyFloat_FromDouble(fabs(v
->ob_fval
));
999 float_nonzero(PyFloatObject
*v
)
1001 return v
->ob_fval
!= 0.0;
1005 float_coerce(PyObject
**pv
, PyObject
**pw
)
1007 if (PyInt_Check(*pw
)) {
1008 long x
= PyInt_AsLong(*pw
);
1009 *pw
= PyFloat_FromDouble((double)x
);
1013 else if (PyLong_Check(*pw
)) {
1014 double x
= PyLong_AsDouble(*pw
);
1015 if (x
== -1.0 && PyErr_Occurred())
1017 *pw
= PyFloat_FromDouble(x
);
1021 else if (PyFloat_Check(*pw
)) {
1026 return 1; /* Can't do it */
1030 float_is_integer(PyObject
*v
)
1032 double x
= PyFloat_AsDouble(v
);
1035 if (x
== -1.0 && PyErr_Occurred())
1037 if (!Py_IS_FINITE(x
))
1040 PyFPE_START_PROTECT("is_integer", return NULL
)
1041 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
1042 PyFPE_END_PROTECT(x
)
1044 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
1054 float_is_inf(PyObject
*v
)
1056 double x
= PyFloat_AsDouble(v
);
1057 if (x
== -1.0 && PyErr_Occurred())
1059 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
1063 float_is_nan(PyObject
*v
)
1065 double x
= PyFloat_AsDouble(v
);
1066 if (x
== -1.0 && PyErr_Occurred())
1068 return PyBool_FromLong((long)Py_IS_NAN(x
));
1072 float_is_finite(PyObject
*v
)
1074 double x
= PyFloat_AsDouble(v
);
1075 if (x
== -1.0 && PyErr_Occurred())
1077 return PyBool_FromLong((long)Py_IS_FINITE(x
));
1082 float_trunc(PyObject
*v
)
1084 double x
= PyFloat_AsDouble(v
);
1085 double wholepart
; /* integral portion of x, rounded toward 0 */
1087 (void)modf(x
, &wholepart
);
1088 /* Try to get out cheap if this fits in a Python int. The attempt
1089 * to cast to long must be protected, as C doesn't define what
1090 * happens if the double is too big to fit in a long. Some rare
1091 * systems raise an exception then (RISCOS was mentioned as one,
1092 * and someone using a non-default option on Sun also bumped into
1093 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1094 * still be vulnerable: if a long has more bits of precision than
1095 * a double, casting MIN/MAX to double may yield an approximation,
1096 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1097 * yield true from the C expression wholepart<=LONG_MAX, despite
1098 * that wholepart is actually greater than LONG_MAX.
1100 if (LONG_MIN
< wholepart
&& wholepart
< LONG_MAX
) {
1101 const long aslong
= (long)wholepart
;
1102 return PyInt_FromLong(aslong
);
1104 return PyLong_FromDouble(wholepart
);
1108 float_long(PyObject
*v
)
1110 double x
= PyFloat_AsDouble(v
);
1111 return PyLong_FromDouble(x
);
1115 float_float(PyObject
*v
)
1117 if (PyFloat_CheckExact(v
))
1120 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1124 /* turn ASCII hex characters into integer values and vice versa */
1127 char_from_hex(int x
)
1129 assert(0 <= x
&& x
< 16);
1130 return "0123456789abcdef"[x
];
1134 hex_from_char(char c
) {
1198 /* convert a float to a hexadecimal string */
1200 /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1201 of the form 4k+1. */
1202 #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1205 float_hex(PyObject
*v
)
1208 int e
, shift
, i
, si
, esign
;
1209 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1210 trailing NUL byte. */
1211 char s
[(TOHEX_NBITS
-1)/4+3];
1213 CONVERT_TO_DOUBLE(v
, x
);
1215 if (Py_IS_NAN(x
) || Py_IS_INFINITY(x
))
1216 return float_str((PyFloatObject
*)v
);
1219 if(copysign(1.0, x
) == -1.0)
1220 return PyString_FromString("-0x0.0p+0");
1222 return PyString_FromString("0x0.0p+0");
1225 m
= frexp(fabs(x
), &e
);
1226 shift
= 1 - MAX(DBL_MIN_EXP
- e
, 0);
1227 m
= ldexp(m
, shift
);
1231 s
[si
] = char_from_hex((int)m
);
1236 for (i
=0; i
< (TOHEX_NBITS
-1)/4; i
++) {
1238 s
[si
] = char_from_hex((int)m
);
1252 return PyString_FromFormat("-0x%sp%c%d", s
, esign
, e
);
1254 return PyString_FromFormat("0x%sp%c%d", s
, esign
, e
);
1257 PyDoc_STRVAR(float_hex_doc
,
1258 "float.hex() -> string\n\
1260 Return a hexadecimal representation of a floating-point number.\n\
1262 '-0x1.999999999999ap-4'\n\
1263 >>> 3.14159.hex()\n\
1264 '0x1.921f9f01b866ep+1'");
1266 /* Convert a hexadecimal string to a float. */
1269 float_fromhex(PyObject
*cls
, PyObject
*arg
)
1271 PyObject
*result_as_float
, *result
;
1273 long exp
, top_exp
, lsb
, key_digit
;
1274 char *s
, *coeff_start
, *s_store
, *coeff_end
, *exp_start
, *s_end
;
1275 int half_eps
, digit
, round_up
, sign
=1;
1276 Py_ssize_t length
, ndigits
, fdigits
, i
;
1279 * For the sake of simplicity and correctness, we impose an artificial
1280 * limit on ndigits, the total number of hex digits in the coefficient
1281 * The limit is chosen to ensure that, writing exp for the exponent,
1283 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1284 * guaranteed to overflow (provided it's nonzero)
1286 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1287 * guaranteed to underflow to 0.
1289 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1290 * overflow in the calculation of exp and top_exp below.
1292 * More specifically, ndigits is assumed to satisfy the following
1295 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1296 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1298 * If either of these inequalities is not satisfied, a ValueError is
1299 * raised. Otherwise, write x for the value of the hex string, and
1300 * assume x is nonzero. Then
1302 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1304 * Now if exp > LONG_MAX/2 then:
1306 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1309 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1310 * double, so overflows. If exp < LONG_MIN/2, then
1312 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1313 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1314 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1316 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1317 * when converted to a C double.
1319 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1320 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1323 if (PyString_AsStringAndSize(arg
, &s
, &length
))
1327 /********************
1328 * Parse the string *
1329 ********************/
1331 /* leading whitespace and optional sign */
1341 /* infinities and nans */
1342 if (PyOS_strnicmp(s
, "nan", 4) == 0) {
1346 if (PyOS_strnicmp(s
, "inf", 4) == 0 ||
1347 PyOS_strnicmp(s
, "infinity", 9) == 0) {
1348 x
= sign
*Py_HUGE_VAL
;
1356 if (tolower(*s
) == (int)'x')
1362 /* coefficient: <integer> [. <fraction>] */
1364 while (hex_from_char(*s
) >= 0)
1369 while (hex_from_char(*s
) >= 0)
1376 /* ndigits = total # of hex digits; fdigits = # after point */
1377 ndigits
= coeff_end
- coeff_start
;
1378 fdigits
= coeff_end
- s_store
;
1381 if (ndigits
> MIN(DBL_MIN_EXP
- DBL_MANT_DIG
- LONG_MIN
/2,
1382 LONG_MAX
/2 + 1 - DBL_MAX_EXP
)/4)
1383 goto insane_length_error
;
1385 /* [p <exponent>] */
1386 if (tolower(*s
) == (int)'p') {
1389 if (*s
== '-' || *s
== '+')
1391 if (!('0' <= *s
&& *s
<= '9'))
1394 while ('0' <= *s
&& *s
<= '9')
1396 exp
= strtol(exp_start
, NULL
, 10);
1401 /* optional trailing whitespace leading to the end of the string */
1407 /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1408 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1412 /*******************************************
1413 * Compute rounded value of the hex string *
1414 *******************************************/
1416 /* Discard leading zeros, and catch extreme overflow and underflow */
1417 while (ndigits
> 0 && HEX_DIGIT(ndigits
-1) == 0)
1419 if (ndigits
== 0 || exp
< LONG_MIN
/2) {
1423 if (exp
> LONG_MAX
/2)
1424 goto overflow_error
;
1426 /* Adjust exponent for fractional part. */
1427 exp
= exp
- 4*((long)fdigits
);
1429 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1430 top_exp
= exp
+ 4*((long)ndigits
- 1);
1431 for (digit
= HEX_DIGIT(ndigits
-1); digit
!= 0; digit
/= 2)
1434 /* catch almost all nonextreme cases of overflow and underflow here */
1435 if (top_exp
< DBL_MIN_EXP
- DBL_MANT_DIG
) {
1439 if (top_exp
> DBL_MAX_EXP
)
1440 goto overflow_error
;
1442 /* lsb = exponent of least significant bit of the *rounded* value.
1443 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1444 lsb
= MAX(top_exp
, (long)DBL_MIN_EXP
) - DBL_MANT_DIG
;
1448 /* no rounding required */
1449 for (i
= ndigits
-1; i
>= 0; i
--)
1450 x
= 16.0*x
+ HEX_DIGIT(i
);
1451 x
= sign
* ldexp(x
, (int)(exp
));
1454 /* rounding required. key_digit is the index of the hex digit
1455 containing the first bit to be rounded away. */
1456 half_eps
= 1 << (int)((lsb
- exp
- 1) % 4);
1457 key_digit
= (lsb
- exp
- 1) / 4;
1458 for (i
= ndigits
-1; i
> key_digit
; i
--)
1459 x
= 16.0*x
+ HEX_DIGIT(i
);
1460 digit
= HEX_DIGIT(key_digit
);
1461 x
= 16.0*x
+ (double)(digit
& (16-2*half_eps
));
1463 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1464 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1465 if ((digit
& half_eps
) != 0) {
1467 if ((digit
& (3*half_eps
-1)) != 0 ||
1468 (half_eps
== 8 && (HEX_DIGIT(key_digit
+1) & 1) != 0))
1471 for (i
= key_digit
-1; i
>= 0; i
--)
1472 if (HEX_DIGIT(i
) != 0) {
1476 if (round_up
== 1) {
1478 if (top_exp
== DBL_MAX_EXP
&&
1479 x
== ldexp((double)(2*half_eps
), DBL_MANT_DIG
))
1480 /* overflow corner case: pre-rounded value <
1481 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1482 goto overflow_error
;
1485 x
= sign
* ldexp(x
, (int)(exp
+4*key_digit
));
1488 result_as_float
= Py_BuildValue("(d)", x
);
1489 if (result_as_float
== NULL
)
1491 result
= PyObject_CallObject(cls
, result_as_float
);
1492 Py_DECREF(result_as_float
);
1496 PyErr_SetString(PyExc_OverflowError
,
1497 "hexadecimal value too large to represent as a float");
1501 PyErr_SetString(PyExc_ValueError
,
1502 "invalid hexadecimal floating-point string");
1505 insane_length_error
:
1506 PyErr_SetString(PyExc_ValueError
,
1507 "hexadecimal string too long to convert");
1511 PyDoc_STRVAR(float_fromhex_doc
,
1512 "float.fromhex(string) -> float\n\
1514 Create a floating-point number from a hexadecimal string.\n\
1515 >>> float.fromhex('0x1.ffffp10')\n\
1517 >>> float.fromhex('-0x1p-1074')\n\
1518 -4.9406564584124654e-324");
1522 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
1530 PyObject
*py_exponent
= NULL
;
1531 PyObject
*numerator
= NULL
;
1532 PyObject
*denominator
= NULL
;
1533 PyObject
*result_pair
= NULL
;
1534 PyNumberMethods
*long_methods
= PyLong_Type
.tp_as_number
;
1536 #define INPLACE_UPDATE(obj, call) \
1541 CONVERT_TO_DOUBLE(v, self);
1543 if (Py_IS_INFINITY(self
)) {
1544 PyErr_SetString(PyExc_OverflowError
,
1545 "Cannot pass infinity to float.as_integer_ratio.");
1549 if (Py_IS_NAN(self
)) {
1550 PyErr_SetString(PyExc_ValueError
,
1551 "Cannot pass NaN to float.as_integer_ratio.");
1556 PyFPE_START_PROTECT("as_integer_ratio", goto error
);
1557 float_part
= frexp(self
, &exponent
); /* self == float_part * 2**exponent exactly */
1558 PyFPE_END_PROTECT(float_part
);
1560 for (i
=0; i
<300 && float_part
!= floor(float_part
) ; i
++) {
1564 /* self == float_part * 2**exponent exactly and float_part is integral.
1565 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1566 to be truncated by PyLong_FromDouble(). */
1568 numerator
= PyLong_FromDouble(float_part
);
1569 if (numerator
== NULL
) goto error
;
1571 /* fold in 2**exponent */
1572 denominator
= PyLong_FromLong(1);
1573 py_exponent
= PyLong_FromLong(labs((long)exponent
));
1574 if (py_exponent
== NULL
) goto error
;
1575 INPLACE_UPDATE(py_exponent
,
1576 long_methods
->nb_lshift(denominator
, py_exponent
));
1577 if (py_exponent
== NULL
) goto error
;
1579 INPLACE_UPDATE(numerator
,
1580 long_methods
->nb_multiply(numerator
, py_exponent
));
1581 if (numerator
== NULL
) goto error
;
1584 Py_DECREF(denominator
);
1585 denominator
= py_exponent
;
1589 /* Returns ints instead of longs where possible */
1590 INPLACE_UPDATE(numerator
, PyNumber_Int(numerator
));
1591 if (numerator
== NULL
) goto error
;
1592 INPLACE_UPDATE(denominator
, PyNumber_Int(denominator
));
1593 if (denominator
== NULL
) goto error
;
1595 result_pair
= PyTuple_Pack(2, numerator
, denominator
);
1597 #undef INPLACE_UPDATE
1599 Py_XDECREF(py_exponent
);
1600 Py_XDECREF(denominator
);
1601 Py_XDECREF(numerator
);
1605 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1606 "float.as_integer_ratio() -> (int, int)\n"
1608 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
1609 "float and with a positive denominator.\n"
1610 "Raises OverflowError on infinities and a ValueError on NaNs.\n"
1612 ">>> (10.0).as_integer_ratio()\n"
1614 ">>> (0.0).as_integer_ratio()\n"
1616 ">>> (-.25).as_integer_ratio()\n"
1621 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
1624 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1626 PyObject
*x
= Py_False
; /* Integer zero */
1627 static char *kwlist
[] = {"x", 0};
1629 if (type
!= &PyFloat_Type
)
1630 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
1631 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
1633 if (PyString_Check(x
))
1634 return PyFloat_FromString(x
, NULL
);
1635 return PyNumber_Float(x
);
1638 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1639 first create a regular float from whatever arguments we got,
1640 then allocate a subtype instance and initialize its ob_fval
1641 from the regular float. The regular float is then thrown away.
1644 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1646 PyObject
*tmp
, *newobj
;
1648 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
1649 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
1652 assert(PyFloat_CheckExact(tmp
));
1653 newobj
= type
->tp_alloc(type
, 0);
1654 if (newobj
== NULL
) {
1658 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
1664 float_getnewargs(PyFloatObject
*v
)
1666 return Py_BuildValue("(d)", v
->ob_fval
);
1669 /* this is for the benefit of the pack/unpack routines below */
1672 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
1673 } float_format_type
;
1675 static float_format_type double_format
, float_format
;
1676 static float_format_type detected_double_format
, detected_float_format
;
1679 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1682 float_format_type r
;
1684 if (!PyString_Check(arg
)) {
1685 PyErr_Format(PyExc_TypeError
,
1686 "__getformat__() argument must be string, not %.500s",
1687 Py_TYPE(arg
)->tp_name
);
1690 s
= PyString_AS_STRING(arg
);
1691 if (strcmp(s
, "double") == 0) {
1694 else if (strcmp(s
, "float") == 0) {
1698 PyErr_SetString(PyExc_ValueError
,
1699 "__getformat__() argument 1 must be "
1700 "'double' or 'float'");
1705 case unknown_format
:
1706 return PyString_FromString("unknown");
1707 case ieee_little_endian_format
:
1708 return PyString_FromString("IEEE, little-endian");
1709 case ieee_big_endian_format
:
1710 return PyString_FromString("IEEE, big-endian");
1712 Py_FatalError("insane float_format or double_format");
1717 PyDoc_STRVAR(float_getformat_doc
,
1718 "float.__getformat__(typestr) -> string\n"
1720 "You probably don't want to use this function. It exists mainly to be\n"
1721 "used in Python's test suite.\n"
1723 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1724 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1725 "format of floating point numbers used by the C type named by typestr.");
1728 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1732 float_format_type f
;
1733 float_format_type detected
;
1734 float_format_type
*p
;
1736 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1739 if (strcmp(typestr
, "double") == 0) {
1741 detected
= detected_double_format
;
1743 else if (strcmp(typestr
, "float") == 0) {
1745 detected
= detected_float_format
;
1748 PyErr_SetString(PyExc_ValueError
,
1749 "__setformat__() argument 1 must "
1750 "be 'double' or 'float'");
1754 if (strcmp(format
, "unknown") == 0) {
1757 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1758 f
= ieee_little_endian_format
;
1760 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1761 f
= ieee_big_endian_format
;
1764 PyErr_SetString(PyExc_ValueError
,
1765 "__setformat__() argument 2 must be "
1766 "'unknown', 'IEEE, little-endian' or "
1767 "'IEEE, big-endian'");
1772 if (f
!= unknown_format
&& f
!= detected
) {
1773 PyErr_Format(PyExc_ValueError
,
1774 "can only set %s format to 'unknown' or the "
1775 "detected platform value", typestr
);
1783 PyDoc_STRVAR(float_setformat_doc
,
1784 "float.__setformat__(typestr, fmt) -> None\n"
1786 "You probably don't want to use this function. It exists mainly to be\n"
1787 "used in Python's test suite.\n"
1789 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1790 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1791 "one of the latter two if it appears to match the underlying C reality.\n"
1793 "Overrides the automatic determination of C-level floating point type.\n"
1794 "This affects how floats are converted to and from binary strings.");
1797 float_getzero(PyObject
*v
, void *closure
)
1799 return PyFloat_FromDouble(0.0);
1803 float__format__(PyObject
*self
, PyObject
*args
)
1805 PyObject
*format_spec
;
1807 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1809 if (PyBytes_Check(format_spec
))
1810 return _PyFloat_FormatAdvanced(self
,
1811 PyBytes_AS_STRING(format_spec
),
1812 PyBytes_GET_SIZE(format_spec
));
1813 if (PyUnicode_Check(format_spec
)) {
1814 /* Convert format_spec to a str */
1816 PyObject
*str_spec
= PyObject_Str(format_spec
);
1818 if (str_spec
== NULL
)
1821 result
= _PyFloat_FormatAdvanced(self
,
1822 PyBytes_AS_STRING(str_spec
),
1823 PyBytes_GET_SIZE(str_spec
));
1825 Py_DECREF(str_spec
);
1828 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1832 PyDoc_STRVAR(float__format__doc
,
1833 "float.__format__(format_spec) -> string\n"
1835 "Formats the float according to format_spec.");
1838 static PyMethodDef float_methods
[] = {
1839 {"conjugate", (PyCFunction
)float_float
, METH_NOARGS
,
1840 "Returns self, the complex conjugate of any float."},
1841 {"__trunc__", (PyCFunction
)float_trunc
, METH_NOARGS
,
1842 "Returns the Integral closest to x between 0 and x."},
1843 {"as_integer_ratio", (PyCFunction
)float_as_integer_ratio
, METH_NOARGS
,
1844 float_as_integer_ratio_doc
},
1845 {"fromhex", (PyCFunction
)float_fromhex
,
1846 METH_O
|METH_CLASS
, float_fromhex_doc
},
1847 {"hex", (PyCFunction
)float_hex
,
1848 METH_NOARGS
, float_hex_doc
},
1849 {"is_integer", (PyCFunction
)float_is_integer
, METH_NOARGS
,
1850 "Returns True if the float is an integer."},
1852 {"is_inf", (PyCFunction
)float_is_inf
, METH_NOARGS
,
1853 "Returns True if the float is positive or negative infinite."},
1854 {"is_finite", (PyCFunction
)float_is_finite
, METH_NOARGS
,
1855 "Returns True if the float is finite, neither infinite nor NaN."},
1856 {"is_nan", (PyCFunction
)float_is_nan
, METH_NOARGS
,
1857 "Returns True if the float is not a number (NaN)."},
1859 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
1860 {"__getformat__", (PyCFunction
)float_getformat
,
1861 METH_O
|METH_CLASS
, float_getformat_doc
},
1862 {"__setformat__", (PyCFunction
)float_setformat
,
1863 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
1864 {"__format__", (PyCFunction
)float__format__
,
1865 METH_VARARGS
, float__format__doc
},
1866 {NULL
, NULL
} /* sentinel */
1869 static PyGetSetDef float_getset
[] = {
1871 (getter
)float_float
, (setter
)NULL
,
1872 "the real part of a complex number",
1875 (getter
)float_getzero
, (setter
)NULL
,
1876 "the imaginary part of a complex number",
1878 {NULL
} /* Sentinel */
1881 PyDoc_STRVAR(float_doc
,
1882 "float(x) -> floating point number\n\
1884 Convert a string or number to a floating point number, if possible.");
1887 static PyNumberMethods float_as_number
= {
1888 float_add
, /*nb_add*/
1889 float_sub
, /*nb_subtract*/
1890 float_mul
, /*nb_multiply*/
1891 float_classic_div
, /*nb_divide*/
1892 float_rem
, /*nb_remainder*/
1893 float_divmod
, /*nb_divmod*/
1894 float_pow
, /*nb_power*/
1895 (unaryfunc
)float_neg
, /*nb_negative*/
1896 (unaryfunc
)float_float
, /*nb_positive*/
1897 (unaryfunc
)float_abs
, /*nb_absolute*/
1898 (inquiry
)float_nonzero
, /*nb_nonzero*/
1905 float_coerce
, /*nb_coerce*/
1906 float_trunc
, /*nb_int*/
1907 float_long
, /*nb_long*/
1908 float_float
, /*nb_float*/
1911 0, /* nb_inplace_add */
1912 0, /* nb_inplace_subtract */
1913 0, /* nb_inplace_multiply */
1914 0, /* nb_inplace_divide */
1915 0, /* nb_inplace_remainder */
1916 0, /* nb_inplace_power */
1917 0, /* nb_inplace_lshift */
1918 0, /* nb_inplace_rshift */
1919 0, /* nb_inplace_and */
1920 0, /* nb_inplace_xor */
1921 0, /* nb_inplace_or */
1922 float_floor_div
, /* nb_floor_divide */
1923 float_div
, /* nb_true_divide */
1924 0, /* nb_inplace_floor_divide */
1925 0, /* nb_inplace_true_divide */
1928 PyTypeObject PyFloat_Type
= {
1929 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
1931 sizeof(PyFloatObject
),
1933 (destructor
)float_dealloc
, /* tp_dealloc */
1934 (printfunc
)float_print
, /* tp_print */
1938 (reprfunc
)float_repr
, /* tp_repr */
1939 &float_as_number
, /* tp_as_number */
1940 0, /* tp_as_sequence */
1941 0, /* tp_as_mapping */
1942 (hashfunc
)float_hash
, /* tp_hash */
1944 (reprfunc
)float_str
, /* tp_str */
1945 PyObject_GenericGetAttr
, /* tp_getattro */
1946 0, /* tp_setattro */
1947 0, /* tp_as_buffer */
1948 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
1949 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1950 float_doc
, /* tp_doc */
1951 0, /* tp_traverse */
1953 float_richcompare
, /* tp_richcompare */
1954 0, /* tp_weaklistoffset */
1956 0, /* tp_iternext */
1957 float_methods
, /* tp_methods */
1959 float_getset
, /* tp_getset */
1962 0, /* tp_descr_get */
1963 0, /* tp_descr_set */
1964 0, /* tp_dictoffset */
1967 float_new
, /* tp_new */
1973 /* We attempt to determine if this machine is using IEEE
1974 floating point formats by peering at the bits of some
1975 carefully chosen values. If it looks like we are on an
1976 IEEE platform, the float packing/unpacking routines can
1977 just copy bits, if not they resort to arithmetic & shifts
1978 and masks. The shifts & masks approach works on all finite
1979 values, but what happens to infinities, NaNs and signed
1980 zeroes on packing is an accident, and attempting to unpack
1981 a NaN or an infinity will raise an exception.
1983 Note that if we're on some whacked-out platform which uses
1984 IEEE formats but isn't strictly little-endian or big-
1985 endian, we will fall back to the portable shifts & masks
1988 #if SIZEOF_DOUBLE == 8
1990 double x
= 9006104071832581.0;
1991 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1992 detected_double_format
= ieee_big_endian_format
;
1993 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1994 detected_double_format
= ieee_little_endian_format
;
1996 detected_double_format
= unknown_format
;
1999 detected_double_format
= unknown_format
;
2002 #if SIZEOF_FLOAT == 4
2004 float y
= 16711938.0;
2005 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
2006 detected_float_format
= ieee_big_endian_format
;
2007 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
2008 detected_float_format
= ieee_little_endian_format
;
2010 detected_float_format
= unknown_format
;
2013 detected_float_format
= unknown_format
;
2016 double_format
= detected_double_format
;
2017 float_format
= detected_float_format
;
2019 /* Init float info */
2020 if (FloatInfoType
.tp_name
== 0)
2021 PyStructSequence_InitType(&FloatInfoType
, &floatinfo_desc
);
2025 PyFloat_ClearFreeList(void)
2028 PyFloatBlock
*list
, *next
;
2030 int u
; /* remaining unfreed ints per block */
2031 int freelist_size
= 0;
2036 while (list
!= NULL
) {
2038 for (i
= 0, p
= &list
->objects
[0];
2041 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
2046 list
->next
= block_list
;
2048 for (i
= 0, p
= &list
->objects
[0];
2051 if (!PyFloat_CheckExact(p
) ||
2052 Py_REFCNT(p
) == 0) {
2053 Py_TYPE(p
) = (struct _typeobject
*)
2065 return freelist_size
;
2074 int u
; /* total unfreed floats per block */
2076 u
= PyFloat_ClearFreeList();
2078 if (!Py_VerboseFlag
)
2080 fprintf(stderr
, "# cleanup floats");
2082 fprintf(stderr
, "\n");
2086 ": %d unfreed float%s\n",
2087 u
, u
== 1 ? "" : "s");
2089 if (Py_VerboseFlag
> 1) {
2091 while (list
!= NULL
) {
2092 for (i
= 0, p
= &list
->objects
[0];
2095 if (PyFloat_CheckExact(p
) &&
2096 Py_REFCNT(p
) != 0) {
2098 PyFloat_AsString(buf
, p
);
2099 /* XXX(twouters) cast refcount to
2100 long until %zd is universally
2104 "# <float at %p, refcnt=%ld, val=%s>\n",
2105 p
, (long)Py_REFCNT(p
), buf
);
2113 /*----------------------------------------------------------------------------
2114 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
2117 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
2119 if (float_format
== unknown_format
) {
2140 /* Normalize f to be in the range [1.0, 2.0) */
2141 if (0.5 <= f
&& f
< 1.0) {
2148 PyErr_SetString(PyExc_SystemError
,
2149 "frexp() result out of range");
2155 else if (e
< -126) {
2156 /* Gradual underflow */
2157 f
= ldexp(f
, 126 + e
);
2160 else if (!(e
== 0 && f
== 0.0)) {
2162 f
-= 1.0; /* Get rid of leading 1 */
2165 f
*= 8388608.0; /* 2**23 */
2166 fbits
= (unsigned int)(f
+ 0.5); /* Round */
2167 assert(fbits
<= 8388608);
2169 /* The carry propagated out of a string of 23 1 bits. */
2177 *p
= (sign
<< 7) | (e
>> 1);
2181 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
2185 *p
= (fbits
>> 8) & 0xFF;
2197 const char *s
= (char*)&y
;
2200 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
2203 if ((float_format
== ieee_little_endian_format
&& !le
)
2204 || (float_format
== ieee_big_endian_format
&& le
)) {
2209 for (i
= 0; i
< 4; i
++) {
2216 PyErr_SetString(PyExc_OverflowError
,
2217 "float too large to pack with f format");
2222 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
2224 if (double_format
== unknown_format
) {
2228 unsigned int fhi
, flo
;
2245 /* Normalize f to be in the range [1.0, 2.0) */
2246 if (0.5 <= f
&& f
< 1.0) {
2253 PyErr_SetString(PyExc_SystemError
,
2254 "frexp() result out of range");
2260 else if (e
< -1022) {
2261 /* Gradual underflow */
2262 f
= ldexp(f
, 1022 + e
);
2265 else if (!(e
== 0 && f
== 0.0)) {
2267 f
-= 1.0; /* Get rid of leading 1 */
2270 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2271 f
*= 268435456.0; /* 2**28 */
2272 fhi
= (unsigned int)f
; /* Truncate */
2273 assert(fhi
< 268435456);
2276 f
*= 16777216.0; /* 2**24 */
2277 flo
= (unsigned int)(f
+ 0.5); /* Round */
2278 assert(flo
<= 16777216);
2280 /* The carry propagated out of a string of 24 1 bits. */
2284 /* And it also progagated out of the next 28 bits. */
2293 *p
= (sign
<< 7) | (e
>> 4);
2297 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
2301 *p
= (fhi
>> 16) & 0xFF;
2305 *p
= (fhi
>> 8) & 0xFF;
2313 *p
= (flo
>> 16) & 0xFF;
2317 *p
= (flo
>> 8) & 0xFF;
2328 PyErr_SetString(PyExc_OverflowError
,
2329 "float too large to pack with d format");
2333 const char *s
= (char*)&x
;
2336 if ((double_format
== ieee_little_endian_format
&& !le
)
2337 || (double_format
== ieee_big_endian_format
&& le
)) {
2342 for (i
= 0; i
< 8; i
++) {
2351 _PyFloat_Unpack4(const unsigned char *p
, int le
)
2353 if (float_format
== unknown_format
) {
2366 sign
= (*p
>> 7) & 1;
2367 e
= (*p
& 0x7F) << 1;
2372 f
= (*p
& 0x7F) << 16;
2378 "can't unpack IEEE 754 special value "
2379 "on non-IEEE platform");
2390 x
= (double)f
/ 8388608.0;
2392 /* XXX This sadly ignores Inf/NaN issues */
2409 if ((float_format
== ieee_little_endian_format
&& !le
)
2410 || (float_format
== ieee_big_endian_format
&& le
)) {
2415 for (i
= 0; i
< 4; i
++) {
2429 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2431 if (double_format
== unknown_format
) {
2434 unsigned int fhi
, flo
;
2444 sign
= (*p
>> 7) & 1;
2445 e
= (*p
& 0x7F) << 4;
2450 e
|= (*p
>> 4) & 0xF;
2451 fhi
= (*p
& 0xF) << 24;
2457 "can't unpack IEEE 754 special value "
2458 "on non-IEEE platform");
2485 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2486 x
/= 268435456.0; /* 2**28 */
2504 if ((double_format
== ieee_little_endian_format
&& !le
)
2505 || (double_format
== ieee_big_endian_format
&& le
)) {
2510 for (i
= 0; i
< 8; i
++) {