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);
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 char s_buffer
[256]; /* for objects convertible to a char buffer */
117 if (PyString_Check(v
)) {
118 s
= PyString_AS_STRING(v
);
119 len
= PyString_GET_SIZE(v
);
121 else if (PyUnicode_Check(v
)) {
122 if (PyUnicode_GET_SIZE(v
) >= sizeof(s_buffer
)) {
123 PyErr_SetString(PyExc_ValueError
,
124 "Unicode float() literal too long to convert");
127 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
128 PyUnicode_GET_SIZE(v
),
133 len
= (int)strlen(s
);
135 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
136 PyErr_SetString(PyExc_TypeError
,
137 "float() needs a string argument");
142 while (*s
&& isspace(Py_CHARMASK(*s
)))
145 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
148 /* We don't care about overflow or underflow. If the platform supports
149 * them, infinities and signed zeroes (on underflow) are fine.
150 * However, strtod can return 0 for denormalized numbers, where atof
151 * does not. So (alas!) we special-case a zero result. Note that
152 * whether strtod sets errno on underflow is not defined, so we can't
155 PyFPE_START_PROTECT("strtod", return NULL
)
156 x
= strtod(s
, (char **)&end
);
159 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
160 byte at the end of the string, when the input is inf(inity). */
164 sprintf(buffer
, "invalid literal for float(): %.200s", s
);
165 PyErr_SetString(PyExc_ValueError
, buffer
);
168 /* Since end != s, the platform made *some* kind of sense out
169 of the input. Trust it. */
170 while (*end
&& isspace(Py_CHARMASK(*end
)))
173 sprintf(buffer
, "invalid literal for float(): %.200s", s
);
174 PyErr_SetString(PyExc_ValueError
, buffer
);
177 else if (end
!= last
) {
178 PyErr_SetString(PyExc_ValueError
,
179 "null byte in argument for float()");
183 /* See above -- may have been strtod being anal
185 PyFPE_START_PROTECT("atof", return NULL
)
188 errno
= 0; /* whether atof ever set errno is undefined */
190 return PyFloat_FromDouble(x
);
194 float_dealloc(PyFloatObject
*op
)
196 op
->ob_type
= (struct _typeobject
*)free_list
;
201 PyFloat_AsDouble(PyObject
*op
)
207 if (op
&& PyFloat_Check(op
))
208 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
210 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
211 nb
->nb_float
== NULL
) {
216 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
219 if (!PyFloat_Check(fo
)) {
220 PyErr_SetString(PyExc_TypeError
,
221 "nb_float should return float object");
225 val
= PyFloat_AS_DOUBLE(fo
);
234 PyFloat_AsStringEx(char *buf
, PyFloatObject
*v
, int precision
)
237 /* Subroutine for float_repr and float_print.
238 We want float numbers to be recognizable as such,
239 i.e., they should contain a decimal point or an exponent.
240 However, %g may print the number as an integer;
241 in such cases, we append ".0" to the string. */
242 sprintf(buf
, "%.*g", precision
, v
->ob_fval
);
246 for (; *cp
!= '\0'; cp
++) {
247 /* Any non-digit means it's not an integer;
248 this takes care of NAN and INF as well. */
249 if (!isdigit(Py_CHARMASK(*cp
)))
259 /* Macro and helper that convert PyObject obj to a C double and store
260 the value in dbl; this replaces the functionality of the coercion
263 #define CONVERT_TO_DOUBLE(obj, dbl) \
264 if (PyFloat_Check(obj)) \
265 dbl = PyFloat_AS_DOUBLE(obj); \
266 else if (convert_to_double(&(obj), &(dbl)) < 0) \
270 convert_to_double(PyObject
**v
,
273 register PyObject
*obj
= *v
;
275 if (PyInt_Check(obj
)) {
276 *dbl
= (double)PyInt_AS_LONG(obj
);
278 else if (PyLong_Check(obj
)) {
279 PyFPE_START_PROTECT("convert_to_double", {*v
=NULL
;return -1;})
280 *dbl
= PyLong_AsDouble(obj
);
281 PyFPE_END_PROTECT(*dbl
)
284 Py_INCREF(Py_NotImplemented
);
285 *v
= Py_NotImplemented
;
291 /* Precisions used by repr() and str(), respectively.
293 The repr() precision (17 significant decimal digits) is the minimal number
294 that is guaranteed to have enough precision so that if the number is read
295 back in the exact same binary value is recreated. This is true for IEEE
296 floating point by design, and also happens to work for all other modern
299 The str() precision is chosen so that in most cases, the rounding noise
300 created by various operations is suppressed, while giving plenty of
301 precision for practical use.
309 PyFloat_AsString(char *buf
, PyFloatObject
*v
)
311 PyFloat_AsStringEx(buf
, v
, PREC_STR
);
316 float_print(PyFloatObject
*v
, FILE *fp
, int flags
)
317 /* flags -- not used but required by interface */
320 PyFloat_AsStringEx(buf
, v
, flags
&Py_PRINT_RAW
? PREC_STR
: PREC_REPR
);
326 float_repr(PyFloatObject
*v
)
329 PyFloat_AsStringEx(buf
, v
, PREC_REPR
);
330 return PyString_FromString(buf
);
334 float_str(PyFloatObject
*v
)
337 PyFloat_AsStringEx(buf
, v
, PREC_STR
);
338 return PyString_FromString(buf
);
342 float_compare(PyFloatObject
*v
, PyFloatObject
*w
)
344 double i
= v
->ob_fval
;
345 double j
= w
->ob_fval
;
346 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
350 float_hash(PyFloatObject
*v
)
352 return _Py_HashDouble(v
->ob_fval
);
356 float_add(PyObject
*v
, PyObject
*w
)
359 CONVERT_TO_DOUBLE(v
, a
);
360 CONVERT_TO_DOUBLE(w
, b
);
361 PyFPE_START_PROTECT("add", return 0)
364 return PyFloat_FromDouble(a
);
368 float_sub(PyObject
*v
, PyObject
*w
)
371 CONVERT_TO_DOUBLE(v
, a
);
372 CONVERT_TO_DOUBLE(w
, b
);
373 PyFPE_START_PROTECT("subtract", return 0)
376 return PyFloat_FromDouble(a
);
380 float_mul(PyObject
*v
, PyObject
*w
)
383 CONVERT_TO_DOUBLE(v
, a
);
384 CONVERT_TO_DOUBLE(w
, b
);
385 PyFPE_START_PROTECT("multiply", return 0)
388 return PyFloat_FromDouble(a
);
392 float_div(PyObject
*v
, PyObject
*w
)
395 CONVERT_TO_DOUBLE(v
, a
);
396 CONVERT_TO_DOUBLE(w
, b
);
398 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
401 PyFPE_START_PROTECT("divide", return 0)
404 return PyFloat_FromDouble(a
);
408 float_rem(PyObject
*v
, PyObject
*w
)
412 CONVERT_TO_DOUBLE(v
, vx
);
413 CONVERT_TO_DOUBLE(w
, wx
);
415 PyErr_SetString(PyExc_ZeroDivisionError
, "float modulo");
418 PyFPE_START_PROTECT("modulo", return 0)
420 /* note: checking mod*wx < 0 is incorrect -- underflows to
421 0 if wx < sqrt(smallest nonzero double) */
422 if (mod
&& ((wx
< 0) != (mod
< 0))) {
425 PyFPE_END_PROTECT(mod
)
426 return PyFloat_FromDouble(mod
);
430 float_divmod(PyObject
*v
, PyObject
*w
)
433 double div
, mod
, floordiv
;
434 CONVERT_TO_DOUBLE(v
, vx
);
435 CONVERT_TO_DOUBLE(w
, wx
);
437 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
440 PyFPE_START_PROTECT("divmod", return 0)
442 /* fmod is typically exact, so vx-mod is *mathematically* an
443 exact multiple of wx. But this is fp arithmetic, and fp
444 vx - mod is an approximation; the result is that div may
445 not be an exact integral value after the division, although
446 it will always be very close to one.
448 div
= (vx
- mod
) / wx
;
449 /* note: checking mod*wx < 0 is incorrect -- underflows to
450 0 if wx < sqrt(smallest nonzero double) */
451 if (mod
&& ((wx
< 0) != (mod
< 0))) {
455 /* snap quotient to nearest integral value */
456 floordiv
= floor(div
);
457 if (div
- floordiv
> 0.5)
459 PyFPE_END_PROTECT(div
)
460 return Py_BuildValue("(dd)", floordiv
, mod
);
463 static double powu(double x
, long n
)
468 while (mask
> 0 && n
>= mask
) {
478 float_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
482 /* XXX Doesn't handle overflows if z!=None yet; it may never do so :(
483 * The z parameter is really only going to be useful for integers and
484 * long integers. Maybe something clever with logarithms could be done.
487 CONVERT_TO_DOUBLE(v
, iv
);
488 CONVERT_TO_DOUBLE(w
, iw
);
491 /* Sort out special cases here instead of relying on pow() */
492 if (iw
== 0) { /* x**0 is 1, even 0**0 */
493 PyFPE_START_PROTECT("pow", return NULL
)
494 if ((PyObject
*)z
!= Py_None
) {
496 CONVERT_TO_DOUBLE(z
, iz
);
498 if (ix
!=0 && iz
<0) ix
+=iz
;
502 PyFPE_END_PROTECT(ix
)
503 return PyFloat_FromDouble(ix
);
507 PyErr_SetString(PyExc_ZeroDivisionError
,
508 "0.0 cannot be raised to a negative power");
511 return PyFloat_FromDouble(0.0);
514 if (iw
== intw
&& intw
> LONG_MIN
) {
515 /* ruled out LONG_MIN because -LONG_MIN isn't representable */
517 PyFPE_START_PROTECT("pow", return NULL
)
521 ix
= 1./powu(iv
, -intw
);
522 PyFPE_END_PROTECT(ix
)
525 /* Sort out special cases here instead of relying on pow() */
527 PyErr_SetString(PyExc_ValueError
,
528 "negative number cannot be raised to a fractional power");
532 PyFPE_START_PROTECT("pow", return NULL
)
534 PyFPE_END_PROTECT(ix
)
538 /* XXX could it be another type of error? */
539 PyErr_SetFromErrno(PyExc_OverflowError
);
542 if ((PyObject
*)z
!= Py_None
) {
544 CONVERT_TO_DOUBLE(z
, iz
);
545 PyFPE_START_PROTECT("pow", return 0)
546 ix
=fmod(ix
, iz
); /* XXX To Be Rewritten */
547 if (ix
!=0 && ((iv
<0 && iz
>0) || (iv
>0 && iz
<0) )) {
550 PyFPE_END_PROTECT(ix
)
552 return PyFloat_FromDouble(ix
);
556 float_neg(PyFloatObject
*v
)
558 return PyFloat_FromDouble(-v
->ob_fval
);
562 float_pos(PyFloatObject
*v
)
565 return (PyObject
*)v
;
569 float_abs(PyFloatObject
*v
)
578 float_nonzero(PyFloatObject
*v
)
580 return v
->ob_fval
!= 0.0;
584 float_coerce(PyObject
**pv
, PyObject
**pw
)
586 if (PyInt_Check(*pw
)) {
587 long x
= PyInt_AsLong(*pw
);
588 *pw
= PyFloat_FromDouble((double)x
);
592 else if (PyLong_Check(*pw
)) {
593 *pw
= PyFloat_FromDouble(PyLong_AsDouble(*pw
));
597 return 1; /* Can't do it */
601 float_int(PyObject
*v
)
603 double x
= PyFloat_AsDouble(v
);
604 if (x
< 0 ? (x
= ceil(x
)) < (double)LONG_MIN
605 : (x
= floor(x
)) > (double)LONG_MAX
) {
606 PyErr_SetString(PyExc_OverflowError
,
607 "float too large to convert");
610 return PyInt_FromLong((long)x
);
614 float_long(PyObject
*v
)
616 double x
= PyFloat_AsDouble(v
);
617 return PyLong_FromDouble(x
);
621 float_float(PyObject
*v
)
628 static PyNumberMethods float_as_number
= {
629 (binaryfunc
)float_add
, /*nb_add*/
630 (binaryfunc
)float_sub
, /*nb_subtract*/
631 (binaryfunc
)float_mul
, /*nb_multiply*/
632 (binaryfunc
)float_div
, /*nb_divide*/
633 (binaryfunc
)float_rem
, /*nb_remainder*/
634 (binaryfunc
)float_divmod
, /*nb_divmod*/
635 (ternaryfunc
)float_pow
, /*nb_power*/
636 (unaryfunc
)float_neg
, /*nb_negative*/
637 (unaryfunc
)float_pos
, /*nb_positive*/
638 (unaryfunc
)float_abs
, /*nb_absolute*/
639 (inquiry
)float_nonzero
, /*nb_nonzero*/
646 (coercion
)float_coerce
, /*nb_coerce*/
647 (unaryfunc
)float_int
, /*nb_int*/
648 (unaryfunc
)float_long
, /*nb_long*/
649 (unaryfunc
)float_float
, /*nb_float*/
652 0, /*nb_inplace_add*/
653 0, /*nb_inplace_subtract*/
654 0, /*nb_inplace_multiply*/
655 0, /*nb_inplace_divide*/
656 0, /*nb_inplace_remainder*/
657 0, /*nb_inplace_power*/
658 0, /*nb_inplace_lshift*/
659 0, /*nb_inplace_rshift*/
660 0, /*nb_inplace_and*/
661 0, /*nb_inplace_xor*/
665 PyTypeObject PyFloat_Type
= {
666 PyObject_HEAD_INIT(&PyType_Type
)
669 sizeof(PyFloatObject
),
671 (destructor
)float_dealloc
, /*tp_dealloc*/
672 (printfunc
)float_print
, /*tp_print*/
675 (cmpfunc
)float_compare
, /*tp_compare*/
676 (reprfunc
)float_repr
, /*tp_repr*/
677 &float_as_number
, /*tp_as_number*/
678 0, /*tp_as_sequence*/
680 (hashfunc
)float_hash
, /*tp_hash*/
682 (reprfunc
)float_str
, /*tp_str*/
686 Py_TPFLAGS_CHECKTYPES
/*tp_flags*/
693 PyFloatBlock
*list
, *next
;
695 int bc
, bf
; /* block count, number of freed blocks */
696 int frem
, fsum
; /* remaining unfreed floats per block, total */
704 while (list
!= NULL
) {
707 for (i
= 0, p
= &list
->objects
[0];
710 if (PyFloat_Check(p
) && p
->ob_refcnt
!= 0)
715 list
->next
= block_list
;
717 for (i
= 0, p
= &list
->objects
[0];
720 if (!PyFloat_Check(p
) || p
->ob_refcnt
== 0) {
721 p
->ob_type
= (struct _typeobject
*)
728 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
736 fprintf(stderr
, "# cleanup floats");
738 fprintf(stderr
, "\n");
742 ": %d unfreed float%s in %d out of %d block%s\n",
743 fsum
, fsum
== 1 ? "" : "s",
744 bc
- bf
, bc
, bc
== 1 ? "" : "s");
746 if (Py_VerboseFlag
> 1) {
748 while (list
!= NULL
) {
749 for (i
= 0, p
= &list
->objects
[0];
752 if (PyFloat_Check(p
) && p
->ob_refcnt
!= 0) {
754 PyFloat_AsString(buf
, p
);
756 "# <float at %p, refcnt=%d, val=%s>\n",
757 p
, p
->ob_refcnt
, buf
);