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. */
18 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
19 extern int finite(double);
22 /* Special free list -- see comments for same code in intobject.c. */
23 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
24 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
25 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
28 struct _floatblock
*next
;
29 PyFloatObject objects
[N_FLOATOBJECTS
];
32 typedef struct _floatblock PyFloatBlock
;
34 static PyFloatBlock
*block_list
= NULL
;
35 static PyFloatObject
*free_list
= NULL
;
37 static PyFloatObject
*
41 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
42 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
44 return (PyFloatObject
*) PyErr_NoMemory();
45 ((PyFloatBlock
*)p
)->next
= block_list
;
46 block_list
= (PyFloatBlock
*)p
;
47 p
= &((PyFloatBlock
*)p
)->objects
[0];
48 q
= p
+ N_FLOATOBJECTS
;
50 Py_TYPE(q
) = (struct _typeobject
*)(q
-1);
52 return p
+ N_FLOATOBJECTS
- 1;
67 static PyTypeObject FloatInfoType
= {0, 0, 0, 0, 0, 0};
69 PyDoc_STRVAR(floatinfo__doc__
,
72 A structseq holding information about the float type. It contains low level\n\
73 information about the precision and internal representation. Please study\n\
74 your system's :file:`float.h` for more information.");
76 static PyStructSequence_Field floatinfo_fields
[] = {
77 {"max", "DBL_MAX -- maximum representable finite float"},
78 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
80 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
82 {"min", "DBL_MIN -- Minimum positive normalizer float"},
83 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
84 "is a normalized float"},
85 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
87 {"dig", "DBL_DIG -- digits"},
88 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
89 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
90 "representable float"},
91 {"radix", "FLT_RADIX -- radix of exponent"},
92 {"rounds", "FLT_ROUNDS -- addition rounds"},
96 static PyStructSequence_Desc floatinfo_desc
= {
97 "sys.floatinfo", /* name */
98 floatinfo__doc__
, /* doc */
99 floatinfo_fields
, /* fields */
104 PyFloat_GetInfo(void)
109 floatinfo
= PyStructSequence_New(&FloatInfoType
);
110 if (floatinfo
== NULL
) {
114 #define SetIntFlag(flag) \
115 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
116 #define SetDblFlag(flag) \
117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
120 SetIntFlag(DBL_MAX_EXP
);
121 SetIntFlag(DBL_MAX_10_EXP
);
123 SetIntFlag(DBL_MIN_EXP
);
124 SetIntFlag(DBL_MIN_10_EXP
);
126 SetIntFlag(DBL_MANT_DIG
);
127 SetDblFlag(DBL_EPSILON
);
128 SetIntFlag(FLT_RADIX
);
129 SetIntFlag(FLT_ROUNDS
);
133 if (PyErr_Occurred()) {
141 PyFloat_FromDouble(double fval
)
143 register PyFloatObject
*op
;
144 if (free_list
== NULL
) {
145 if ((free_list
= fill_free_list()) == NULL
)
148 /* Inline PyObject_New */
150 free_list
= (PyFloatObject
*)Py_TYPE(op
);
151 PyObject_INIT(op
, &PyFloat_Type
);
153 return (PyObject
*) op
;
156 /**************************************************************************
157 RED_FLAG 22-Sep-2000 tim
158 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
160 1. If v was a regular string, *pend was set to point to its terminating
161 null byte. That's useless (the caller can find that without any
162 help from this function!).
164 2. If v was a Unicode string, or an object convertible to a character
165 buffer, *pend was set to point into stack trash (the auto temp
166 vector holding the character buffer). That was downright dangerous.
168 Since we can't change the interface of a public API function, pend is
169 still supported but now *officially* useless: if pend is not NULL,
170 *pend is set to NULL.
171 **************************************************************************/
173 PyFloat_FromString(PyObject
*v
, char **pend
)
175 const char *s
, *last
, *end
, *sp
;
177 char buffer
[256]; /* for errors */
178 #ifdef Py_USING_UNICODE
179 char s_buffer
[256]; /* for objects convertible to a char buffer */
185 if (PyString_Check(v
)) {
186 s
= PyString_AS_STRING(v
);
187 len
= PyString_GET_SIZE(v
);
189 #ifdef Py_USING_UNICODE
190 else if (PyUnicode_Check(v
)) {
191 if (PyUnicode_GET_SIZE(v
) >= (Py_ssize_t
)sizeof(s_buffer
)) {
192 PyErr_SetString(PyExc_ValueError
,
193 "Unicode float() literal too long to convert");
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 (*s
&& isspace(Py_CHARMASK(*s
)))
215 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
219 /* We don't care about overflow or underflow. If the platform supports
220 * them, infinities and signed zeroes (on underflow) are fine.
221 * However, strtod can return 0 for denormalized numbers, where atof
222 * does not. So (alas!) we special-case a zero result. Note that
223 * whether strtod sets errno on underflow is not defined, so we can't
226 PyFPE_START_PROTECT("strtod", return NULL
)
227 x
= PyOS_ascii_strtod(s
, (char **)&end
);
230 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
231 byte at the end of the string, when the input is inf(inity). */
234 /* Check for inf and nan. This is done late because it rarely happens. */
246 if (PyOS_strnicmp(p
, "inf", 4) == 0) {
250 if(PyOS_strnicmp(p
, "nan", 4) == 0) {
254 PyOS_snprintf(buffer
, sizeof(buffer
),
255 "invalid literal for float(): %.200s", s
);
256 PyErr_SetString(PyExc_ValueError
, buffer
);
259 /* Since end != s, the platform made *some* kind of sense out
260 of the input. Trust it. */
261 while (*end
&& isspace(Py_CHARMASK(*end
)))
264 PyOS_snprintf(buffer
, sizeof(buffer
),
265 "invalid literal for float(): %.200s", s
);
266 PyErr_SetString(PyExc_ValueError
, buffer
);
269 else if (end
!= last
) {
270 PyErr_SetString(PyExc_ValueError
,
271 "null byte in argument for float()");
275 /* See above -- may have been strtod being anal
277 PyFPE_START_PROTECT("atof", return NULL
)
278 x
= PyOS_ascii_atof(s
);
280 errno
= 0; /* whether atof ever set errno is undefined */
282 return PyFloat_FromDouble(x
);
286 float_dealloc(PyFloatObject
*op
)
288 if (PyFloat_CheckExact(op
)) {
289 Py_TYPE(op
) = (struct _typeobject
*)free_list
;
293 Py_TYPE(op
)->tp_free((PyObject
*)op
);
297 PyFloat_AsDouble(PyObject
*op
)
303 if (op
&& PyFloat_Check(op
))
304 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
311 if ((nb
= Py_TYPE(op
)->tp_as_number
) == NULL
|| nb
->nb_float
== NULL
) {
312 PyErr_SetString(PyExc_TypeError
, "a float is required");
316 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
319 if (!PyFloat_Check(fo
)) {
320 PyErr_SetString(PyExc_TypeError
,
321 "nb_float should return float object");
325 val
= PyFloat_AS_DOUBLE(fo
);
334 format_float(char *buf
, size_t buflen
, PyFloatObject
*v
, int precision
)
340 /* Subroutine for float_repr and float_print.
341 We want float numbers to be recognizable as such,
342 i.e., they should contain a decimal point or an exponent.
343 However, %g may print the number as an integer;
344 in such cases, we append ".0" to the string. */
346 assert(PyFloat_Check(v
));
347 PyOS_snprintf(format
, 32, "%%.%ig", precision
);
348 PyOS_ascii_formatd(buf
, buflen
, format
, v
->ob_fval
);
352 for (; *cp
!= '\0'; cp
++) {
353 /* Any non-digit means it's not an integer;
354 this takes care of NAN and INF as well. */
355 if (!isdigit(Py_CHARMASK(*cp
)))
364 /* Checking the next three chars should be more than enough to
365 * detect inf or nan, even on Windows. We check for inf or nan
366 * at last because they are rare cases.
368 for (i
=0; *cp
!= '\0' && i
<3; cp
++, i
++) {
369 if (isdigit(Py_CHARMASK(*cp
)) || *cp
== '.')
371 /* found something that is neither a digit nor point
372 * it might be a NaN or INF
375 if (Py_IS_NAN(v
->ob_fval
)) {
380 if (Py_IS_INFINITY(v
->ob_fval
)) {
391 /* XXX PyFloat_AsStringEx should not be a public API function (for one
392 XXX thing, its signature passes a buffer without a length; for another,
393 XXX it isn't useful outside this file).
396 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
398 format_float(buf
, 100, v
, precision
);
401 /* Macro and helper that convert PyObject obj to a C double and store
402 the value in dbl; this replaces the functionality of the coercion
403 slot function. If conversion to double raises an exception, obj is
404 set to NULL, and the function invoking this macro returns NULL. If
405 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
406 stored in obj, and returned from the function invoking this macro.
408 #define CONVERT_TO_DOUBLE(obj, dbl) \
409 if (PyFloat_Check(obj)) \
410 dbl = PyFloat_AS_DOUBLE(obj); \
411 else if (convert_to_double(&(obj), &(dbl)) < 0) \
415 convert_to_double(PyObject
**v
, double *dbl
)
417 register PyObject
*obj
= *v
;
419 if (PyInt_Check(obj
)) {
420 *dbl
= (double)PyInt_AS_LONG(obj
);
422 else if (PyLong_Check(obj
)) {
423 *dbl
= PyLong_AsDouble(obj
);
424 if (*dbl
== -1.0 && PyErr_Occurred()) {
430 Py_INCREF(Py_NotImplemented
);
431 *v
= Py_NotImplemented
;
437 /* Precisions used by repr() and str(), respectively.
439 The repr() precision (17 significant decimal digits) is the minimal number
440 that is guaranteed to have enough precision so that if the number is read
441 back in the exact same binary value is recreated. This is true for IEEE
442 floating point by design, and also happens to work for all other modern
445 The str() precision is chosen so that in most cases, the rounding noise
446 created by various operations is suppressed, while giving plenty of
447 precision for practical use.
454 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
455 XXX they pass a char buffer without passing a length.
458 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
460 format_float(buf
, 100, v
, PREC_STR
);
464 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
466 format_float(buf
, 100, v
, PREC_REPR
);
471 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
474 format_float(buf
, sizeof(buf
), v
,
475 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
476 Py_BEGIN_ALLOW_THREADS
483 float_repr(PyFloatObject
*v
)
486 format_float(buf
, sizeof(buf
), v
, PREC_REPR
);
488 return PyString_FromString(buf
);
492 float_str(PyFloatObject
*v
)
495 format_float(buf
, sizeof(buf
), v
, PREC_STR
);
496 return PyString_FromString(buf
);
499 /* Comparison is pretty much a nightmare. When comparing float to float,
500 * we do it as straightforwardly (and long-windedly) as conceivable, so
501 * that, e.g., Python x == y delivers the same result as the platform
502 * C x == y when x and/or y is a NaN.
503 * When mixing float with an integer type, there's no good *uniform* approach.
504 * Converting the double to an integer obviously doesn't work, since we
505 * may lose info from fractional bits. Converting the integer to a double
506 * also has two failure modes: (1) a long int may trigger overflow (too
507 * large to fit in the dynamic range of a C double); (2) even a C long may have
508 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
509 * 63 bits of precision, but a C double probably has only 53), and then
510 * we can falsely claim equality when low-order integer bits are lost by
511 * coercion to double. So this part is painful too.
515 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
520 assert(PyFloat_Check(v
));
521 i
= PyFloat_AS_DOUBLE(v
);
523 /* Switch on the type of w. Set i and j to doubles to be compared,
524 * and op to the richcomp to use.
526 if (PyFloat_Check(w
))
527 j
= PyFloat_AS_DOUBLE(w
);
529 else if (!Py_IS_FINITE(i
)) {
530 if (PyInt_Check(w
) || PyLong_Check(w
))
531 /* If i is an infinity, its magnitude exceeds any
532 * finite integer, so it doesn't matter which int we
533 * compare i with. If i is a NaN, similarly.
540 else if (PyInt_Check(w
)) {
541 long jj
= PyInt_AS_LONG(w
);
542 /* In the worst realistic case I can imagine, C double is a
543 * Cray single with 48 bits of precision, and long has 64
547 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
549 /* Needs more than 48 bits. Make it take the
553 PyObject
*ww
= PyLong_FromLong(jj
);
557 result
= float_richcompare(v
, ww
, op
);
563 assert((long)j
== jj
);
566 else if (PyLong_Check(w
)) {
567 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
568 int wsign
= _PyLong_Sign(w
);
572 if (vsign
!= wsign
) {
573 /* Magnitudes are irrelevant -- the signs alone
574 * determine the outcome.
580 /* The signs are the same. */
581 /* Convert w to a double if it fits. In particular, 0 fits. */
582 nbits
= _PyLong_NumBits(w
);
583 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
584 /* This long is so large that size_t isn't big enough
585 * to hold the # of bits. Replace with little doubles
586 * that give the same outcome -- w is so large that
587 * its magnitude must exceed the magnitude of any
597 j
= PyLong_AsDouble(w
);
598 /* It's impossible that <= 48 bits overflowed. */
599 assert(j
!= -1.0 || ! PyErr_Occurred());
602 assert(wsign
!= 0); /* else nbits was 0 */
603 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
604 * not 0, we would have taken the
605 * vsign != wsign branch at the start */
606 /* We want to work with non-negative numbers. */
608 /* "Multiply both sides" by -1; this also swaps the
612 op
= _Py_SwappedOp
[op
];
615 (void) frexp(i
, &exponent
);
616 /* exponent is the # of bits in v before the radix point;
617 * we know that nbits (the # of bits in w) > 48 at this point
619 if (exponent
< 0 || (size_t)exponent
< nbits
) {
624 if ((size_t)exponent
> nbits
) {
629 /* v and w have the same number of bits before the radix
630 * point. Construct two longs that have the same comparison
636 PyObject
*result
= NULL
;
637 PyObject
*one
= NULL
;
642 ww
= PyNumber_Negative(w
);
649 fracpart
= modf(i
, &intpart
);
650 vv
= PyLong_FromDouble(intpart
);
654 if (fracpart
!= 0.0) {
655 /* Shift left, and or a 1 bit into vv
656 * to represent the lost fraction.
660 one
= PyInt_FromLong(1);
664 temp
= PyNumber_Lshift(ww
, one
);
670 temp
= PyNumber_Lshift(vv
, one
);
676 temp
= PyNumber_Or(vv
, one
);
683 r
= PyObject_RichCompareBool(vv
, ww
, op
);
686 result
= PyBool_FromLong(r
);
693 } /* else if (PyLong_Check(w)) */
695 else /* w isn't float, int, or long */
699 PyFPE_START_PROTECT("richcompare", return NULL
)
721 return PyBool_FromLong(r
);
724 Py_INCREF(Py_NotImplemented
);
725 return Py_NotImplemented
;
729 float_hash(PyFloatObject
*v
)
731 return _Py_HashDouble(v
->ob_fval
);
735 float_add(PyObject
*v
, PyObject
*w
)
738 CONVERT_TO_DOUBLE(v
, a
);
739 CONVERT_TO_DOUBLE(w
, b
);
740 PyFPE_START_PROTECT("add", return 0)
743 return PyFloat_FromDouble(a
);
747 float_sub(PyObject
*v
, PyObject
*w
)
750 CONVERT_TO_DOUBLE(v
, a
);
751 CONVERT_TO_DOUBLE(w
, b
);
752 PyFPE_START_PROTECT("subtract", return 0)
755 return PyFloat_FromDouble(a
);
759 float_mul(PyObject
*v
, PyObject
*w
)
762 CONVERT_TO_DOUBLE(v
, a
);
763 CONVERT_TO_DOUBLE(w
, b
);
764 PyFPE_START_PROTECT("multiply", return 0)
767 return PyFloat_FromDouble(a
);
771 float_div(PyObject
*v
, PyObject
*w
)
774 CONVERT_TO_DOUBLE(v
, a
);
775 CONVERT_TO_DOUBLE(w
, b
);
778 PyErr_SetString(PyExc_ZeroDivisionError
,
783 PyFPE_START_PROTECT("divide", return 0)
786 return PyFloat_FromDouble(a
);
790 float_classic_div(PyObject
*v
, PyObject
*w
)
793 CONVERT_TO_DOUBLE(v
, a
);
794 CONVERT_TO_DOUBLE(w
, b
);
795 if (Py_DivisionWarningFlag
>= 2 &&
796 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
800 PyErr_SetString(PyExc_ZeroDivisionError
,
805 PyFPE_START_PROTECT("divide", return 0)
808 return PyFloat_FromDouble(a
);
812 float_rem(PyObject
*v
, PyObject
*w
)
816 CONVERT_TO_DOUBLE(v
, vx
);
817 CONVERT_TO_DOUBLE(w
, wx
);
820 PyErr_SetString(PyExc_ZeroDivisionError
,
825 PyFPE_START_PROTECT("modulo", return 0)
827 /* note: checking mod*wx < 0 is incorrect -- underflows to
828 0 if wx < sqrt(smallest nonzero double) */
829 if (mod
&& ((wx
< 0) != (mod
< 0))) {
832 PyFPE_END_PROTECT(mod
)
833 return PyFloat_FromDouble(mod
);
837 float_divmod(PyObject
*v
, PyObject
*w
)
840 double div
, mod
, floordiv
;
841 CONVERT_TO_DOUBLE(v
, vx
);
842 CONVERT_TO_DOUBLE(w
, wx
);
844 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
847 PyFPE_START_PROTECT("divmod", return 0)
849 /* fmod is typically exact, so vx-mod is *mathematically* an
850 exact multiple of wx. But this is fp arithmetic, and fp
851 vx - mod is an approximation; the result is that div may
852 not be an exact integral value after the division, although
853 it will always be very close to one.
855 div
= (vx
- mod
) / wx
;
857 /* ensure the remainder has the same sign as the denominator */
858 if ((wx
< 0) != (mod
< 0)) {
864 /* the remainder is zero, and in the presence of signed zeroes
865 fmod returns different results across platforms; ensure
866 it has the same sign as the denominator; we'd like to do
867 "mod = wx * 0.0", but that may get optimized away */
868 mod
*= mod
; /* hide "mod = +0" from optimizer */
872 /* snap quotient to nearest integral value */
874 floordiv
= floor(div
);
875 if (div
- floordiv
> 0.5)
879 /* div is zero - get the same sign as the true quotient */
880 div
*= div
; /* hide "div = +0" from optimizers */
881 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
883 PyFPE_END_PROTECT(floordiv
)
884 return Py_BuildValue("(dd)", floordiv
, mod
);
888 float_floor_div(PyObject
*v
, PyObject
*w
)
892 t
= float_divmod(v
, w
);
893 if (t
== NULL
|| t
== Py_NotImplemented
)
895 assert(PyTuple_CheckExact(t
));
896 r
= PyTuple_GET_ITEM(t
, 0);
903 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
907 if ((PyObject
*)z
!= Py_None
) {
908 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
909 "allowed unless all arguments are integers");
913 CONVERT_TO_DOUBLE(v
, iv
);
914 CONVERT_TO_DOUBLE(w
, iw
);
916 /* Sort out special cases here instead of relying on pow() */
917 if (iw
== 0) { /* v**0 is 1, even 0**0 */
918 return PyFloat_FromDouble(1.0);
920 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
922 PyErr_SetString(PyExc_ZeroDivisionError
,
923 "0.0 cannot be raised to a negative power");
926 return PyFloat_FromDouble(0.0);
928 if (iv
== 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
929 return PyFloat_FromDouble(1.0);
932 /* Whether this is an error is a mess, and bumps into libm
933 * bugs so we have to figure it out ourselves.
935 if (iw
!= floor(iw
)) {
936 PyErr_SetString(PyExc_ValueError
, "negative number "
937 "cannot be raised to a fractional power");
940 /* iw is an exact integer, albeit perhaps a very large one.
941 * -1 raised to an exact integer should never be exceptional.
942 * Alas, some libms (chiefly glibc as of early 2003) return
943 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
944 * happen to be representable in a *C* integer. That's a
945 * bug; we let that slide in math.pow() (which currently
946 * reflects all platform accidents), but not for Python's **.
948 if (iv
== -1.0 && Py_IS_FINITE(iw
)) {
949 /* Return 1 if iw is even, -1 if iw is odd; there's
950 * no guarantee that any C integral type is big
951 * enough to hold iw, so we have to check this
954 ix
= floor(iw
* 0.5) * 2.0;
955 return PyFloat_FromDouble(ix
== iw
? 1.0 : -1.0);
957 /* Else iv != -1.0, and overflow or underflow are possible.
958 * Unless we're to write pow() ourselves, we have to trust
959 * the platform to do this correctly.
963 PyFPE_START_PROTECT("pow", return NULL
)
965 PyFPE_END_PROTECT(ix
)
966 Py_ADJUST_ERANGE1(ix
);
968 /* We don't expect any errno value other than ERANGE, but
969 * the range of libm bugs appears unbounded.
971 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
975 return PyFloat_FromDouble(ix
);
979 float_neg(PyFloatObject
*v
)
981 return PyFloat_FromDouble(-v
->ob_fval
);
985 float_abs(PyFloatObject
*v
)
987 return PyFloat_FromDouble(fabs(v
->ob_fval
));
991 float_nonzero(PyFloatObject
*v
)
993 return v
->ob_fval
!= 0.0;
997 float_coerce(PyObject
**pv
, PyObject
**pw
)
999 if (PyInt_Check(*pw
)) {
1000 long x
= PyInt_AsLong(*pw
);
1001 *pw
= PyFloat_FromDouble((double)x
);
1005 else if (PyLong_Check(*pw
)) {
1006 double x
= PyLong_AsDouble(*pw
);
1007 if (x
== -1.0 && PyErr_Occurred())
1009 *pw
= PyFloat_FromDouble(x
);
1013 else if (PyFloat_Check(*pw
)) {
1018 return 1; /* Can't do it */
1022 float_is_integer(PyObject
*v
)
1024 double x
= PyFloat_AsDouble(v
);
1027 if (x
== -1.0 && PyErr_Occurred())
1029 if (!Py_IS_FINITE(x
))
1032 PyFPE_START_PROTECT("is_integer", return NULL
)
1033 o
= (floor(x
) == x
) ? Py_True
: Py_False
;
1034 PyFPE_END_PROTECT(x
)
1036 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
1046 float_is_inf(PyObject
*v
)
1048 double x
= PyFloat_AsDouble(v
);
1049 if (x
== -1.0 && PyErr_Occurred())
1051 return PyBool_FromLong((long)Py_IS_INFINITY(x
));
1055 float_is_nan(PyObject
*v
)
1057 double x
= PyFloat_AsDouble(v
);
1058 if (x
== -1.0 && PyErr_Occurred())
1060 return PyBool_FromLong((long)Py_IS_NAN(x
));
1064 float_is_finite(PyObject
*v
)
1066 double x
= PyFloat_AsDouble(v
);
1067 if (x
== -1.0 && PyErr_Occurred())
1069 return PyBool_FromLong((long)Py_IS_FINITE(x
));
1074 float_trunc(PyObject
*v
)
1076 double x
= PyFloat_AsDouble(v
);
1077 double wholepart
; /* integral portion of x, rounded toward 0 */
1079 (void)modf(x
, &wholepart
);
1080 /* Try to get out cheap if this fits in a Python int. The attempt
1081 * to cast to long must be protected, as C doesn't define what
1082 * happens if the double is too big to fit in a long. Some rare
1083 * systems raise an exception then (RISCOS was mentioned as one,
1084 * and someone using a non-default option on Sun also bumped into
1085 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1086 * still be vulnerable: if a long has more bits of precision than
1087 * a double, casting MIN/MAX to double may yield an approximation,
1088 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1089 * yield true from the C expression wholepart<=LONG_MAX, despite
1090 * that wholepart is actually greater than LONG_MAX.
1092 if (LONG_MIN
< wholepart
&& wholepart
< LONG_MAX
) {
1093 const long aslong
= (long)wholepart
;
1094 return PyInt_FromLong(aslong
);
1096 return PyLong_FromDouble(wholepart
);
1100 float_float(PyObject
*v
)
1102 if (PyFloat_CheckExact(v
))
1105 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
1110 float_as_integer_ratio(PyObject
*v
, PyObject
*unused
)
1118 PyObject
*py_exponent
= NULL
;
1119 PyObject
*numerator
= NULL
;
1120 PyObject
*denominator
= NULL
;
1121 PyObject
*result_pair
= NULL
;
1122 PyNumberMethods
*long_methods
= PyLong_Type
.tp_as_number
;
1124 #define INPLACE_UPDATE(obj, call) \
1129 CONVERT_TO_DOUBLE(v, self);
1131 if (Py_IS_INFINITY(self
)) {
1132 PyErr_SetString(PyExc_OverflowError
,
1133 "Cannot pass infinity to float.as_integer_ratio.");
1137 if (Py_IS_NAN(self
)) {
1138 PyErr_SetString(PyExc_ValueError
,
1139 "Cannot pass nan to float.as_integer_ratio.");
1144 PyFPE_START_PROTECT("as_integer_ratio", goto error
);
1145 float_part
= frexp(self
, &exponent
); /* self == float_part * 2**exponent exactly */
1146 PyFPE_END_PROTECT(float_part
);
1148 for (i
=0; i
<300 && float_part
!= floor(float_part
) ; i
++) {
1152 /* self == float_part * 2**exponent exactly and float_part is integral.
1153 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1154 to be truncated by PyLong_FromDouble(). */
1156 numerator
= PyLong_FromDouble(float_part
);
1157 if (numerator
== NULL
) goto error
;
1159 /* fold in 2**exponent */
1160 denominator
= PyLong_FromLong(1);
1161 py_exponent
= PyLong_FromLong(labs((long)exponent
));
1162 if (py_exponent
== NULL
) goto error
;
1163 INPLACE_UPDATE(py_exponent
,
1164 long_methods
->nb_lshift(denominator
, py_exponent
));
1165 if (py_exponent
== NULL
) goto error
;
1167 INPLACE_UPDATE(numerator
,
1168 long_methods
->nb_multiply(numerator
, py_exponent
));
1169 if (numerator
== NULL
) goto error
;
1172 Py_DECREF(denominator
);
1173 denominator
= py_exponent
;
1177 /* Returns ints instead of longs where possible */
1178 INPLACE_UPDATE(numerator
, PyNumber_Int(numerator
));
1179 if (numerator
== NULL
) goto error
;
1180 INPLACE_UPDATE(denominator
, PyNumber_Int(denominator
));
1181 if (denominator
== NULL
) goto error
;
1183 result_pair
= PyTuple_Pack(2, numerator
, denominator
);
1185 #undef INPLACE_UPDATE
1187 Py_XDECREF(py_exponent
);
1188 Py_XDECREF(denominator
);
1189 Py_XDECREF(numerator
);
1193 PyDoc_STRVAR(float_as_integer_ratio_doc
,
1194 "float.as_integer_ratio() -> (int, int)\n"
1196 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
1197 "float and with a positive denominator.\n"
1198 "Raises OverflowError on infinities and a ValueError on nans.\n"
1200 ">>> (10.0).as_integer_ratio()\n"
1202 ">>> (0.0).as_integer_ratio()\n"
1204 ">>> (-.25).as_integer_ratio()\n"
1209 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
1212 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1214 PyObject
*x
= Py_False
; /* Integer zero */
1215 static char *kwlist
[] = {"x", 0};
1217 if (type
!= &PyFloat_Type
)
1218 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
1219 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
1221 if (PyString_Check(x
))
1222 return PyFloat_FromString(x
, NULL
);
1223 return PyNumber_Float(x
);
1226 /* Wimpy, slow approach to tp_new calls for subtypes of float:
1227 first create a regular float from whatever arguments we got,
1228 then allocate a subtype instance and initialize its ob_fval
1229 from the regular float. The regular float is then thrown away.
1232 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1234 PyObject
*tmp
, *newobj
;
1236 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
1237 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
1240 assert(PyFloat_CheckExact(tmp
));
1241 newobj
= type
->tp_alloc(type
, 0);
1242 if (newobj
== NULL
) {
1246 ((PyFloatObject
*)newobj
)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
1252 float_getnewargs(PyFloatObject
*v
)
1254 return Py_BuildValue("(d)", v
->ob_fval
);
1257 /* this is for the benefit of the pack/unpack routines below */
1260 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
1261 } float_format_type
;
1263 static float_format_type double_format
, float_format
;
1264 static float_format_type detected_double_format
, detected_float_format
;
1267 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1270 float_format_type r
;
1272 if (!PyString_Check(arg
)) {
1273 PyErr_Format(PyExc_TypeError
,
1274 "__getformat__() argument must be string, not %.500s",
1275 Py_TYPE(arg
)->tp_name
);
1278 s
= PyString_AS_STRING(arg
);
1279 if (strcmp(s
, "double") == 0) {
1282 else if (strcmp(s
, "float") == 0) {
1286 PyErr_SetString(PyExc_ValueError
,
1287 "__getformat__() argument 1 must be "
1288 "'double' or 'float'");
1293 case unknown_format
:
1294 return PyString_FromString("unknown");
1295 case ieee_little_endian_format
:
1296 return PyString_FromString("IEEE, little-endian");
1297 case ieee_big_endian_format
:
1298 return PyString_FromString("IEEE, big-endian");
1300 Py_FatalError("insane float_format or double_format");
1305 PyDoc_STRVAR(float_getformat_doc
,
1306 "float.__getformat__(typestr) -> string\n"
1308 "You probably don't want to use this function. It exists mainly to be\n"
1309 "used in Python's test suite.\n"
1311 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1312 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1313 "format of floating point numbers used by the C type named by typestr.");
1316 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1320 float_format_type f
;
1321 float_format_type detected
;
1322 float_format_type
*p
;
1324 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1327 if (strcmp(typestr
, "double") == 0) {
1329 detected
= detected_double_format
;
1331 else if (strcmp(typestr
, "float") == 0) {
1333 detected
= detected_float_format
;
1336 PyErr_SetString(PyExc_ValueError
,
1337 "__setformat__() argument 1 must "
1338 "be 'double' or 'float'");
1342 if (strcmp(format
, "unknown") == 0) {
1345 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1346 f
= ieee_little_endian_format
;
1348 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1349 f
= ieee_big_endian_format
;
1352 PyErr_SetString(PyExc_ValueError
,
1353 "__setformat__() argument 2 must be "
1354 "'unknown', 'IEEE, little-endian' or "
1355 "'IEEE, big-endian'");
1360 if (f
!= unknown_format
&& f
!= detected
) {
1361 PyErr_Format(PyExc_ValueError
,
1362 "can only set %s format to 'unknown' or the "
1363 "detected platform value", typestr
);
1371 PyDoc_STRVAR(float_setformat_doc
,
1372 "float.__setformat__(typestr, fmt) -> None\n"
1374 "You probably don't want to use this function. It exists mainly to be\n"
1375 "used in Python's test suite.\n"
1377 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1378 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1379 "one of the latter two if it appears to match the underlying C reality.\n"
1381 "Overrides the automatic determination of C-level floating point type.\n"
1382 "This affects how floats are converted to and from binary strings.");
1385 float_getzero(PyObject
*v
, void *closure
)
1387 return PyFloat_FromDouble(0.0);
1391 float__format__(PyObject
*self
, PyObject
*args
)
1393 PyObject
*format_spec
;
1395 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1397 if (PyBytes_Check(format_spec
))
1398 return _PyFloat_FormatAdvanced(self
,
1399 PyBytes_AS_STRING(format_spec
),
1400 PyBytes_GET_SIZE(format_spec
));
1401 if (PyUnicode_Check(format_spec
)) {
1402 /* Convert format_spec to a str */
1404 PyObject
*str_spec
= PyObject_Str(format_spec
);
1406 if (str_spec
== NULL
)
1409 result
= _PyFloat_FormatAdvanced(self
,
1410 PyBytes_AS_STRING(str_spec
),
1411 PyBytes_GET_SIZE(str_spec
));
1413 Py_DECREF(str_spec
);
1416 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1420 PyDoc_STRVAR(float__format__doc
,
1421 "float.__format__(format_spec) -> string\n"
1423 "Formats the float according to format_spec.");
1426 static PyMethodDef float_methods
[] = {
1427 {"conjugate", (PyCFunction
)float_float
, METH_NOARGS
,
1428 "Returns self, the complex conjugate of any float."},
1429 {"__trunc__", (PyCFunction
)float_trunc
, METH_NOARGS
,
1430 "Returns the Integral closest to x between 0 and x."},
1431 {"as_integer_ratio", (PyCFunction
)float_as_integer_ratio
, METH_NOARGS
,
1432 float_as_integer_ratio_doc
},
1433 {"is_integer", (PyCFunction
)float_is_integer
, METH_NOARGS
,
1434 "Returns True if the float is an integer."},
1436 {"is_inf", (PyCFunction
)float_is_inf
, METH_NOARGS
,
1437 "Returns True if the float is positive or negative infinite."},
1438 {"is_finite", (PyCFunction
)float_is_finite
, METH_NOARGS
,
1439 "Returns True if the float is finite, neither infinite nor NaN."},
1440 {"is_nan", (PyCFunction
)float_is_nan
, METH_NOARGS
,
1441 "Returns True if the float is not a number (NaN)."},
1443 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
1444 {"__getformat__", (PyCFunction
)float_getformat
,
1445 METH_O
|METH_CLASS
, float_getformat_doc
},
1446 {"__setformat__", (PyCFunction
)float_setformat
,
1447 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
1448 {"__format__", (PyCFunction
)float__format__
,
1449 METH_VARARGS
, float__format__doc
},
1450 {NULL
, NULL
} /* sentinel */
1453 static PyGetSetDef float_getset
[] = {
1455 (getter
)float_float
, (setter
)NULL
,
1456 "the real part of a complex number",
1459 (getter
)float_getzero
, (setter
)NULL
,
1460 "the imaginary part of a complex number",
1462 {NULL
} /* Sentinel */
1465 PyDoc_STRVAR(float_doc
,
1466 "float(x) -> floating point number\n\
1468 Convert a string or number to a floating point number, if possible.");
1471 static PyNumberMethods float_as_number
= {
1472 float_add
, /*nb_add*/
1473 float_sub
, /*nb_subtract*/
1474 float_mul
, /*nb_multiply*/
1475 float_classic_div
, /*nb_divide*/
1476 float_rem
, /*nb_remainder*/
1477 float_divmod
, /*nb_divmod*/
1478 float_pow
, /*nb_power*/
1479 (unaryfunc
)float_neg
, /*nb_negative*/
1480 (unaryfunc
)float_float
, /*nb_positive*/
1481 (unaryfunc
)float_abs
, /*nb_absolute*/
1482 (inquiry
)float_nonzero
, /*nb_nonzero*/
1489 float_coerce
, /*nb_coerce*/
1490 float_trunc
, /*nb_int*/
1491 float_trunc
, /*nb_long*/
1492 float_float
, /*nb_float*/
1495 0, /* nb_inplace_add */
1496 0, /* nb_inplace_subtract */
1497 0, /* nb_inplace_multiply */
1498 0, /* nb_inplace_divide */
1499 0, /* nb_inplace_remainder */
1500 0, /* nb_inplace_power */
1501 0, /* nb_inplace_lshift */
1502 0, /* nb_inplace_rshift */
1503 0, /* nb_inplace_and */
1504 0, /* nb_inplace_xor */
1505 0, /* nb_inplace_or */
1506 float_floor_div
, /* nb_floor_divide */
1507 float_div
, /* nb_true_divide */
1508 0, /* nb_inplace_floor_divide */
1509 0, /* nb_inplace_true_divide */
1512 PyTypeObject PyFloat_Type
= {
1513 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
1515 sizeof(PyFloatObject
),
1517 (destructor
)float_dealloc
, /* tp_dealloc */
1518 (printfunc
)float_print
, /* tp_print */
1522 (reprfunc
)float_repr
, /* tp_repr */
1523 &float_as_number
, /* tp_as_number */
1524 0, /* tp_as_sequence */
1525 0, /* tp_as_mapping */
1526 (hashfunc
)float_hash
, /* tp_hash */
1528 (reprfunc
)float_str
, /* tp_str */
1529 PyObject_GenericGetAttr
, /* tp_getattro */
1530 0, /* tp_setattro */
1531 0, /* tp_as_buffer */
1532 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
1533 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1534 float_doc
, /* tp_doc */
1535 0, /* tp_traverse */
1537 float_richcompare
, /* tp_richcompare */
1538 0, /* tp_weaklistoffset */
1540 0, /* tp_iternext */
1541 float_methods
, /* tp_methods */
1543 float_getset
, /* tp_getset */
1546 0, /* tp_descr_get */
1547 0, /* tp_descr_set */
1548 0, /* tp_dictoffset */
1551 float_new
, /* tp_new */
1557 /* We attempt to determine if this machine is using IEEE
1558 floating point formats by peering at the bits of some
1559 carefully chosen values. If it looks like we are on an
1560 IEEE platform, the float packing/unpacking routines can
1561 just copy bits, if not they resort to arithmetic & shifts
1562 and masks. The shifts & masks approach works on all finite
1563 values, but what happens to infinities, NaNs and signed
1564 zeroes on packing is an accident, and attempting to unpack
1565 a NaN or an infinity will raise an exception.
1567 Note that if we're on some whacked-out platform which uses
1568 IEEE formats but isn't strictly little-endian or big-
1569 endian, we will fall back to the portable shifts & masks
1572 #if SIZEOF_DOUBLE == 8
1574 double x
= 9006104071832581.0;
1575 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1576 detected_double_format
= ieee_big_endian_format
;
1577 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1578 detected_double_format
= ieee_little_endian_format
;
1580 detected_double_format
= unknown_format
;
1583 detected_double_format
= unknown_format
;
1586 #if SIZEOF_FLOAT == 4
1588 float y
= 16711938.0;
1589 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
1590 detected_float_format
= ieee_big_endian_format
;
1591 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
1592 detected_float_format
= ieee_little_endian_format
;
1594 detected_float_format
= unknown_format
;
1597 detected_float_format
= unknown_format
;
1600 double_format
= detected_double_format
;
1601 float_format
= detected_float_format
;
1603 /* Init float info */
1604 if (FloatInfoType
.tp_name
== 0)
1605 PyStructSequence_InitType(&FloatInfoType
, &floatinfo_desc
);
1609 PyFloat_CompactFreeList(size_t *pbc
, size_t *pbf
, size_t *bsum
)
1612 PyFloatBlock
*list
, *next
;
1614 size_t bc
= 0, bf
= 0; /* block count, number of freed blocks */
1615 size_t fsum
= 0; /* total unfreed ints */
1616 int frem
; /* remaining unfreed ints per block */
1621 while (list
!= NULL
) {
1624 for (i
= 0, p
= &list
->objects
[0];
1627 if (PyFloat_CheckExact(p
) && Py_REFCNT(p
) != 0)
1632 list
->next
= block_list
;
1634 for (i
= 0, p
= &list
->objects
[0];
1637 if (!PyFloat_CheckExact(p
) ||
1638 Py_REFCNT(p
) == 0) {
1639 Py_TYPE(p
) = (struct _typeobject
*)
1646 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
1663 size_t bc
, bf
; /* block count, number of freed blocks */
1664 size_t fsum
; /* total unfreed floats per block */
1666 PyFloat_CompactFreeList(&bc
, &bf
, &fsum
);
1668 if (!Py_VerboseFlag
)
1670 fprintf(stderr
, "# cleanup floats");
1672 fprintf(stderr
, "\n");
1676 ": %" PY_FORMAT_SIZE_T
"d unfreed float%s in %"
1677 PY_FORMAT_SIZE_T
"d out of %"
1678 PY_FORMAT_SIZE_T
"d block%s\n",
1679 fsum
, fsum
== 1 ? "" : "s",
1680 bc
- bf
, bc
, bc
== 1 ? "" : "s");
1682 if (Py_VerboseFlag
> 1) {
1684 while (list
!= NULL
) {
1685 for (i
= 0, p
= &list
->objects
[0];
1688 if (PyFloat_CheckExact(p
) &&
1689 Py_REFCNT(p
) != 0) {
1691 PyFloat_AsString(buf
, p
);
1692 /* XXX(twouters) cast refcount to
1693 long until %zd is universally
1697 "# <float at %p, refcnt=%ld, val=%s>\n",
1698 p
, (long)Py_REFCNT(p
), buf
);
1706 /*----------------------------------------------------------------------------
1707 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1710 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
1712 if (float_format
== unknown_format
) {
1733 /* Normalize f to be in the range [1.0, 2.0) */
1734 if (0.5 <= f
&& f
< 1.0) {
1741 PyErr_SetString(PyExc_SystemError
,
1742 "frexp() result out of range");
1748 else if (e
< -126) {
1749 /* Gradual underflow */
1750 f
= ldexp(f
, 126 + e
);
1753 else if (!(e
== 0 && f
== 0.0)) {
1755 f
-= 1.0; /* Get rid of leading 1 */
1758 f
*= 8388608.0; /* 2**23 */
1759 fbits
= (unsigned int)(f
+ 0.5); /* Round */
1760 assert(fbits
<= 8388608);
1762 /* The carry propagated out of a string of 23 1 bits. */
1770 *p
= (sign
<< 7) | (e
>> 1);
1774 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
1778 *p
= (fbits
>> 8) & 0xFF;
1790 const char *s
= (char*)&y
;
1793 if (Py_IS_INFINITY(y
) && !Py_IS_INFINITY(x
))
1796 if ((float_format
== ieee_little_endian_format
&& !le
)
1797 || (float_format
== ieee_big_endian_format
&& le
)) {
1802 for (i
= 0; i
< 4; i
++) {
1809 PyErr_SetString(PyExc_OverflowError
,
1810 "float too large to pack with f format");
1815 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
1817 if (double_format
== unknown_format
) {
1821 unsigned int fhi
, flo
;
1838 /* Normalize f to be in the range [1.0, 2.0) */
1839 if (0.5 <= f
&& f
< 1.0) {
1846 PyErr_SetString(PyExc_SystemError
,
1847 "frexp() result out of range");
1853 else if (e
< -1022) {
1854 /* Gradual underflow */
1855 f
= ldexp(f
, 1022 + e
);
1858 else if (!(e
== 0 && f
== 0.0)) {
1860 f
-= 1.0; /* Get rid of leading 1 */
1863 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1864 f
*= 268435456.0; /* 2**28 */
1865 fhi
= (unsigned int)f
; /* Truncate */
1866 assert(fhi
< 268435456);
1869 f
*= 16777216.0; /* 2**24 */
1870 flo
= (unsigned int)(f
+ 0.5); /* Round */
1871 assert(flo
<= 16777216);
1873 /* The carry propagated out of a string of 24 1 bits. */
1877 /* And it also progagated out of the next 28 bits. */
1886 *p
= (sign
<< 7) | (e
>> 4);
1890 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
1894 *p
= (fhi
>> 16) & 0xFF;
1898 *p
= (fhi
>> 8) & 0xFF;
1906 *p
= (flo
>> 16) & 0xFF;
1910 *p
= (flo
>> 8) & 0xFF;
1921 PyErr_SetString(PyExc_OverflowError
,
1922 "float too large to pack with d format");
1926 const char *s
= (char*)&x
;
1929 if ((double_format
== ieee_little_endian_format
&& !le
)
1930 || (double_format
== ieee_big_endian_format
&& le
)) {
1935 for (i
= 0; i
< 8; i
++) {
1944 _PyFloat_Unpack4(const unsigned char *p
, int le
)
1946 if (float_format
== unknown_format
) {
1959 sign
= (*p
>> 7) & 1;
1960 e
= (*p
& 0x7F) << 1;
1965 f
= (*p
& 0x7F) << 16;
1971 "can't unpack IEEE 754 special value "
1972 "on non-IEEE platform");
1983 x
= (double)f
/ 8388608.0;
1985 /* XXX This sadly ignores Inf/NaN issues */
2002 if ((float_format
== ieee_little_endian_format
&& !le
)
2003 || (float_format
== ieee_big_endian_format
&& le
)) {
2008 for (i
= 0; i
< 4; i
++) {
2022 _PyFloat_Unpack8(const unsigned char *p
, int le
)
2024 if (double_format
== unknown_format
) {
2027 unsigned int fhi
, flo
;
2037 sign
= (*p
>> 7) & 1;
2038 e
= (*p
& 0x7F) << 4;
2043 e
|= (*p
>> 4) & 0xF;
2044 fhi
= (*p
& 0xF) << 24;
2050 "can't unpack IEEE 754 special value "
2051 "on non-IEEE platform");
2078 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2079 x
/= 268435456.0; /* 2**28 */
2097 if ((double_format
== ieee_little_endian_format
&& !le
)
2098 || (double_format
== ieee_big_endian_format
&& le
)) {
2103 for (i
= 0; i
< 8; i
++) {