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__) && !defined(macintosh)
12 extern double fmod(double, double);
13 extern double pow(double, double);
16 #if defined(sun) && !defined(__SVR4)
17 /* On SunOS4.1 only libm.a exists. Make sure that references to all
18 needed math functions exist in the executable, so that dynamic
19 loading of mathmodule does not fail. */
20 double (*_Py_math_funcs_hack
[])() = {
21 acos
, asin
, atan
, atan2
, ceil
, cos
, cosh
, exp
, fabs
, floor
,
22 fmod
, log
, log10
, pow
, sin
, sinh
, sqrt
, tan
, tanh
26 /* Special free list -- see comments for same code in intobject.c. */
27 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
28 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
29 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
32 struct _floatblock
*next
;
33 PyFloatObject objects
[N_FLOATOBJECTS
];
36 typedef struct _floatblock PyFloatBlock
;
38 static PyFloatBlock
*block_list
= NULL
;
39 static PyFloatObject
*free_list
= NULL
;
41 static PyFloatObject
*
45 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
46 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
48 return (PyFloatObject
*) PyErr_NoMemory();
49 ((PyFloatBlock
*)p
)->next
= block_list
;
50 block_list
= (PyFloatBlock
*)p
;
51 p
= &((PyFloatBlock
*)p
)->objects
[0];
52 q
= p
+ N_FLOATOBJECTS
;
54 q
->ob_type
= (struct _typeobject
*)(q
-1);
56 return p
+ N_FLOATOBJECTS
- 1;
60 PyFloat_FromDouble(double fval
)
62 register PyFloatObject
*op
;
63 if (free_list
== NULL
) {
64 if ((free_list
= fill_free_list()) == NULL
)
67 /* PyObject_New is inlined */
69 free_list
= (PyFloatObject
*)op
->ob_type
;
70 PyObject_INIT(op
, &PyFloat_Type
);
72 return (PyObject
*) op
;
75 /**************************************************************************
76 RED_FLAG 22-Sep-2000 tim
77 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
79 1. If v was a regular string, *pend was set to point to its terminating
80 null byte. That's useless (the caller can find that without any
81 help from this function!).
83 2. If v was a Unicode string, or an object convertible to a character
84 buffer, *pend was set to point into stack trash (the auto temp
85 vector holding the character buffer). That was downright dangerous.
87 Since we can't change the interface of a public API function, pend is
88 still supported but now *officially* useless: if pend is not NULL,
90 **************************************************************************/
92 PyFloat_FromString(PyObject
*v
, char **pend
)
94 const char *s
, *last
, *end
;
96 char buffer
[256]; /* for errors */
97 #ifdef Py_USING_UNICODE
98 char s_buffer
[256]; /* for objects convertible to a char buffer */
104 if (PyString_Check(v
)) {
105 s
= PyString_AS_STRING(v
);
106 len
= PyString_GET_SIZE(v
);
108 #ifdef Py_USING_UNICODE
109 else if (PyUnicode_Check(v
)) {
110 if (PyUnicode_GET_SIZE(v
) >= sizeof(s_buffer
)) {
111 PyErr_SetString(PyExc_ValueError
,
112 "Unicode float() literal too long to convert");
115 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
116 PyUnicode_GET_SIZE(v
),
121 len
= (int)strlen(s
);
124 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
125 PyErr_SetString(PyExc_TypeError
,
126 "float() needs a string argument");
131 while (*s
&& isspace(Py_CHARMASK(*s
)))
134 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
137 /* We don't care about overflow or underflow. If the platform supports
138 * them, infinities and signed zeroes (on underflow) are fine.
139 * However, strtod can return 0 for denormalized numbers, where atof
140 * does not. So (alas!) we special-case a zero result. Note that
141 * whether strtod sets errno on underflow is not defined, so we can't
144 PyFPE_START_PROTECT("strtod", return NULL
)
145 x
= strtod(s
, (char **)&end
);
148 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
149 byte at the end of the string, when the input is inf(inity). */
153 PyOS_snprintf(buffer
, sizeof(buffer
),
154 "invalid literal for float(): %.200s", s
);
155 PyErr_SetString(PyExc_ValueError
, buffer
);
158 /* Since end != s, the platform made *some* kind of sense out
159 of the input. Trust it. */
160 while (*end
&& isspace(Py_CHARMASK(*end
)))
163 PyOS_snprintf(buffer
, sizeof(buffer
),
164 "invalid literal for float(): %.200s", s
);
165 PyErr_SetString(PyExc_ValueError
, buffer
);
168 else if (end
!= last
) {
169 PyErr_SetString(PyExc_ValueError
,
170 "null byte in argument for float()");
174 /* See above -- may have been strtod being anal
176 PyFPE_START_PROTECT("atof", return NULL
)
179 errno
= 0; /* whether atof ever set errno is undefined */
181 return PyFloat_FromDouble(x
);
185 float_dealloc(PyFloatObject
*op
)
187 if (PyFloat_CheckExact(op
)) {
188 op
->ob_type
= (struct _typeobject
*)free_list
;
192 op
->ob_type
->tp_free((PyObject
*)op
);
196 PyFloat_AsDouble(PyObject
*op
)
202 if (op
&& PyFloat_Check(op
))
203 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
205 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
206 nb
->nb_float
== NULL
) {
211 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
214 if (!PyFloat_Check(fo
)) {
215 PyErr_SetString(PyExc_TypeError
,
216 "nb_float should return float object");
220 val
= PyFloat_AS_DOUBLE(fo
);
229 format_float(char *buf
, size_t buflen
, PyFloatObject
*v
, int precision
)
232 /* Subroutine for float_repr and float_print.
233 We want float numbers to be recognizable as such,
234 i.e., they should contain a decimal point or an exponent.
235 However, %g may print the number as an integer;
236 in such cases, we append ".0" to the string. */
238 assert(PyFloat_Check(v
));
239 PyOS_snprintf(buf
, buflen
, "%.*g", precision
, v
->ob_fval
);
243 for (; *cp
!= '\0'; cp
++) {
244 /* Any non-digit means it's not an integer;
245 this takes care of NAN and INF as well. */
246 if (!isdigit(Py_CHARMASK(*cp
)))
256 /* XXX PyFloat_AsStringEx should not be a public API function (for one
257 XXX thing, its signature passes a buffer without a length; for another,
258 XXX it isn't useful outside this file).
261 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
263 format_float(buf
, 100, v
, precision
);
266 /* Macro and helper that convert PyObject obj to a C double and store
267 the value in dbl; this replaces the functionality of the coercion
268 slot function. If conversion to double raises an exception, obj is
269 set to NULL, and the function invoking this macro returns NULL. If
270 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
271 stored in obj, and returned from the function invoking this macro.
273 #define CONVERT_TO_DOUBLE(obj, dbl) \
274 if (PyFloat_Check(obj)) \
275 dbl = PyFloat_AS_DOUBLE(obj); \
276 else if (convert_to_double(&(obj), &(dbl)) < 0) \
280 convert_to_double(PyObject
**v
, double *dbl
)
282 register PyObject
*obj
= *v
;
284 if (PyInt_Check(obj
)) {
285 *dbl
= (double)PyInt_AS_LONG(obj
);
287 else if (PyLong_Check(obj
)) {
288 *dbl
= PyLong_AsDouble(obj
);
289 if (*dbl
== -1.0 && PyErr_Occurred()) {
295 Py_INCREF(Py_NotImplemented
);
296 *v
= Py_NotImplemented
;
302 /* Precisions used by repr() and str(), respectively.
304 The repr() precision (17 significant decimal digits) is the minimal number
305 that is guaranteed to have enough precision so that if the number is read
306 back in the exact same binary value is recreated. This is true for IEEE
307 floating point by design, and also happens to work for all other modern
310 The str() precision is chosen so that in most cases, the rounding noise
311 created by various operations is suppressed, while giving plenty of
312 precision for practical use.
319 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
320 XXX they pass a char buffer without passing a length.
323 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
325 format_float(buf
, 100, v
, PREC_STR
);
329 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
331 format_float(buf
, 100, v
, PREC_REPR
);
336 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
339 format_float(buf
, sizeof(buf
), v
,
340 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
346 float_repr(PyFloatObject
*v
)
349 format_float(buf
, sizeof(buf
), v
, PREC_REPR
);
350 return PyString_FromString(buf
);
354 float_str(PyFloatObject
*v
)
357 format_float(buf
, sizeof(buf
), v
, PREC_STR
);
358 return PyString_FromString(buf
);
362 float_compare(PyFloatObject
*v
, PyFloatObject
*w
)
364 double i
= v
->ob_fval
;
365 double j
= w
->ob_fval
;
366 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
370 float_hash(PyFloatObject
*v
)
372 return _Py_HashDouble(v
->ob_fval
);
376 float_add(PyObject
*v
, PyObject
*w
)
379 CONVERT_TO_DOUBLE(v
, a
);
380 CONVERT_TO_DOUBLE(w
, b
);
381 PyFPE_START_PROTECT("add", return 0)
384 return PyFloat_FromDouble(a
);
388 float_sub(PyObject
*v
, PyObject
*w
)
391 CONVERT_TO_DOUBLE(v
, a
);
392 CONVERT_TO_DOUBLE(w
, b
);
393 PyFPE_START_PROTECT("subtract", return 0)
396 return PyFloat_FromDouble(a
);
400 float_mul(PyObject
*v
, PyObject
*w
)
403 CONVERT_TO_DOUBLE(v
, a
);
404 CONVERT_TO_DOUBLE(w
, b
);
405 PyFPE_START_PROTECT("multiply", return 0)
408 return PyFloat_FromDouble(a
);
412 float_div(PyObject
*v
, PyObject
*w
)
415 CONVERT_TO_DOUBLE(v
, a
);
416 CONVERT_TO_DOUBLE(w
, b
);
418 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
421 PyFPE_START_PROTECT("divide", return 0)
424 return PyFloat_FromDouble(a
);
428 float_classic_div(PyObject
*v
, PyObject
*w
)
431 CONVERT_TO_DOUBLE(v
, a
);
432 CONVERT_TO_DOUBLE(w
, b
);
433 if (Py_DivisionWarningFlag
>= 2 &&
434 PyErr_Warn(PyExc_DeprecationWarning
, "classic float division") < 0)
437 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
440 PyFPE_START_PROTECT("divide", return 0)
443 return PyFloat_FromDouble(a
);
447 float_rem(PyObject
*v
, PyObject
*w
)
451 CONVERT_TO_DOUBLE(v
, vx
);
452 CONVERT_TO_DOUBLE(w
, wx
);
454 PyErr_SetString(PyExc_ZeroDivisionError
, "float modulo");
457 PyFPE_START_PROTECT("modulo", return 0)
459 /* note: checking mod*wx < 0 is incorrect -- underflows to
460 0 if wx < sqrt(smallest nonzero double) */
461 if (mod
&& ((wx
< 0) != (mod
< 0))) {
464 PyFPE_END_PROTECT(mod
)
465 return PyFloat_FromDouble(mod
);
469 float_divmod(PyObject
*v
, PyObject
*w
)
472 double div
, mod
, floordiv
;
473 CONVERT_TO_DOUBLE(v
, vx
);
474 CONVERT_TO_DOUBLE(w
, wx
);
476 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
479 PyFPE_START_PROTECT("divmod", return 0)
481 /* fmod is typically exact, so vx-mod is *mathematically* an
482 exact multiple of wx. But this is fp arithmetic, and fp
483 vx - mod is an approximation; the result is that div may
484 not be an exact integral value after the division, although
485 it will always be very close to one.
487 div
= (vx
- mod
) / wx
;
489 /* ensure the remainder has the same sign as the denominator */
490 if ((wx
< 0) != (mod
< 0)) {
496 /* the remainder is zero, and in the presence of signed zeroes
497 fmod returns different results across platforms; ensure
498 it has the same sign as the denominator; we'd like to do
499 "mod = wx * 0.0", but that may get optimized away */
500 mod
*= mod
; /* hide "mod = +0" from optimizer */
504 /* snap quotient to nearest integral value */
506 floordiv
= floor(div
);
507 if (div
- floordiv
> 0.5)
511 /* div is zero - get the same sign as the true quotient */
512 div
*= div
; /* hide "div = +0" from optimizers */
513 floordiv
= div
* vx
/ wx
; /* zero w/ sign of vx/wx */
515 PyFPE_END_PROTECT(floordiv
)
516 return Py_BuildValue("(dd)", floordiv
, mod
);
520 float_floor_div(PyObject
*v
, PyObject
*w
)
524 t
= float_divmod(v
, w
);
525 if (t
== NULL
|| t
== Py_NotImplemented
)
527 assert(PyTuple_CheckExact(t
));
528 r
= PyTuple_GET_ITEM(t
, 0);
535 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
539 if ((PyObject
*)z
!= Py_None
) {
540 PyErr_SetString(PyExc_TypeError
, "pow() 3rd argument not "
541 "allowed unless all arguments are integers");
545 CONVERT_TO_DOUBLE(v
, iv
);
546 CONVERT_TO_DOUBLE(w
, iw
);
548 /* Sort out special cases here instead of relying on pow() */
549 if (iw
== 0) { /* v**0 is 1, even 0**0 */
550 PyFPE_START_PROTECT("pow", return NULL
)
551 if ((PyObject
*)z
!= Py_None
) {
553 CONVERT_TO_DOUBLE(z
, iz
);
555 if (ix
!= 0 && iz
< 0)
560 PyFPE_END_PROTECT(ix
)
561 return PyFloat_FromDouble(ix
);
563 if (iv
== 0.0) { /* 0**w is error if w<0, else 1 */
565 PyErr_SetString(PyExc_ZeroDivisionError
,
566 "0.0 cannot be raised to a negative power");
569 return PyFloat_FromDouble(0.0);
571 if (iv
< 0.0 && iw
!= floor(iw
)) {
572 PyErr_SetString(PyExc_ValueError
,
573 "negative number cannot be raised to a fractional power");
577 PyFPE_START_PROTECT("pow", return NULL
)
579 PyFPE_END_PROTECT(ix
)
580 Py_SET_ERANGE_IF_OVERFLOW(ix
);
582 /* XXX could it be another type of error? */
583 PyErr_SetFromErrno(PyExc_OverflowError
);
586 return PyFloat_FromDouble(ix
);
590 float_neg(PyFloatObject
*v
)
592 return PyFloat_FromDouble(-v
->ob_fval
);
596 float_pos(PyFloatObject
*v
)
598 if (PyFloat_CheckExact(v
)) {
600 return (PyObject
*)v
;
603 return PyFloat_FromDouble(v
->ob_fval
);
607 float_abs(PyFloatObject
*v
)
609 return PyFloat_FromDouble(fabs(v
->ob_fval
));
613 float_nonzero(PyFloatObject
*v
)
615 return v
->ob_fval
!= 0.0;
619 float_coerce(PyObject
**pv
, PyObject
**pw
)
621 if (PyInt_Check(*pw
)) {
622 long x
= PyInt_AsLong(*pw
);
623 *pw
= PyFloat_FromDouble((double)x
);
627 else if (PyLong_Check(*pw
)) {
628 *pw
= PyFloat_FromDouble(PyLong_AsDouble(*pw
));
632 else if (PyFloat_Check(*pw
)) {
637 return 1; /* Can't do it */
641 float_int(PyObject
*v
)
643 double x
= PyFloat_AsDouble(v
);
644 double wholepart
; /* integral portion of x, rounded toward 0 */
645 long aslong
; /* (long)wholepart */
647 (void)modf(x
, &wholepart
);
649 /* conversion from floating to integral type would raise exception */
650 if (wholepart
>LONG_MAX
|| wholepart
<LONG_MIN
) {
651 PyErr_SetString(PyExc_OverflowError
, "float too large to convert");
655 /* doubles may have more bits than longs, or vice versa; and casting
656 to long may yield gibberish in either case. What really matters
657 is whether converting back to double again reproduces what we
659 aslong
= (long)wholepart
;
660 if ((double)aslong
== wholepart
)
661 return PyInt_FromLong(aslong
);
662 PyErr_SetString(PyExc_OverflowError
, "float too large to convert");
667 float_long(PyObject
*v
)
669 double x
= PyFloat_AsDouble(v
);
670 return PyLong_FromDouble(x
);
674 float_float(PyObject
*v
)
681 staticforward PyObject
*
682 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
685 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
687 PyObject
*x
= Py_False
; /* Integer zero */
688 static char *kwlist
[] = {"x", 0};
690 if (type
!= &PyFloat_Type
)
691 return float_subtype_new(type
, args
, kwds
); /* Wimp out */
692 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
694 if (PyString_Check(x
))
695 return PyFloat_FromString(x
, NULL
);
696 return PyNumber_Float(x
);
699 /* Wimpy, slow approach to tp_new calls for subtypes of float:
700 first create a regular float from whatever arguments we got,
701 then allocate a subtype instance and initialize its ob_fval
702 from the regular float. The regular float is then thrown away.
705 float_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
709 assert(PyType_IsSubtype(type
, &PyFloat_Type
));
710 tmp
= float_new(&PyFloat_Type
, args
, kwds
);
713 assert(PyFloat_CheckExact(tmp
));
714 new = type
->tp_alloc(type
, 0);
717 ((PyFloatObject
*)new)->ob_fval
= ((PyFloatObject
*)tmp
)->ob_fval
;
722 static char float_doc
[] =
723 "float(x) -> floating point number\n\
725 Convert a string or number to a floating point number, if possible.";
728 static PyNumberMethods float_as_number
= {
729 (binaryfunc
)float_add
, /*nb_add*/
730 (binaryfunc
)float_sub
, /*nb_subtract*/
731 (binaryfunc
)float_mul
, /*nb_multiply*/
732 (binaryfunc
)float_classic_div
, /*nb_divide*/
733 (binaryfunc
)float_rem
, /*nb_remainder*/
734 (binaryfunc
)float_divmod
, /*nb_divmod*/
735 (ternaryfunc
)float_pow
, /*nb_power*/
736 (unaryfunc
)float_neg
, /*nb_negative*/
737 (unaryfunc
)float_pos
, /*nb_positive*/
738 (unaryfunc
)float_abs
, /*nb_absolute*/
739 (inquiry
)float_nonzero
, /*nb_nonzero*/
746 (coercion
)float_coerce
, /*nb_coerce*/
747 (unaryfunc
)float_int
, /*nb_int*/
748 (unaryfunc
)float_long
, /*nb_long*/
749 (unaryfunc
)float_float
, /*nb_float*/
752 0, /* nb_inplace_add */
753 0, /* nb_inplace_subtract */
754 0, /* nb_inplace_multiply */
755 0, /* nb_inplace_divide */
756 0, /* nb_inplace_remainder */
757 0, /* nb_inplace_power */
758 0, /* nb_inplace_lshift */
759 0, /* nb_inplace_rshift */
760 0, /* nb_inplace_and */
761 0, /* nb_inplace_xor */
762 0, /* nb_inplace_or */
763 float_floor_div
, /* nb_floor_divide */
764 float_div
, /* nb_true_divide */
765 0, /* nb_inplace_floor_divide */
766 0, /* nb_inplace_true_divide */
769 PyTypeObject PyFloat_Type
= {
770 PyObject_HEAD_INIT(&PyType_Type
)
773 sizeof(PyFloatObject
),
775 (destructor
)float_dealloc
, /* tp_dealloc */
776 (printfunc
)float_print
, /* tp_print */
779 (cmpfunc
)float_compare
, /* tp_compare */
780 (reprfunc
)float_repr
, /* tp_repr */
781 &float_as_number
, /* tp_as_number */
782 0, /* tp_as_sequence */
783 0, /* tp_as_mapping */
784 (hashfunc
)float_hash
, /* tp_hash */
786 (reprfunc
)float_str
, /* tp_str */
787 PyObject_GenericGetAttr
, /* tp_getattro */
789 0, /* tp_as_buffer */
790 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
791 Py_TPFLAGS_BASETYPE
, /* tp_flags */
792 float_doc
, /* tp_doc */
795 0, /* tp_richcompare */
796 0, /* tp_weaklistoffset */
804 0, /* tp_descr_get */
805 0, /* tp_descr_set */
806 0, /* tp_dictoffset */
809 float_new
, /* tp_new */
816 PyFloatBlock
*list
, *next
;
818 int bc
, bf
; /* block count, number of freed blocks */
819 int frem
, fsum
; /* remaining unfreed floats per block, total */
827 while (list
!= NULL
) {
830 for (i
= 0, p
= &list
->objects
[0];
833 if (PyFloat_CheckExact(p
) && p
->ob_refcnt
!= 0)
838 list
->next
= block_list
;
840 for (i
= 0, p
= &list
->objects
[0];
843 if (!PyFloat_CheckExact(p
) ||
845 p
->ob_type
= (struct _typeobject
*)
852 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
860 fprintf(stderr
, "# cleanup floats");
862 fprintf(stderr
, "\n");
866 ": %d unfreed float%s in %d out of %d block%s\n",
867 fsum
, fsum
== 1 ? "" : "s",
868 bc
- bf
, bc
, bc
== 1 ? "" : "s");
870 if (Py_VerboseFlag
> 1) {
872 while (list
!= NULL
) {
873 for (i
= 0, p
= &list
->objects
[0];
876 if (PyFloat_CheckExact(p
) &&
879 PyFloat_AsString(buf
, p
);
881 "# <float at %p, refcnt=%d, val=%s>\n",
882 p
, p
->ob_refcnt
, buf
);