1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Float object implementation */
34 /* XXX There should be overflow checks here, but it's hard to check
35 for any kind of float exception without losing portability. */
43 /* Cray APP has bogus definition of HUGE_VAL in <math.h> */
47 #if defined(HUGE_VAL) && !defined(CHECK)
48 #define CHECK(x) if (errno != 0) ; \
49 else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \
54 #define CHECK(x) /* Don't know how to check */
62 #define LONG_MAX 0X7FFFFFFFL
66 #define LONG_MIN (-LONG_MAX-1)
72 * This works around a bug in the NS/Sparc 3.3 pre-release
73 * limits.h header file.
74 * 10-Feb-1995 bwarsaw@cnri.reston.va.us
77 #define LONG_MIN (-LONG_MAX-1)
81 #if !defined(__STDC__) && !defined(macintosh)
82 extern double fmod
Py_PROTO((double, double));
83 extern double pow
Py_PROTO((double, double));
87 /* On SunOS4.1 only libm.a exists. Make sure that references to all
88 needed math functions exist in the executable, so that dynamic
89 loading of mathmodule does not fail. */
90 double (*_Py_math_funcs_hack
[])() = {
91 acos
, asin
, atan
, atan2
, ceil
, cos
, cosh
, exp
, fabs
, floor
,
92 fmod
, log
, log10
, pow
, sin
, sinh
, sqrt
, tan
, tanh
96 /* Special free list -- see comments for same code in intobject.c. */
97 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
98 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
99 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
101 #define PyMem_MALLOC malloc
102 #define PyMem_FREE free
105 struct _floatblock
*next
;
106 PyFloatObject objects
[N_FLOATOBJECTS
];
109 typedef struct _floatblock PyFloatBlock
;
111 static PyFloatBlock
*block_list
= NULL
;
112 static PyFloatObject
*free_list
= NULL
;
114 static PyFloatObject
*
117 PyFloatObject
*p
, *q
;
118 p
= (PyFloatObject
*)PyMem_MALLOC(sizeof(PyFloatBlock
));
120 return (PyFloatObject
*)PyErr_NoMemory();
121 ((PyFloatBlock
*)p
)->next
= block_list
;
122 block_list
= (PyFloatBlock
*)p
;
123 p
= &((PyFloatBlock
*)p
)->objects
[0];
124 q
= p
+ N_FLOATOBJECTS
;
126 q
->ob_type
= (struct _typeobject
*)(q
-1);
128 return p
+ N_FLOATOBJECTS
- 1;
133 PyFloat_FromDouble(double fval
)
135 PyFloat_FromDouble(fval
)
139 register PyFloatObject
*op
;
140 if (free_list
== NULL
) {
141 if ((free_list
= fill_free_list()) == NULL
)
145 free_list
= (PyFloatObject
*)op
->ob_type
;
146 op
->ob_type
= &PyFloat_Type
;
148 _Py_NewReference((PyObject
*)op
);
149 return (PyObject
*) op
;
153 PyFloat_FromString(v
, pend
)
157 extern double strtod
Py_PROTO((const char *, char **));
158 char *s
, *last
, *end
;
160 char buffer
[256]; /* For errors */
162 if (!PyString_Check(v
))
164 s
= PyString_AS_STRING(v
);
166 last
= s
+ PyString_GET_SIZE(v
);
167 while (*s
&& isspace(Py_CHARMASK(*s
)))
170 PyErr_SetString(PyExc_ValueError
, "empty string for float()");
174 PyFPE_START_PROTECT("PyFloat_FromString", return 0)
177 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
178 byte at the end of the string, when the input is inf(inity) */
181 while (*end
&& isspace(Py_CHARMASK(*end
)))
184 sprintf(buffer
, "invalid literal for float(): %.200s", s
);
185 PyErr_SetString(PyExc_ValueError
, buffer
);
188 else if (end
!= PyString_AS_STRING(v
) + PyString_GET_SIZE(v
)) {
189 PyErr_SetString(PyExc_ValueError
,
190 "null byte in argument for float()");
193 else if (errno
!= 0) {
194 sprintf(buffer
, "float() literal too large: %.200s", s
);
195 PyErr_SetString(PyExc_ValueError
, buffer
);
200 return PyFloat_FromDouble(x
);
207 op
->ob_type
= (struct _typeobject
*)free_list
;
219 if (op
&& PyFloat_Check(op
))
220 return PyFloat_AS_DOUBLE((PyFloatObject
*) op
);
222 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
223 nb
->nb_float
== NULL
) {
228 fo
= (PyFloatObject
*) (*nb
->nb_float
) (op
);
231 if (!PyFloat_Check(fo
)) {
232 PyErr_SetString(PyExc_TypeError
,
233 "nb_float should return float object");
237 val
= PyFloat_AS_DOUBLE(fo
);
246 PyFloat_AsStringEx(buf
, v
, precision
)
252 /* Subroutine for float_repr and float_print.
253 We want float numbers to be recognizable as such,
254 i.e., they should contain a decimal point or an exponent.
255 However, %g may print the number as an integer;
256 in such cases, we append ".0" to the string. */
257 sprintf(buf
, "%.*g", precision
, v
->ob_fval
);
261 for (; *cp
!= '\0'; cp
++) {
262 /* Any non-digit means it's not an integer;
263 this takes care of NAN and INF as well. */
264 if (!isdigit(Py_CHARMASK(*cp
)))
274 /* Precisions used by repr() and str(), respectively.
276 The repr() precision (17 significant decimal digits) is the minimal number
277 that is guaranteed to have enough precision so that if the number is read
278 back in the exact same binary value is recreated. This is true for IEEE
279 floating point by design, and also happens to work for all other modern
282 The str() precision is chosen so that in most cases, the rounding noise
283 created by various operations is suppressed, while giving plenty of
284 precision for practical use.
292 PyFloat_AsString(buf
, v
)
296 PyFloat_AsStringEx(buf
, v
, PREC_STR
);
301 float_print(v
, fp
, flags
)
304 int flags
; /* Not used but required by interface */
307 PyFloat_AsStringEx(buf
, v
, flags
&Py_PRINT_RAW
? PREC_STR
: PREC_REPR
);
317 PyFloat_AsStringEx(buf
, v
, PREC_REPR
);
318 return PyString_FromString(buf
);
326 PyFloat_AsStringEx(buf
, v
, PREC_STR
);
327 return PyString_FromString(buf
);
332 PyFloatObject
*v
, *w
;
334 double i
= v
->ob_fval
;
335 double j
= w
->ob_fval
;
336 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
343 double intpart
, fractpart
;
346 /* This is designed so that Python numbers with the same
347 value hash to the same value, otherwise comparisons
348 of mapping keys will turn out weird */
350 #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
353 fractpart
= modf(v
->ob_fval
, &e
);
357 fractpart
= modf(v
->ob_fval
, &intpart
);
360 if (fractpart
== 0.0) {
361 if (intpart
> 0x7fffffffL
|| -intpart
> 0x7fffffffL
) {
362 /* Convert to long int and use its hash... */
363 PyObject
*w
= PyLong_FromDouble(v
->ob_fval
);
366 x
= PyObject_Hash(w
);
373 /* Note -- if you change this code, also change the copy
374 in complexobject.c */
376 fractpart
= frexp(fractpart
, &expo
);
377 fractpart
= fractpart
* 2147483648.0; /* 2**31 */
378 hipart
= (long)fractpart
; /* Take the top 32 bits */
379 fractpart
= (fractpart
- (double)hipart
) * 2147483648.0;
380 /* Get the next 32 bits */
381 x
= hipart
+ (long)fractpart
+ (long)intpart
+ (expo
<< 15);
382 /* Combine everything */
395 PyFPE_START_PROTECT("add", return 0)
396 result
= v
->ob_fval
+ w
->ob_fval
;
397 PyFPE_END_PROTECT(result
)
398 return PyFloat_FromDouble(result
);
407 PyFPE_START_PROTECT("subtract", return 0)
408 result
= v
->ob_fval
- w
->ob_fval
;
409 PyFPE_END_PROTECT(result
)
410 return PyFloat_FromDouble(result
);
420 PyFPE_START_PROTECT("multiply", return 0)
421 result
= v
->ob_fval
* w
->ob_fval
;
422 PyFPE_END_PROTECT(result
)
423 return PyFloat_FromDouble(result
);
432 if (w
->ob_fval
== 0) {
433 PyErr_SetString(PyExc_ZeroDivisionError
, "float division");
436 PyFPE_START_PROTECT("divide", return 0)
437 result
= v
->ob_fval
/ w
->ob_fval
;
438 PyFPE_END_PROTECT(result
)
439 return PyFloat_FromDouble(result
);
451 PyErr_SetString(PyExc_ZeroDivisionError
, "float modulo");
454 PyFPE_START_PROTECT("modulo", return 0)
457 /* note: checking mod*wx < 0 is incorrect -- underflows to
458 0 if wx < sqrt(smallest nonzero double) */
459 if (mod
&& ((wx
< 0) != (mod
< 0))) {
462 PyFPE_END_PROTECT(mod
)
463 return PyFloat_FromDouble(mod
);
472 double div
, mod
, floordiv
;
475 PyErr_SetString(PyExc_ZeroDivisionError
, "float divmod()");
478 PyFPE_START_PROTECT("divmod", return 0)
481 /* fmod is typically exact, so vx-mod is *mathemtically* 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
;
488 /* note: checking mod*wx < 0 is incorrect -- underflows to
489 0 if wx < sqrt(smallest nonzero double) */
490 if (mod
&& ((wx
< 0) != (mod
< 0))) {
494 /* snap quotient to nearest integral value */
495 floordiv
= floor(div
);
496 if (div
- floordiv
> 0.5)
498 PyFPE_END_PROTECT(div
)
499 return Py_BuildValue("(dd)", floordiv
, mod
);
502 static double powu(x
, n
)
509 while (mask
> 0 && n
>= mask
) {
526 /* XXX Doesn't handle overflows if z!=None yet; it may never do so :(
527 * The z parameter is really only going to be useful for integers and
528 * long integers. Maybe something clever with logarithms could be done.
532 iw
= ((PyFloatObject
*)w
)->ob_fval
;
534 if (iw
== intw
&& -10000 < intw
&& intw
< 10000) {
535 /* Sort out special cases here instead of relying on pow() */
536 if (intw
== 0) { /* x**0 is 1, even 0**0 */
537 PyFPE_START_PROTECT("pow", return 0)
538 if ((PyObject
*)z
!=Py_None
) {
539 ix
=fmod(1.0, z
->ob_fval
);
540 if (ix
!=0 && z
->ob_fval
<0) ix
+=z
->ob_fval
;
543 PyFPE_END_PROTECT(ix
)
544 return PyFloat_FromDouble(ix
);
547 PyFPE_START_PROTECT("pow", return 0)
551 ix
= 1./powu(iv
, -intw
);
552 PyFPE_END_PROTECT(ix
)
555 /* Sort out special cases here instead of relying on pow() */
558 PyErr_SetString(PyExc_ValueError
,
559 "0.0 to a negative power");
562 return PyFloat_FromDouble(0.0);
565 PyErr_SetString(PyExc_ValueError
,
566 "negative number to a float power");
570 PyFPE_START_PROTECT("pow", return 0)
572 PyFPE_END_PROTECT(ix
)
576 /* XXX could it be another type of error? */
577 PyErr_SetFromErrno(PyExc_OverflowError
);
580 if ((PyObject
*)z
!=Py_None
) {
581 PyFPE_START_PROTECT("pow", return 0)
582 ix
=fmod(ix
, z
->ob_fval
); /* XXX To Be Rewritten */
584 ((iv
<0 && z
->ob_fval
>0) || (iv
>0 && z
->ob_fval
<0) )) {
587 PyFPE_END_PROTECT(ix
)
589 return PyFloat_FromDouble(ix
);
596 return PyFloat_FromDouble(-v
->ob_fval
);
604 return (PyObject
*)v
;
621 return v
->ob_fval
!= 0.0;
629 if (PyInt_Check(*pw
)) {
630 long x
= PyInt_AsLong(*pw
);
631 *pw
= PyFloat_FromDouble((double)x
);
635 else if (PyLong_Check(*pw
)) {
636 *pw
= PyFloat_FromDouble(PyLong_AsDouble(*pw
));
640 return 1; /* Can't do it */
647 double x
= PyFloat_AsDouble(v
);
648 if (x
< 0 ? (x
= ceil(x
)) < (double)LONG_MIN
649 : (x
= floor(x
)) > (double)LONG_MAX
) {
650 PyErr_SetString(PyExc_OverflowError
,
651 "float too large to convert");
654 return PyInt_FromLong((long)x
);
661 double x
= PyFloat_AsDouble(v
);
662 return PyLong_FromDouble(x
);
674 static PyNumberMethods float_as_number
= {
675 (binaryfunc
)float_add
, /*nb_add*/
676 (binaryfunc
)float_sub
, /*nb_subtract*/
677 (binaryfunc
)float_mul
, /*nb_multiply*/
678 (binaryfunc
)float_div
, /*nb_divide*/
679 (binaryfunc
)float_rem
, /*nb_remainder*/
680 (binaryfunc
)float_divmod
, /*nb_divmod*/
681 (ternaryfunc
)float_pow
, /*nb_power*/
682 (unaryfunc
)float_neg
, /*nb_negative*/
683 (unaryfunc
)float_pos
, /*nb_positive*/
684 (unaryfunc
)float_abs
, /*nb_absolute*/
685 (inquiry
)float_nonzero
, /*nb_nonzero*/
692 (coercion
)float_coerce
, /*nb_coerce*/
693 (unaryfunc
)float_int
, /*nb_int*/
694 (unaryfunc
)float_long
, /*nb_long*/
695 (unaryfunc
)float_float
, /*nb_float*/
700 PyTypeObject PyFloat_Type
= {
701 PyObject_HEAD_INIT(&PyType_Type
)
704 sizeof(PyFloatObject
),
706 (destructor
)float_dealloc
, /*tp_dealloc*/
707 (printfunc
)float_print
, /*tp_print*/
710 (cmpfunc
)float_compare
, /*tp_compare*/
711 (reprfunc
)float_repr
, /*tp_repr*/
712 &float_as_number
, /*tp_as_number*/
713 0, /*tp_as_sequence*/
715 (hashfunc
)float_hash
, /*tp_hash*/
717 (reprfunc
)float_str
, /*tp_str*/
724 PyFloatBlock
*list
, *next
;
726 int bc
, bf
; /* block count, number of freed blocks */
727 int frem
, fsum
; /* remaining unfreed floats per block, total */
735 while (list
!= NULL
) {
738 for (i
= 0, p
= &list
->objects
[0];
741 if (PyFloat_Check(p
) && p
->ob_refcnt
!= 0)
746 list
->next
= block_list
;
748 for (i
= 0, p
= &list
->objects
[0];
751 if (!PyFloat_Check(p
) || p
->ob_refcnt
== 0) {
752 p
->ob_type
= (struct _typeobject
*)
767 fprintf(stderr
, "# cleanup floats");
769 fprintf(stderr
, "\n");
773 ": %d unfreed float%s in %d out of %d block%s\n",
774 fsum
, fsum
== 1 ? "" : "s",
775 bc
- bf
, bc
, bc
== 1 ? "" : "s");
777 if (Py_VerboseFlag
> 1) {
779 while (list
!= NULL
) {
780 for (i
= 0, p
= &list
->objects
[0];
783 if (PyFloat_Check(p
) && p
->ob_refcnt
!= 0) {
785 PyFloat_AsString(buf
, p
);
787 "# <float at %lx, refcnt=%d, val=%s>\n",
788 p
, p
->ob_refcnt
, buf
);