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. */
12 /* Cray APP has bogus definition of HUGE_VAL in <math.h> */
16 #if defined(HUGE_VAL) && !defined(CHECK)
17 #define CHECK(x) if (errno != 0) ; \
18 else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \
23 #define CHECK(x) /* Don't know how to check */
26 #if !defined(__STDC__) && !defined(macintosh)
27 extern double fmod(double, double);
28 extern double pow(double, double);
31 #if defined(sun) && !defined(__SVR4)
32 /* On SunOS4.1 only libm.a exists. Make sure that references to all
33 needed math functions exist in the executable, so that dynamic
34 loading of mathmodule does not fail. */
35 double (*_Py_math_funcs_hack
[])() = {
36 acos
, asin
, atan
, atan2
, ceil
, cos
, cosh
, exp
, fabs
, floor
,
37 fmod
, log
, log10
, pow
, sin
, sinh
, sqrt
, tan
, tanh
41 /* Special free list -- see comments for same code in intobject.c. */
42 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
43 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
44 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
47 struct _floatblock
*next
;
48 PyFloatObject objects
[N_FLOATOBJECTS
];
51 typedef struct _floatblock PyFloatBlock
;
53 static PyFloatBlock
*block_list
= NULL
;
54 static PyFloatObject
*free_list
= NULL
;
56 static PyFloatObject
*
60 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
61 p
= (PyFloatObject
*) PyMem_MALLOC(sizeof(PyFloatBlock
));
63 return (PyFloatObject
*) PyErr_NoMemory();
64 ((PyFloatBlock
*)p
)->next
= block_list
;
65 block_list
= (PyFloatBlock
*)p
;
66 p
= &((PyFloatBlock
*)p
)->objects
[0];
67 q
= p
+ N_FLOATOBJECTS
;
69 q
->ob_type
= (struct _typeobject
*)(q
-1);
71 return p
+ N_FLOATOBJECTS
- 1;
75 PyFloat_FromDouble(double fval
)
77 register PyFloatObject
*op
;
78 if (free_list
== NULL
) {
79 if ((free_list
= fill_free_list()) == NULL
)
82 /* PyObject_New is inlined */
84 free_list
= (PyFloatObject
*)op
->ob_type
;
85 PyObject_INIT(op
, &PyFloat_Type
);
87 return (PyObject
*) op
;
90 /**************************************************************************
91 RED_FLAG 22-Sep-2000 tim
92 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
94 1. If v was a regular string, *pend was set to point to its terminating
95 null byte. That's useless (the caller can find that without any
96 help from this function!).
98 2. If v was a Unicode string, or an object convertible to a character
99 buffer, *pend was set to point into stack trash (the auto temp
100 vector holding the character buffer). That was downright dangerous.
102 Since we can't change the interface of a public API function, pend is
103 still supported but now *officially* useless: if pend is not NULL,
104 *pend is set to NULL.
105 **************************************************************************/
107 PyFloat_FromString(PyObject
*v
, char **pend
)
109 const char *s
, *last
, *end
;
111 char buffer
[256]; /* for errors */
112 #ifdef Py_USING_UNICODE
113 char s_buffer
[256]; /* for objects convertible to a char buffer */
119 if (PyString_Check(v
)) {
120 s
= PyString_AS_STRING(v
);
121 len
= PyString_GET_SIZE(v
);
123 #ifdef Py_USING_UNICODE
124 else if (PyUnicode_Check(v
)) {
125 if (PyUnicode_GET_SIZE(v
) >= sizeof(s_buffer
)) {
126 PyErr_SetString(PyExc_ValueError
,
127 "Unicode float() literal too long to convert");
130 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
131 PyUnicode_GET_SIZE(v
),
136 len
= (int)strlen(s
);
139 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
140 PyErr_SetString(PyExc_TypeError
,
141 "float() needs a string argument");
146 while (*s
&& isspace(Py_CHARMASK(*s
)))
149 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
152 /* We don't care about overflow or underflow. If the platform supports
153 * them, infinities and signed zeroes (on underflow) are fine.
154 * However, strtod can return 0 for denormalized numbers, where atof
155 * does not. So (alas!) we special-case a zero result. Note that
156 * whether strtod sets errno on underflow is not defined, so we can't
159 PyFPE_START_PROTECT("strtod", return NULL
)
160 x
= strtod(s
, (char **)&end
);
163 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
164 byte at the end of the string, when the input is inf(inity). */
168 sprintf(buffer
, "invalid literal for float(): %.200s", s
);
169 PyErr_SetString(PyExc_ValueError
, buffer
);
172 /* Since end != s, the platform made *some* kind of sense out
173 of the input. Trust it. */
174 while (*end
&& isspace(Py_CHARMASK(*end
)))
177 sprintf(buffer
, "invalid literal for float(): %.200s", s
);
178 PyErr_SetString(PyExc_ValueError
, buffer
);
181 else if (end
!= last
) {
182 PyErr_SetString(PyExc_ValueError
,
183 "null byte in argument for float()");
187 /* See above -- may have been strtod being anal
189 PyFPE_START_PROTECT("atof", return NULL
)
192 errno
= 0; /* whether atof ever set errno is undefined */
194 return PyFloat_FromDouble(x
);
198 float_dealloc(PyFloatObject
*op
)
200 op
->ob_type
= (struct _typeobject
*)free_list
;
205 PyFloat_AsDouble(PyObject
*op
)
211 if (op
&& PyFloat_Check(op
))
212 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
214 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
215 nb
->nb_float
== NULL
) {
220 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
223 if (!PyFloat_Check(fo
)) {
224 PyErr_SetString(PyExc_TypeError
,
225 "nb_float should return float object");
229 val
= PyFloat_AS_DOUBLE(fo
);
238 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
241 /* Subroutine for float_repr and float_print.
242 We want float numbers to be recognizable as such,
243 i.e., they should contain a decimal point or an exponent.
244 However, %g may print the number as an integer;
245 in such cases, we append ".0" to the string. */
246 sprintf(buf
, "%.*g", precision
, v
->ob_fval
);
250 for (; *cp
!= '\0'; cp
++) {
251 /* Any non-digit means it's not an integer;
252 this takes care of NAN and INF as well. */
253 if (!isdigit(Py_CHARMASK(*cp
)))
263 /* Macro and helper that convert PyObject obj to a C double and store
264 the value in dbl; this replaces the functionality of the coercion
267 #define CONVERT_TO_DOUBLE(obj, dbl) \
268 if (PyFloat_Check(obj)) \
269 dbl = PyFloat_AS_DOUBLE(obj); \
270 else if (convert_to_double(&(obj), &(dbl)) < 0) \
274 convert_to_double(PyObject
**v
,
277 register PyObject
*obj
= *v
;
279 if (PyInt_Check(obj
)) {
280 *dbl
= (double)PyInt_AS_LONG(obj
);
282 else if (PyLong_Check(obj
)) {
283 PyFPE_START_PROTECT("convert_to_double", {*v
=NULL
;return -1;})
284 *dbl
= PyLong_AsDouble(obj
);
285 PyFPE_END_PROTECT(*dbl
)
288 Py_INCREF(Py_NotImplemented
);
289 *v
= Py_NotImplemented
;
295 /* Precisions used by repr() and str(), respectively.
297 The repr() precision (17 significant decimal digits) is the minimal number
298 that is guaranteed to have enough precision so that if the number is read
299 back in the exact same binary value is recreated. This is true for IEEE
300 floating point by design, and also happens to work for all other modern
303 The str() precision is chosen so that in most cases, the rounding noise
304 created by various operations is suppressed, while giving plenty of
305 precision for practical use.
313 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
315 PyFloat_AsStringEx(buf
, v
, PREC_STR
);
319 PyFloat_AsReprString(char *buf
, PyFloatObject
*v
)
321 PyFloat_AsStringEx(buf
, v
, PREC_REPR
);
326 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
329 PyFloat_AsStringEx(buf
, v
, flags
&Py_PRINT_RAW
? PREC_STR
: PREC_REPR
);
335 float_repr(PyFloatObject
*v
)
338 PyFloat_AsStringEx(buf
, v
, PREC_REPR
);
339 return PyString_FromString(buf
);
343 float_str(PyFloatObject
*v
)
346 PyFloat_AsStringEx(buf
, v
, PREC_STR
);
347 return PyString_FromString(buf
);
351 float_compare(PyFloatObject
*v
, PyFloatObject
*w
)
353 double i
= v
->ob_fval
;
354 double j
= w
->ob_fval
;
355 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
359 float_hash(PyFloatObject
*v
)
361 return _Py_HashDouble(v
->ob_fval
);
365 float_add(PyObject
*v
, PyObject
*w
)
368 CONVERT_TO_DOUBLE(v
, a
);
369 CONVERT_TO_DOUBLE(w
, b
);
370 PyFPE_START_PROTECT("add", return 0)
373 return PyFloat_FromDouble(a
);
377 float_sub(PyObject
*v
, PyObject
*w
)
380 CONVERT_TO_DOUBLE(v
, a
);
381 CONVERT_TO_DOUBLE(w
, b
);
382 PyFPE_START_PROTECT("subtract", return 0)
385 return PyFloat_FromDouble(a
);
389 float_mul(PyObject
*v
, PyObject
*w
)
392 CONVERT_TO_DOUBLE(v
, a
);
393 CONVERT_TO_DOUBLE(w
, b
);
394 PyFPE_START_PROTECT("multiply", return 0)
397 return PyFloat_FromDouble(a
);
401 float_div(PyObject
*v
, PyObject
*w
)
404 CONVERT_TO_DOUBLE(v
, a
);
405 CONVERT_TO_DOUBLE(w
, b
);
407 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
410 PyFPE_START_PROTECT("divide", return 0)
413 return PyFloat_FromDouble(a
);
417 float_rem(PyObject
*v
, PyObject
*w
)
421 CONVERT_TO_DOUBLE(v
, vx
);
422 CONVERT_TO_DOUBLE(w
, wx
);
424 PyErr_SetString(PyExc_ZeroDivisionError
, "float modulo");
427 PyFPE_START_PROTECT("modulo", return 0)
429 /* note: checking mod*wx < 0 is incorrect -- underflows to
430 0 if wx < sqrt(smallest nonzero double) */
431 if (mod
&& ((wx
< 0) != (mod
< 0))) {
434 PyFPE_END_PROTECT(mod
)
435 return PyFloat_FromDouble(mod
);
439 float_divmod(PyObject
*v
, PyObject
*w
)
442 double div
, mod
, floordiv
;
443 CONVERT_TO_DOUBLE(v
, vx
);
444 CONVERT_TO_DOUBLE(w
, wx
);
446 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
449 PyFPE_START_PROTECT("divmod", return 0)
451 /* fmod is typically exact, so vx-mod is *mathematically* an
452 exact multiple of wx. But this is fp arithmetic, and fp
453 vx - mod is an approximation; the result is that div may
454 not be an exact integral value after the division, although
455 it will always be very close to one.
457 div
= (vx
- mod
) / wx
;
458 /* note: checking mod*wx < 0 is incorrect -- underflows to
459 0 if wx < sqrt(smallest nonzero double) */
460 if (mod
&& ((wx
< 0) != (mod
< 0))) {
464 /* snap quotient to nearest integral value */
465 floordiv
= floor(div
);
466 if (div
- floordiv
> 0.5)
468 PyFPE_END_PROTECT(div
)
469 return Py_BuildValue("(dd)", floordiv
, mod
);
472 static double powu(double x
, long n
)
477 while (mask
> 0 && n
>= mask
) {
487 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
491 /* XXX Doesn't handle overflows if z!=None yet; it may never do so :(
492 * The z parameter is really only going to be useful for integers and
493 * long integers. Maybe something clever with logarithms could be done.
496 CONVERT_TO_DOUBLE(v
, iv
);
497 CONVERT_TO_DOUBLE(w
, iw
);
500 /* Sort out special cases here instead of relying on pow() */
501 if (iw
== 0) { /* x**0 is 1, even 0**0 */
502 PyFPE_START_PROTECT("pow", return NULL
)
503 if ((PyObject
*)z
!= Py_None
) {
505 CONVERT_TO_DOUBLE(z
, iz
);
507 if (ix
!=0 && iz
<0) ix
+=iz
;
511 PyFPE_END_PROTECT(ix
)
512 return PyFloat_FromDouble(ix
);
516 PyErr_SetString(PyExc_ZeroDivisionError
,
517 "0.0 cannot be raised to a negative power");
520 return PyFloat_FromDouble(0.0);
523 if (iw
== intw
&& intw
> LONG_MIN
) {
524 /* ruled out LONG_MIN because -LONG_MIN isn't representable */
526 PyFPE_START_PROTECT("pow", return NULL
)
530 ix
= 1./powu(iv
, -intw
);
531 PyFPE_END_PROTECT(ix
)
534 /* Sort out special cases here instead of relying on pow() */
536 PyErr_SetString(PyExc_ValueError
,
537 "negative number cannot be raised to a fractional power");
541 PyFPE_START_PROTECT("pow", return NULL
)
543 PyFPE_END_PROTECT(ix
)
547 /* XXX could it be another type of error? */
548 PyErr_SetFromErrno(PyExc_OverflowError
);
551 if ((PyObject
*)z
!= Py_None
) {
553 CONVERT_TO_DOUBLE(z
, iz
);
554 PyFPE_START_PROTECT("pow", return 0)
555 ix
=fmod(ix
, iz
); /* XXX To Be Rewritten */
556 if (ix
!=0 && ((iv
<0 && iz
>0) || (iv
>0 && iz
<0) )) {
559 PyFPE_END_PROTECT(ix
)
561 return PyFloat_FromDouble(ix
);
565 float_int_div(PyObject
*v
, PyObject
*w
)
569 t
= float_divmod(v
, w
);
571 r
= PyTuple_GET_ITEM(t
, 0);
580 float_neg(PyFloatObject
*v
)
582 return PyFloat_FromDouble(-v
->ob_fval
);
586 float_pos(PyFloatObject
*v
)
589 return (PyObject
*)v
;
593 float_abs(PyFloatObject
*v
)
602 float_nonzero(PyFloatObject
*v
)
604 return v
->ob_fval
!= 0.0;
608 float_coerce(PyObject
**pv
, PyObject
**pw
)
610 if (PyInt_Check(*pw
)) {
611 long x
= PyInt_AsLong(*pw
);
612 *pw
= PyFloat_FromDouble((double)x
);
616 else if (PyLong_Check(*pw
)) {
617 *pw
= PyFloat_FromDouble(PyLong_AsDouble(*pw
));
621 return 1; /* Can't do it */
625 float_int(PyObject
*v
)
627 double x
= PyFloat_AsDouble(v
);
628 double wholepart
; /* integral portion of x, rounded toward 0 */
629 long aslong
; /* (long)wholepart */
631 (void)modf(x
, &wholepart
);
632 /* doubles may have more bits than longs, or vice versa; and casting
633 to long may yield gibberish in either case. What really matters
634 is whether converting back to double again reproduces what we
636 aslong
= (long)wholepart
;
637 if ((double)aslong
== wholepart
)
638 return PyInt_FromLong(aslong
);
639 PyErr_SetString(PyExc_OverflowError
, "float too large to convert");
644 float_long(PyObject
*v
)
646 double x
= PyFloat_AsDouble(v
);
647 return PyLong_FromDouble(x
);
651 float_float(PyObject
*v
)
659 float_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
661 PyObject
*x
= Py_False
; /* Integer zero */
662 static char *kwlist
[] = {"x", 0};
664 assert(type
== &PyFloat_Type
);
665 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:float", kwlist
, &x
))
667 if (PyString_Check(x
))
668 return PyFloat_FromString(x
, NULL
);
669 return PyNumber_Float(x
);
672 static char float_doc
[] =
673 "float(x) -> floating point number\n\
675 Convert a string or number to a floating point number, if possible.";
678 static PyNumberMethods float_as_number
= {
679 (binaryfunc
)float_add
, /*nb_add*/
680 (binaryfunc
)float_sub
, /*nb_subtract*/
681 (binaryfunc
)float_mul
, /*nb_multiply*/
682 (binaryfunc
)float_div
, /*nb_divide*/
683 (binaryfunc
)float_rem
, /*nb_remainder*/
684 (binaryfunc
)float_divmod
, /*nb_divmod*/
685 (ternaryfunc
)float_pow
, /*nb_power*/
686 (unaryfunc
)float_neg
, /*nb_negative*/
687 (unaryfunc
)float_pos
, /*nb_positive*/
688 (unaryfunc
)float_abs
, /*nb_absolute*/
689 (inquiry
)float_nonzero
, /*nb_nonzero*/
696 (coercion
)float_coerce
, /*nb_coerce*/
697 (unaryfunc
)float_int
, /*nb_int*/
698 (unaryfunc
)float_long
, /*nb_long*/
699 (unaryfunc
)float_float
, /*nb_float*/
702 0, /* nb_inplace_add */
703 0, /* nb_inplace_subtract */
704 0, /* nb_inplace_multiply */
705 0, /* nb_inplace_divide */
706 0, /* nb_inplace_remainder */
707 0, /* nb_inplace_power */
708 0, /* nb_inplace_lshift */
709 0, /* nb_inplace_rshift */
710 0, /* nb_inplace_and */
711 0, /* nb_inplace_xor */
712 0, /* nb_inplace_or */
713 float_int_div
, /* nb_floor_divide */
714 float_div
, /* nb_true_divide */
715 0, /* nb_inplace_floor_divide */
716 0, /* nb_inplace_true_divide */
719 PyTypeObject PyFloat_Type
= {
720 PyObject_HEAD_INIT(&PyType_Type
)
723 sizeof(PyFloatObject
),
725 (destructor
)float_dealloc
, /* tp_dealloc */
726 (printfunc
)float_print
, /* tp_print */
729 (cmpfunc
)float_compare
, /* tp_compare */
730 (reprfunc
)float_repr
, /* tp_repr */
731 &float_as_number
, /* tp_as_number */
732 0, /* tp_as_sequence */
733 0, /* tp_as_mapping */
734 (hashfunc
)float_hash
, /* tp_hash */
736 (reprfunc
)float_str
, /* tp_str */
737 PyObject_GenericGetAttr
, /* tp_getattro */
739 0, /* tp_as_buffer */
740 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
, /* tp_flags */
741 float_doc
, /* tp_doc */
744 0, /* tp_richcompare */
745 0, /* tp_weaklistoffset */
753 0, /* tp_descr_get */
754 0, /* tp_descr_set */
755 0, /* tp_dictoffset */
758 float_new
, /* tp_new */
765 PyFloatBlock
*list
, *next
;
767 int bc
, bf
; /* block count, number of freed blocks */
768 int frem
, fsum
; /* remaining unfreed floats per block, total */
776 while (list
!= NULL
) {
779 for (i
= 0, p
= &list
->objects
[0];
782 if (PyFloat_Check(p
) && p
->ob_refcnt
!= 0)
787 list
->next
= block_list
;
789 for (i
= 0, p
= &list
->objects
[0];
792 if (!PyFloat_Check(p
) || p
->ob_refcnt
== 0) {
793 p
->ob_type
= (struct _typeobject
*)
800 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
808 fprintf(stderr
, "# cleanup floats");
810 fprintf(stderr
, "\n");
814 ": %d unfreed float%s in %d out of %d block%s\n",
815 fsum
, fsum
== 1 ? "" : "s",
816 bc
- bf
, bc
, bc
== 1 ? "" : "s");
818 if (Py_VerboseFlag
> 1) {
820 while (list
!= NULL
) {
821 for (i
= 0, p
= &list
->objects
[0];
824 if (PyFloat_Check(p
) && p
->ob_refcnt
!= 0) {
826 PyFloat_AsString(buf
, p
);
828 "# <float at %p, refcnt=%d, val=%s>\n",
829 p
, p
->ob_refcnt
, buf
);