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. */
11 #if !defined(__STDC__)
12 extern double fmod(double, double);
13 extern double pow(double, double);
16 /* Special free list -- see comments for same code in intobject.c. */
17 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
18 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
19 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
22 struct _floatblock
*next
;
23 PyFloatObject objects
[N_FLOATOBJECTS
];
26 typedef struct _floatblock PyFloatBlock
;
28 static PyFloatBlock
*block_list
= NULL
;
29 static PyFloatObject
*free_list
= NULL
;
31 static PyFloatObject
*
35 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
36 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
38 return (PyFloatObject
*) PyErr_NoMemory();
39 ((PyFloatBlock
*)p
)->next
= block_list
;
40 block_list
= (PyFloatBlock
*)p
;
41 p
= &((PyFloatBlock
*)p
)->objects
[0];
42 q
= p
+ N_FLOATOBJECTS
;
44 q
->ob_type
= (struct _typeobject
*)(q
-1);
46 return p
+ N_FLOATOBJECTS
- 1;
50 PyFloat_FromDouble(double fval
)
52 register PyFloatObject
*op
;
53 if (free_list
== NULL
) {
54 if ((free_list
= fill_free_list()) == NULL
)
57 /* Inline PyObject_New */
59 free_list
= (PyFloatObject
*)op
->ob_type
;
60 PyObject_INIT(op
, &PyFloat_Type
);
62 return (PyObject
*) op
;
65 /**************************************************************************
66 RED_FLAG 22-Sep-2000 tim
67 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
69 1. If v was a regular string, *pend was set to point to its terminating
70 null byte. That's useless (the caller can find that without any
71 help from this function!).
73 2. If v was a Unicode string, or an object convertible to a character
74 buffer, *pend was set to point into stack trash (the auto temp
75 vector holding the character buffer). That was downright dangerous.
77 Since we can't change the interface of a public API function, pend is
78 still supported but now *officially* useless: if pend is not NULL,
80 **************************************************************************/
82 PyFloat_FromString(PyObject
*v
, char **pend
)
84 const char *s
, *last
, *end
;
86 char buffer
[256]; /* for errors */
87 #ifdef Py_USING_UNICODE
88 char s_buffer
[256]; /* for objects convertible to a char buffer */
94 if (PyString_Check(v
)) {
95 s
= PyString_AS_STRING(v
);
96 len
= PyString_GET_SIZE(v
);
98 #ifdef Py_USING_UNICODE
99 else if (PyUnicode_Check(v
)) {
100 if (PyUnicode_GET_SIZE(v
) >= sizeof(s_buffer
)) {
101 PyErr_SetString(PyExc_ValueError
,
102 "Unicode float() literal too long to convert");
105 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
106 PyUnicode_GET_SIZE(v
),
111 len
= (int)strlen(s
);
114 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
115 PyErr_SetString(PyExc_TypeError
,
116 "float() argument must be a string or a number");
121 while (*s
&& isspace(Py_CHARMASK(*s
)))
124 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
127 /* We don't care about overflow or underflow. If the platform supports
128 * them, infinities and signed zeroes (on underflow) are fine.
129 * However, strtod can return 0 for denormalized numbers, where atof
130 * does not. So (alas!) we special-case a zero result. Note that
131 * whether strtod sets errno on underflow is not defined, so we can't
134 PyFPE_START_PROTECT("strtod", return NULL
)
135 x
= PyOS_ascii_strtod(s
, (char **)&end
);
138 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
139 byte at the end of the string, when the input is inf(inity). */
143 PyOS_snprintf(buffer
, sizeof(buffer
),
144 "invalid literal for float(): %.200s", s
);
145 PyErr_SetString(PyExc_ValueError
, buffer
);
148 /* Since end != s, the platform made *some* kind of sense out
149 of the input. Trust it. */
150 while (*end
&& isspace(Py_CHARMASK(*end
)))
153 PyOS_snprintf(buffer
, sizeof(buffer
),
154 "invalid literal for float(): %.200s", s
);
155 PyErr_SetString(PyExc_ValueError
, buffer
);
158 else if (end
!= last
) {
159 PyErr_SetString(PyExc_ValueError
,
160 "null byte in argument for float()");
164 /* See above -- may have been strtod being anal
166 PyFPE_START_PROTECT("atof", return NULL
)
167 x
= PyOS_ascii_atof(s
);
169 errno
= 0; /* whether atof ever set errno is undefined */
171 return PyFloat_FromDouble(x
);
175 float_dealloc(PyFloatObject
*op
)
177 if (PyFloat_CheckExact(op
)) {
178 op
->ob_type
= (struct _typeobject
*)free_list
;
182 op
->ob_type
->tp_free((PyObject
*)op
);
186 PyFloat_AsDouble(PyObject
*op
)
192 if (op
&& PyFloat_Check(op
))
193 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
200 if ((nb
= op
->ob_type
->tp_as_number
) == NULL
|| nb
->nb_float
== NULL
) {
201 PyErr_SetString(PyExc_TypeError
, "a float is required");
205 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
208 if (!PyFloat_Check(fo
)) {
209 PyErr_SetString(PyExc_TypeError
,
210 "nb_float should return float object");
214 val
= PyFloat_AS_DOUBLE(fo
);
223 format_float(char *buf
, size_t buflen
, PyFloatObject
*v
, int precision
)
227 /* Subroutine for float_repr and float_print.
228 We want float numbers to be recognizable as such,
229 i.e., they should contain a decimal point or an exponent.
230 However, %g may print the number as an integer;
231 in such cases, we append ".0" to the string. */
233 assert(PyFloat_Check(v
));
234 PyOS_snprintf(format
, 32, "%%.%ig", precision
);
235 PyOS_ascii_formatd(buf
, buflen
, format
, v
->ob_fval
);
239 for (; *cp
!= '\0'; cp
++) {
240 /* Any non-digit means it's not an integer;
241 this takes care of NAN and INF as well. */
242 if (!isdigit(Py_CHARMASK(*cp
)))
252 /* XXX PyFloat_AsStringEx should not be a public API function (for one
253 XXX thing, its signature passes a buffer without a length; for another,
254 XXX it isn't useful outside this file).
257 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
259 format_float(buf
, 100, v
, precision
);
262 /* Macro and helper that convert PyObject obj to a C double and store
263 the value in dbl; this replaces the functionality of the coercion
264 slot function. If conversion to double raises an exception, obj is
265 set to NULL, and the function invoking this macro returns NULL. If
266 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
267 stored in obj, and returned from the function invoking this macro.
269 #define CONVERT_TO_DOUBLE(obj, dbl) \
270 if (PyFloat_Check(obj)) \
271 dbl = PyFloat_AS_DOUBLE(obj); \
272 else if (convert_to_double(&(obj), &(dbl)) < 0) \
276 convert_to_double(PyObject
**v
, double *dbl
)
278 register PyObject
*obj
= *v
;
280 if (PyInt_Check(obj
)) {
281 *dbl
= (double)PyInt_AS_LONG(obj
);
283 else if (PyLong_Check(obj
)) {
284 *dbl
= PyLong_AsDouble(obj
);
285 if (*dbl
== -1.0 && PyErr_Occurred()) {
291 Py_INCREF(Py_NotImplemented
);
292 *v
= Py_NotImplemented
;
298 /* Precisions used by repr() and str(), respectively.
300 The repr() precision (17 significant decimal digits) is the minimal number
301 that is guaranteed to have enough precision so that if the number is read
302 back in the exact same binary value is recreated. This is true for IEEE
303 floating point by design, and also happens to work for all other modern
306 The str() precision is chosen so that in most cases, the rounding noise
307 created by various operations is suppressed, while giving plenty of
308 precision for practical use.
315 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
316 XXX they pass a char buffer without passing a length.
319 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
321 format_float(buf
, 100, v
, PREC_STR
);
325 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
327 format_float(buf
, 100, v
, PREC_REPR
);
332 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
335 format_float(buf
, sizeof(buf
), v
,
336 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
342 float_repr(PyFloatObject
*v
)
345 format_float(buf
, sizeof(buf
), v
, PREC_REPR
);
346 return PyString_FromString(buf
);
350 float_str(PyFloatObject
*v
)
353 format_float(buf
, sizeof(buf
), v
, PREC_STR
);
354 return PyString_FromString(buf
);
357 /* Comparison is pretty much a nightmare. When comparing float to float,
358 * we do it as straightforwardly (and long-windedly) as conceivable, so
359 * that, e.g., Python x == y delivers the same result as the platform
360 * C x == y when x and/or y is a NaN.
361 * When mixing float with an integer type, there's no good *uniform* approach.
362 * Converting the double to an integer obviously doesn't work, since we
363 * may lose info from fractional bits. Converting the integer to a double
364 * also has two failure modes: (1) a long int may trigger overflow (too
365 * large to fit in the dynamic range of a C double); (2) even a C long may have
366 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
367 * 63 bits of precision, but a C double probably has only 53), and then
368 * we can falsely claim equality when low-order integer bits are lost by
369 * coercion to double. So this part is painful too.
373 float_richcompare(PyObject
*v
, PyObject
*w
, int op
)
378 assert(PyFloat_Check(v
));
379 i
= PyFloat_AS_DOUBLE(v
);
381 /* Switch on the type of w. Set i and j to doubles to be compared,
382 * and op to the richcomp to use.
384 if (PyFloat_Check(w
))
385 j
= PyFloat_AS_DOUBLE(w
);
387 else if (Py_IS_INFINITY(i
) || Py_IS_NAN(i
)) {
388 if (PyInt_Check(w
) || PyLong_Check(w
))
389 /* If i is an infinity, its magnitude exceeds any
390 * finite integer, so it doesn't matter which int we
391 * compare i with. If i is a NaN, similarly.
398 else if (PyInt_Check(w
)) {
399 long jj
= PyInt_AS_LONG(w
);
400 /* In the worst realistic case I can imagine, C double is a
401 * Cray single with 48 bits of precision, and long has 64
405 unsigned long abs
= (unsigned long)(jj
< 0 ? -jj
: jj
);
407 /* Needs more than 48 bits. Make it take the
411 PyObject
*ww
= PyLong_FromLong(jj
);
415 result
= float_richcompare(v
, ww
, op
);
421 assert((long)j
== jj
);
424 else if (PyLong_Check(w
)) {
425 int vsign
= i
== 0.0 ? 0 : i
< 0.0 ? -1 : 1;
426 int wsign
= _PyLong_Sign(w
);
430 if (vsign
!= wsign
) {
431 /* Magnitudes are irrelevant -- the signs alone
432 * determine the outcome.
438 /* The signs are the same. */
439 /* Convert w to a double if it fits. In particular, 0 fits. */
440 nbits
= _PyLong_NumBits(w
);
441 if (nbits
== (size_t)-1 && PyErr_Occurred()) {
442 /* This long is so large that size_t isn't big enough
443 * to hold the # of bits. Replace with little doubles
444 * that give the same outcome -- w is so large that
445 * its magnitude must exceed the magnitude of any
455 j
= PyLong_AsDouble(w
);
456 /* It's impossible that <= 48 bits overflowed. */
457 assert(j
!= -1.0 || ! PyErr_Occurred());
460 assert(wsign
!= 0); /* else nbits was 0 */
461 assert(vsign
!= 0); /* if vsign were 0, then since wsign is
462 * not 0, we would have taken the
463 * vsign != wsign branch at the start */
464 /* We want to work with non-negative numbers. */
466 /* "Multiply both sides" by -1; this also swaps the
470 op
= _Py_SwappedOp
[op
];
473 (void) frexp(i
, &exponent
);
474 /* exponent is the # of bits in v before the radix point;
475 * we know that nbits (the # of bits in w) > 48 at this point
477 if (exponent
< 0 || (size_t)exponent
< nbits
) {
482 if ((size_t)exponent
> nbits
) {
487 /* v and w have the same number of bits before the radix
488 * point. Construct two longs that have the same comparison
494 PyObject
*result
= NULL
;
495 PyObject
*one
= NULL
;
500 ww
= PyNumber_Negative(w
);
507 fracpart
= modf(i
, &intpart
);
508 vv
= PyLong_FromDouble(intpart
);
512 if (fracpart
!= 0.0) {
513 /* Shift left, and or a 1 bit into vv
514 * to represent the lost fraction.
518 one
= PyInt_FromLong(1);
522 temp
= PyNumber_Lshift(ww
, one
);
528 temp
= PyNumber_Lshift(vv
, one
);
534 temp
= PyNumber_Or(vv
, one
);
541 r
= PyObject_RichCompareBool(vv
, ww
, op
);
544 result
= PyBool_FromLong(r
);
551 } /* else if (PyLong_Check(w)) */
553 else /* w isn't float, int, or long */
557 PyFPE_START_PROTECT("richcompare", return NULL
)
579 return PyBool_FromLong(r
);
582 Py_INCREF(Py_NotImplemented
);
583 return Py_NotImplemented
;
587 float_hash(PyFloatObject
*v
)
589 return _Py_HashDouble(v
->ob_fval
);
593 float_add(PyObject
*v
, PyObject
*w
)
596 CONVERT_TO_DOUBLE(v
, a
);
597 CONVERT_TO_DOUBLE(w
, b
);
598 PyFPE_START_PROTECT("add", return 0)
601 return PyFloat_FromDouble(a
);
605 float_sub(PyObject
*v
, PyObject
*w
)
608 CONVERT_TO_DOUBLE(v
, a
);
609 CONVERT_TO_DOUBLE(w
, b
);
610 PyFPE_START_PROTECT("subtract", return 0)
613 return PyFloat_FromDouble(a
);
617 float_mul(PyObject
*v
, PyObject
*w
)
620 CONVERT_TO_DOUBLE(v
, a
);
621 CONVERT_TO_DOUBLE(w
, b
);
622 PyFPE_START_PROTECT("multiply", return 0)
625 return PyFloat_FromDouble(a
);
629 float_div(PyObject
*v
, PyObject
*w
)
632 CONVERT_TO_DOUBLE(v
, a
);
633 CONVERT_TO_DOUBLE(w
, b
);
635 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
638 PyFPE_START_PROTECT("divide", return 0)
641 return PyFloat_FromDouble(a
);
645 float_classic_div(PyObject
*v
, PyObject
*w
)
648 CONVERT_TO_DOUBLE(v
, a
);
649 CONVERT_TO_DOUBLE(w
, b
);
650 if (Py_DivisionWarningFlag
>= 2 &&
651 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
654 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
657 PyFPE_START_PROTECT("divide", return 0)
660 return PyFloat_FromDouble(a
);
664 float_rem(PyObject
*v
, PyObject
*w
)
668 CONVERT_TO_DOUBLE(v
, vx
);
669 CONVERT_TO_DOUBLE(w
, wx
);
671 PyErr_SetString(PyExc_ZeroDivisionError
, "float modulo");
674 PyFPE_START_PROTECT("modulo", return 0)
676 /* note: checking mod*wx < 0 is incorrect -- underflows to
677 0 if wx < sqrt(smallest nonzero double) */
678 if (mod
&& ((wx
< 0) != (mod
< 0))) {
681 PyFPE_END_PROTECT(mod
)
682 return PyFloat_FromDouble(mod
);
686 float_divmod(PyObject
*v
, PyObject
*w
)
689 double div
, mod
, floordiv
;
690 CONVERT_TO_DOUBLE(v
, vx
);
691 CONVERT_TO_DOUBLE(w
, wx
);
693 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
696 PyFPE_START_PROTECT("divmod", return 0)
698 /* fmod is typically exact, so vx-mod is *mathematically* an
699 exact multiple of wx. But this is fp arithmetic, and fp
700 vx - mod is an approximation; the result is that div may
701 not be an exact integral value after the division, although
702 it will always be very close to one.
704 div
= (vx
- mod
) / wx
;
706 /* ensure the remainder has the same sign as the denominator */
707 if ((wx
< 0) != (mod
< 0)) {
713 /* the remainder is zero, and in the presence of signed zeroes
714 fmod returns different results across platforms; ensure
715 it has the same sign as the denominator; we'd like to do
716 "mod = wx * 0.0", but that may get optimized away */
717 mod
*= mod
; /* hide "mod = +0" from optimizer */
721 /* snap quotient to nearest integral value */
723 floordiv
= floor(div
);
724 if (div
- floordiv
> 0.5)
728 /* div is zero - get the same sign as the true quotient */
729 div
*= div
; /* hide "div = +0" from optimizers */
730 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
732 PyFPE_END_PROTECT(floordiv
)
733 return Py_BuildValue("(dd)", floordiv
, mod
);
737 float_floor_div(PyObject
*v
, PyObject
*w
)
741 t
= float_divmod(v
, w
);
742 if (t
== NULL
|| t
== Py_NotImplemented
)
744 assert(PyTuple_CheckExact(t
));
745 r
= PyTuple_GET_ITEM(t
, 0);
752 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
756 if ((PyObject
*)z
!= Py_None
) {
757 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
758 "allowed unless all arguments are integers");
762 CONVERT_TO_DOUBLE(v
, iv
);
763 CONVERT_TO_DOUBLE(w
, iw
);
765 /* Sort out special cases here instead of relying on pow() */
766 if (iw
== 0) { /* v**0 is 1, even 0**0 */
767 PyFPE_START_PROTECT("pow", return NULL
)
768 if ((PyObject
*)z
!= Py_None
) {
770 CONVERT_TO_DOUBLE(z
, iz
);
772 if (ix
!= 0 && iz
< 0)
777 PyFPE_END_PROTECT(ix
)
778 return PyFloat_FromDouble(ix
);
780 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
782 PyErr_SetString(PyExc_ZeroDivisionError
,
783 "0.0 cannot be raised to a negative power");
786 return PyFloat_FromDouble(0.0);
789 /* Whether this is an error is a mess, and bumps into libm
790 * bugs so we have to figure it out ourselves.
792 if (iw
!= floor(iw
)) {
793 PyErr_SetString(PyExc_ValueError
, "negative number "
794 "cannot be raised to a fractional power");
797 /* iw is an exact integer, albeit perhaps a very large one.
798 * -1 raised to an exact integer should never be exceptional.
799 * Alas, some libms (chiefly glibc as of early 2003) return
800 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
801 * happen to be representable in a *C* integer. That's a
802 * bug; we let that slide in math.pow() (which currently
803 * reflects all platform accidents), but not for Python's **.
805 if (iv
== -1.0 && !Py_IS_INFINITY(iw
) && iw
== iw
) {
806 /* XXX the "iw == iw" was to weed out NaNs. This
807 * XXX doesn't actually work on all platforms.
809 /* Return 1 if iw is even, -1 if iw is odd; there's
810 * no guarantee that any C integral type is big
811 * enough to hold iw, so we have to check this
814 ix
= floor(iw
* 0.5) * 2.0;
815 return PyFloat_FromDouble(ix
== iw
? 1.0 : -1.0);
817 /* Else iv != -1.0, and overflow or underflow are possible.
818 * Unless we're to write pow() ourselves, we have to trust
819 * the platform to do this correctly.
823 PyFPE_START_PROTECT("pow", return NULL
)
825 PyFPE_END_PROTECT(ix
)
826 Py_ADJUST_ERANGE1(ix
);
828 /* We don't expect any errno value other than ERANGE, but
829 * the range of libm bugs appears unbounded.
831 PyErr_SetFromErrno(errno
== ERANGE
? PyExc_OverflowError
:
835 return PyFloat_FromDouble(ix
);
839 float_neg(PyFloatObject
*v
)
841 return PyFloat_FromDouble(-v
->ob_fval
);
845 float_pos(PyFloatObject
*v
)
847 if (PyFloat_CheckExact(v
)) {
849 return (PyObject
*)v
;
852 return PyFloat_FromDouble(v
->ob_fval
);
856 float_abs(PyFloatObject
*v
)
858 return PyFloat_FromDouble(fabs(v
->ob_fval
));
862 float_nonzero(PyFloatObject
*v
)
864 return v
->ob_fval
!= 0.0;
868 float_coerce(PyObject
**pv
, PyObject
**pw
)
870 if (PyInt_Check(*pw
)) {
871 long x
= PyInt_AsLong(*pw
);
872 *pw
= PyFloat_FromDouble((double)x
);
876 else if (PyLong_Check(*pw
)) {
877 double x
= PyLong_AsDouble(*pw
);
878 if (x
== -1.0 && PyErr_Occurred())
880 *pw
= PyFloat_FromDouble(x
);
884 else if (PyFloat_Check(*pw
)) {
889 return 1; /* Can't do it */
893 float_long(PyObject
*v
)
895 double x
= PyFloat_AsDouble(v
);
896 return PyLong_FromDouble(x
);
900 float_int(PyObject
*v
)
902 double x
= PyFloat_AsDouble(v
);
903 double wholepart
; /* integral portion of x, rounded toward 0 */
905 (void)modf(x
, &wholepart
);
906 /* Try to get out cheap if this fits in a Python int. The attempt
907 * to cast to long must be protected, as C doesn't define what
908 * happens if the double is too big to fit in a long. Some rare
909 * systems raise an exception then (RISCOS was mentioned as one,
910 * and someone using a non-default option on Sun also bumped into
911 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
912 * still be vulnerable: if a long has more bits of precision than
913 * a double, casting MIN/MAX to double may yield an approximation,
914 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
915 * yield true from the C expression wholepart<=LONG_MAX, despite
916 * that wholepart is actually greater than LONG_MAX.
918 if (LONG_MIN
< wholepart
&& wholepart
< LONG_MAX
) {
919 const long aslong
= (long)wholepart
;
920 return PyInt_FromLong(aslong
);
922 return PyLong_FromDouble(wholepart
);
926 float_float(PyObject
*v
)
928 if (PyFloat_CheckExact(v
))
931 v
= PyFloat_FromDouble(((PyFloatObject
*)v
)->ob_fval
);
937 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
940 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
942 PyObject
*x
= Py_False
; /* Integer zero */
943 static const char *kwlist
[] = {"x", 0};
945 if (type
!= &PyFloat_Type
)
946 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
947 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
949 if (PyString_Check(x
))
950 return PyFloat_FromString(x
, NULL
);
951 return PyNumber_Float(x
);
954 /* Wimpy, slow approach to tp_new calls for subtypes of float:
955 first create a regular float from whatever arguments we got,
956 then allocate a subtype instance and initialize its ob_fval
957 from the regular float. The regular float is then thrown away.
960 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
964 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
965 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
968 assert(PyFloat_CheckExact(tmp
));
969 new = type
->tp_alloc(type
, 0);
974 ((PyFloatObject
*)new)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
980 float_getnewargs(PyFloatObject
*v
)
982 return Py_BuildValue("(d)", v
->ob_fval
);
985 /* this is for the benefit of the pack/unpack routines below */
988 unknown_format
, ieee_big_endian_format
, ieee_little_endian_format
991 static float_format_type double_format
, float_format
;
992 static float_format_type detected_double_format
, detected_float_format
;
995 float_getformat(PyTypeObject
*v
, PyObject
* arg
)
1000 if (!PyString_Check(arg
)) {
1001 PyErr_Format(PyExc_TypeError
,
1002 "__getformat__() argument must be string, not %.500s",
1003 arg
->ob_type
->tp_name
);
1006 s
= PyString_AS_STRING(arg
);
1007 if (strcmp(s
, "double") == 0) {
1010 else if (strcmp(s
, "float") == 0) {
1014 PyErr_SetString(PyExc_ValueError
,
1015 "__getformat__() argument 1 must be "
1016 "'double' or 'float'");
1021 case unknown_format
:
1022 return PyString_FromString("unknown");
1023 case ieee_little_endian_format
:
1024 return PyString_FromString("IEEE, little-endian");
1025 case ieee_big_endian_format
:
1026 return PyString_FromString("IEEE, big-endian");
1028 Py_FatalError("insane float_format or double_format");
1033 PyDoc_STRVAR(float_getformat_doc
,
1034 "float.__getformat__(typestr) -> string\n"
1036 "You probably don't want to use this function. It exists mainly to be\n"
1037 "used in Python's test suite.\n"
1039 "typestr must be 'double' or 'float'. This function returns whichever of\n"
1040 "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1041 "format of floating point numbers used by the C type named by typestr.");
1044 float_setformat(PyTypeObject
*v
, PyObject
* args
)
1048 float_format_type f
;
1049 float_format_type detected
;
1050 float_format_type
*p
;
1052 if (!PyArg_ParseTuple(args
, "ss:__setformat__", &typestr
, &format
))
1055 if (strcmp(typestr
, "double") == 0) {
1057 detected
= detected_double_format
;
1059 else if (strcmp(typestr
, "float") == 0) {
1061 detected
= detected_float_format
;
1064 PyErr_SetString(PyExc_ValueError
,
1065 "__setformat__() argument 1 must "
1066 "be 'double' or 'float'");
1070 if (strcmp(format
, "unknown") == 0) {
1073 else if (strcmp(format
, "IEEE, little-endian") == 0) {
1074 f
= ieee_little_endian_format
;
1076 else if (strcmp(format
, "IEEE, big-endian") == 0) {
1077 f
= ieee_big_endian_format
;
1080 PyErr_SetString(PyExc_ValueError
,
1081 "__setformat__() argument 2 must be "
1082 "'unknown', 'IEEE, little-endian' or "
1083 "'IEEE, big-endian'");
1088 if (f
!= unknown_format
&& f
!= detected
) {
1089 PyErr_Format(PyExc_ValueError
,
1090 "can only set %s format to 'unknown' or the "
1091 "detected platform value", typestr
);
1099 PyDoc_STRVAR(float_setformat_doc
,
1100 "float.__setformat__(typestr, fmt) -> None\n"
1102 "You probably don't want to use this function. It exists mainly to be\n"
1103 "used in Python's test suite.\n"
1105 "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1106 "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1107 "one of the latter two if it appears to match the underlying C reality.\n"
1109 "Overrides the automatic determination of C-level floating point type.\n"
1110 "This affects how floats are converted to and from binary strings.");
1112 static PyMethodDef float_methods
[] = {
1113 {"__getnewargs__", (PyCFunction
)float_getnewargs
, METH_NOARGS
},
1114 {"__getformat__", (PyCFunction
)float_getformat
,
1115 METH_O
|METH_CLASS
, float_getformat_doc
},
1116 {"__setformat__", (PyCFunction
)float_setformat
,
1117 METH_VARARGS
|METH_CLASS
, float_setformat_doc
},
1118 {NULL
, NULL
} /* sentinel */
1121 PyDoc_STRVAR(float_doc
,
1122 "float(x) -> floating point number\n\
1124 Convert a string or number to a floating point number, if possible.");
1127 static PyNumberMethods float_as_number
= {
1128 (binaryfunc
)float_add
, /*nb_add*/
1129 (binaryfunc
)float_sub
, /*nb_subtract*/
1130 (binaryfunc
)float_mul
, /*nb_multiply*/
1131 (binaryfunc
)float_classic_div
, /*nb_divide*/
1132 (binaryfunc
)float_rem
, /*nb_remainder*/
1133 (binaryfunc
)float_divmod
, /*nb_divmod*/
1134 (ternaryfunc
)float_pow
, /*nb_power*/
1135 (unaryfunc
)float_neg
, /*nb_negative*/
1136 (unaryfunc
)float_pos
, /*nb_positive*/
1137 (unaryfunc
)float_abs
, /*nb_absolute*/
1138 (inquiry
)float_nonzero
, /*nb_nonzero*/
1145 (coercion
)float_coerce
, /*nb_coerce*/
1146 (unaryfunc
)float_int
, /*nb_int*/
1147 (unaryfunc
)float_long
, /*nb_long*/
1148 (unaryfunc
)float_float
, /*nb_float*/
1151 0, /* nb_inplace_add */
1152 0, /* nb_inplace_subtract */
1153 0, /* nb_inplace_multiply */
1154 0, /* nb_inplace_divide */
1155 0, /* nb_inplace_remainder */
1156 0, /* nb_inplace_power */
1157 0, /* nb_inplace_lshift */
1158 0, /* nb_inplace_rshift */
1159 0, /* nb_inplace_and */
1160 0, /* nb_inplace_xor */
1161 0, /* nb_inplace_or */
1162 float_floor_div
, /* nb_floor_divide */
1163 float_div
, /* nb_true_divide */
1164 0, /* nb_inplace_floor_divide */
1165 0, /* nb_inplace_true_divide */
1168 PyTypeObject PyFloat_Type
= {
1169 PyObject_HEAD_INIT(&PyType_Type
)
1172 sizeof(PyFloatObject
),
1174 (destructor
)float_dealloc
, /* tp_dealloc */
1175 (printfunc
)float_print
, /* tp_print */
1179 (reprfunc
)float_repr
, /* tp_repr */
1180 &float_as_number
, /* tp_as_number */
1181 0, /* tp_as_sequence */
1182 0, /* tp_as_mapping */
1183 (hashfunc
)float_hash
, /* tp_hash */
1185 (reprfunc
)float_str
, /* tp_str */
1186 PyObject_GenericGetAttr
, /* tp_getattro */
1187 0, /* tp_setattro */
1188 0, /* tp_as_buffer */
1189 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
1190 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1191 float_doc
, /* tp_doc */
1192 0, /* tp_traverse */
1194 (richcmpfunc
)float_richcompare
, /* tp_richcompare */
1195 0, /* tp_weaklistoffset */
1197 0, /* tp_iternext */
1198 float_methods
, /* tp_methods */
1203 0, /* tp_descr_get */
1204 0, /* tp_descr_set */
1205 0, /* tp_dictoffset */
1208 float_new
, /* tp_new */
1214 /* We attempt to determine if this machine is using IEEE
1215 floating point formats by peering at the bits of some
1216 carefully chosen values. If it looks like we are on an
1217 IEEE platform, the float packing/unpacking routines can
1218 just copy bits, if not they resort to arithmetic & shifts
1219 and masks. The shifts & masks approach works on all finite
1220 values, but what happens to infinities, NaNs and signed
1221 zeroes on packing is an accident, and attempting to unpack
1222 a NaN or an infinity will raise an exception.
1224 Note that if we're on some whacked-out platform which uses
1225 IEEE formats but isn't strictly little-endian or big-
1226 endian, we will fall back to the portable shifts & masks
1229 #if SIZEOF_DOUBLE == 8
1231 double x
= 9006104071832581.0;
1232 if (memcmp(&x
, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1233 detected_double_format
= ieee_big_endian_format
;
1234 else if (memcmp(&x
, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1235 detected_double_format
= ieee_little_endian_format
;
1237 detected_double_format
= unknown_format
;
1240 detected_double_format
= unknown_format
;
1243 #if SIZEOF_FLOAT == 4
1245 float y
= 16711938.0;
1246 if (memcmp(&y
, "\x4b\x7f\x01\x02", 4) == 0)
1247 detected_float_format
= ieee_big_endian_format
;
1248 else if (memcmp(&y
, "\x02\x01\x7f\x4b", 4) == 0)
1249 detected_float_format
= ieee_little_endian_format
;
1251 detected_float_format
= unknown_format
;
1254 detected_float_format
= unknown_format
;
1257 double_format
= detected_double_format
;
1258 float_format
= detected_float_format
;
1265 PyFloatBlock
*list
, *next
;
1267 int bc
, bf
; /* block count, number of freed blocks */
1268 int frem
, fsum
; /* remaining unfreed floats per block, total */
1276 while (list
!= NULL
) {
1279 for (i
= 0, p
= &list
->objects
[0];
1282 if (PyFloat_CheckExact(p
) && p
->ob_refcnt
!= 0)
1287 list
->next
= block_list
;
1289 for (i
= 0, p
= &list
->objects
[0];
1292 if (!PyFloat_CheckExact(p
) ||
1293 p
->ob_refcnt
== 0) {
1294 p
->ob_type
= (struct _typeobject
*)
1301 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
1307 if (!Py_VerboseFlag
)
1309 fprintf(stderr
, "# cleanup floats");
1311 fprintf(stderr
, "\n");
1315 ": %d unfreed float%s in %d out of %d block%s\n",
1316 fsum
, fsum
== 1 ? "" : "s",
1317 bc
- bf
, bc
, bc
== 1 ? "" : "s");
1319 if (Py_VerboseFlag
> 1) {
1321 while (list
!= NULL
) {
1322 for (i
= 0, p
= &list
->objects
[0];
1325 if (PyFloat_CheckExact(p
) &&
1326 p
->ob_refcnt
!= 0) {
1328 PyFloat_AsString(buf
, p
);
1330 "# <float at %p, refcnt=%d, val=%s>\n",
1331 p
, p
->ob_refcnt
, buf
);
1339 /*----------------------------------------------------------------------------
1340 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1342 * TODO: On platforms that use the standard IEEE-754 single and double
1343 * formats natively, these routines could simply copy the bytes.
1346 _PyFloat_Pack4(double x
, unsigned char *p
, int le
)
1348 if (float_format
== unknown_format
) {
1369 /* Normalize f to be in the range [1.0, 2.0) */
1370 if (0.5 <= f
&& f
< 1.0) {
1377 PyErr_SetString(PyExc_SystemError
,
1378 "frexp() result out of range");
1384 else if (e
< -126) {
1385 /* Gradual underflow */
1386 f
= ldexp(f
, 126 + e
);
1389 else if (!(e
== 0 && f
== 0.0)) {
1391 f
-= 1.0; /* Get rid of leading 1 */
1394 f
*= 8388608.0; /* 2**23 */
1395 fbits
= (unsigned int)(f
+ 0.5); /* Round */
1396 assert(fbits
<= 8388608);
1398 /* The carry propagated out of a string of 23 1 bits. */
1406 *p
= (sign
<< 7) | (e
>> 1);
1410 *p
= (char) (((e
& 1) << 7) | (fbits
>> 16));
1414 *p
= (fbits
>> 8) & 0xFF;
1424 PyErr_SetString(PyExc_OverflowError
,
1425 "float too large to pack with f format");
1430 const char *s
= (char*)&y
;
1433 if ((float_format
== ieee_little_endian_format
&& !le
)
1434 || (float_format
== ieee_big_endian_format
&& le
)) {
1439 for (i
= 0; i
< 4; i
++) {
1448 _PyFloat_Pack8(double x
, unsigned char *p
, int le
)
1450 if (double_format
== unknown_format
) {
1454 unsigned int fhi
, flo
;
1471 /* Normalize f to be in the range [1.0, 2.0) */
1472 if (0.5 <= f
&& f
< 1.0) {
1479 PyErr_SetString(PyExc_SystemError
,
1480 "frexp() result out of range");
1486 else if (e
< -1022) {
1487 /* Gradual underflow */
1488 f
= ldexp(f
, 1022 + e
);
1491 else if (!(e
== 0 && f
== 0.0)) {
1493 f
-= 1.0; /* Get rid of leading 1 */
1496 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1497 f
*= 268435456.0; /* 2**28 */
1498 fhi
= (unsigned int)f
; /* Truncate */
1499 assert(fhi
< 268435456);
1502 f
*= 16777216.0; /* 2**24 */
1503 flo
= (unsigned int)(f
+ 0.5); /* Round */
1504 assert(flo
<= 16777216);
1506 /* The carry propagated out of a string of 24 1 bits. */
1510 /* And it also progagated out of the next 28 bits. */
1519 *p
= (sign
<< 7) | (e
>> 4);
1523 *p
= (unsigned char) (((e
& 0xF) << 4) | (fhi
>> 24));
1527 *p
= (fhi
>> 16) & 0xFF;
1531 *p
= (fhi
>> 8) & 0xFF;
1539 *p
= (flo
>> 16) & 0xFF;
1543 *p
= (flo
>> 8) & 0xFF;
1554 PyErr_SetString(PyExc_OverflowError
,
1555 "float too large to pack with d format");
1559 const char *s
= (char*)&x
;
1562 if ((double_format
== ieee_little_endian_format
&& !le
)
1563 || (double_format
== ieee_big_endian_format
&& le
)) {
1568 for (i
= 0; i
< 8; i
++) {
1577 _PyFloat_Unpack4(const unsigned char *p
, int le
)
1579 if (float_format
== unknown_format
) {
1592 sign
= (*p
>> 7) & 1;
1593 e
= (*p
& 0x7F) << 1;
1598 f
= (*p
& 0x7F) << 16;
1604 "can't unpack IEEE 754 special value "
1605 "on non-IEEE platform");
1616 x
= (double)f
/ 8388608.0;
1618 /* XXX This sadly ignores Inf/NaN issues */
1635 if ((float_format
== ieee_little_endian_format
&& !le
)
1636 || (float_format
== ieee_big_endian_format
&& le
)) {
1641 for (i
= 0; i
< 4; i
++) {
1655 _PyFloat_Unpack8(const unsigned char *p
, int le
)
1657 if (double_format
== unknown_format
) {
1660 unsigned int fhi
, flo
;
1670 sign
= (*p
>> 7) & 1;
1671 e
= (*p
& 0x7F) << 4;
1676 e
|= (*p
>> 4) & 0xF;
1677 fhi
= (*p
& 0xF) << 24;
1683 "can't unpack IEEE 754 special value "
1684 "on non-IEEE platform");
1711 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
1712 x
/= 268435456.0; /* 2**28 */
1730 if ((double_format
== ieee_little_endian_format
&& !le
)
1731 || (double_format
== ieee_big_endian_format
&& le
)) {
1736 for (i
= 0; i
< 8; i
++) {