Updated for 2.1a3
[python/dscho.git] / Objects / floatobject.c
blob2f1cbdf47667009fb79beb84804885a9d62ffb86
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. */
7 #include "Python.h"
9 #include <ctype.h>
11 #ifdef i860
12 /* Cray APP has bogus definition of HUGE_VAL in <math.h> */
13 #undef HUGE_VAL
14 #endif
16 #if defined(HUGE_VAL) && !defined(CHECK)
17 #define CHECK(x) if (errno != 0) ; \
18 else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \
19 else errno = ERANGE
20 #endif
22 #ifndef CHECK
23 #define CHECK(x) /* Don't know how to check */
24 #endif
26 #if !defined(__STDC__) && !defined(macintosh)
27 extern double fmod(double, double);
28 extern double pow(double, double);
29 #endif
31 #ifdef sun
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
39 #endif
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))
46 struct _floatblock {
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 *
57 fill_free_list(void)
59 PyFloatObject *p, *q;
60 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
61 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
62 if (p == NULL)
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;
68 while (--q > p)
69 q->ob_type = (struct _typeobject *)(q-1);
70 q->ob_type = NULL;
71 return p + N_FLOATOBJECTS - 1;
74 PyObject *
75 PyFloat_FromDouble(double fval)
77 register PyFloatObject *op;
78 if (free_list == NULL) {
79 if ((free_list = fill_free_list()) == NULL)
80 return NULL;
82 /* PyObject_New is inlined */
83 op = free_list;
84 free_list = (PyFloatObject *)op->ob_type;
85 PyObject_INIT(op, &PyFloat_Type);
86 op->ob_fval = fval;
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 **************************************************************************/
106 PyObject *
107 PyFloat_FromString(PyObject *v, char **pend)
109 const char *s, *last, *end;
110 double x;
111 char buffer[256]; /* for errors */
112 char s_buffer[256]; /* for objects convertible to a char buffer */
113 int len;
115 if (pend)
116 *pend = NULL;
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");
125 return NULL;
127 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
128 PyUnicode_GET_SIZE(v),
129 s_buffer,
130 NULL))
131 return NULL;
132 s = s_buffer;
133 len = (int)strlen(s);
135 else if (PyObject_AsCharBuffer(v, &s, &len)) {
136 PyErr_SetString(PyExc_TypeError,
137 "float() needs a string argument");
138 return NULL;
141 last = s + len;
142 while (*s && isspace(Py_CHARMASK(*s)))
143 s++;
144 if (*s == '\0') {
145 PyErr_SetString(PyExc_ValueError, "empty string for float()");
146 return NULL;
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
153 * key off errno.
155 PyFPE_START_PROTECT("strtod", return NULL)
156 x = strtod(s, (char **)&end);
157 PyFPE_END_PROTECT(x)
158 errno = 0;
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). */
161 if (end > last)
162 end = last;
163 if (end == s) {
164 sprintf(buffer, "invalid literal for float(): %.200s", s);
165 PyErr_SetString(PyExc_ValueError, buffer);
166 return NULL;
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)))
171 end++;
172 if (*end != '\0') {
173 sprintf(buffer, "invalid literal for float(): %.200s", s);
174 PyErr_SetString(PyExc_ValueError, buffer);
175 return NULL;
177 else if (end != last) {
178 PyErr_SetString(PyExc_ValueError,
179 "null byte in argument for float()");
180 return NULL;
182 if (x == 0.0) {
183 /* See above -- may have been strtod being anal
184 about denorms. */
185 PyFPE_START_PROTECT("atof", return NULL)
186 x = atof(s);
187 PyFPE_END_PROTECT(x)
188 errno = 0; /* whether atof ever set errno is undefined */
190 return PyFloat_FromDouble(x);
193 static void
194 float_dealloc(PyFloatObject *op)
196 op->ob_type = (struct _typeobject *)free_list;
197 free_list = op;
200 double
201 PyFloat_AsDouble(PyObject *op)
203 PyNumberMethods *nb;
204 PyFloatObject *fo;
205 double val;
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) {
212 PyErr_BadArgument();
213 return -1;
216 fo = (PyFloatObject*) (*nb->nb_float) (op);
217 if (fo == NULL)
218 return -1;
219 if (!PyFloat_Check(fo)) {
220 PyErr_SetString(PyExc_TypeError,
221 "nb_float should return float object");
222 return -1;
225 val = PyFloat_AS_DOUBLE(fo);
226 Py_DECREF(fo);
228 return val;
231 /* Methods */
233 void
234 PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
236 register char *cp;
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);
243 cp = buf;
244 if (*cp == '-')
245 cp++;
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)))
250 break;
252 if (*cp == '\0') {
253 *cp++ = '.';
254 *cp++ = '0';
255 *cp++ = '\0';
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
261 slot function */
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) \
267 return obj;
269 static int
270 convert_to_double(PyObject **v,
271 double *dbl)
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)
283 else {
284 Py_INCREF(Py_NotImplemented);
285 *v = Py_NotImplemented;
286 return -1;
288 return 0;
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
297 hardware.
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.
305 #define PREC_REPR 17
306 #define PREC_STR 12
308 void
309 PyFloat_AsString(char *buf, PyFloatObject *v)
311 PyFloat_AsStringEx(buf, v, PREC_STR);
314 /* ARGSUSED */
315 static int
316 float_print(PyFloatObject *v, FILE *fp, int flags)
317 /* flags -- not used but required by interface */
319 char buf[100];
320 PyFloat_AsStringEx(buf, v, flags&Py_PRINT_RAW ? PREC_STR : PREC_REPR);
321 fputs(buf, fp);
322 return 0;
325 static PyObject *
326 float_repr(PyFloatObject *v)
328 char buf[100];
329 PyFloat_AsStringEx(buf, v, PREC_REPR);
330 return PyString_FromString(buf);
333 static PyObject *
334 float_str(PyFloatObject *v)
336 char buf[100];
337 PyFloat_AsStringEx(buf, v, PREC_STR);
338 return PyString_FromString(buf);
341 static int
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;
349 static long
350 float_hash(PyFloatObject *v)
352 return _Py_HashDouble(v->ob_fval);
355 static PyObject *
356 float_add(PyObject *v, PyObject *w)
358 double a,b;
359 CONVERT_TO_DOUBLE(v, a);
360 CONVERT_TO_DOUBLE(w, b);
361 PyFPE_START_PROTECT("add", return 0)
362 a = a + b;
363 PyFPE_END_PROTECT(a)
364 return PyFloat_FromDouble(a);
367 static PyObject *
368 float_sub(PyObject *v, PyObject *w)
370 double a,b;
371 CONVERT_TO_DOUBLE(v, a);
372 CONVERT_TO_DOUBLE(w, b);
373 PyFPE_START_PROTECT("subtract", return 0)
374 a = a - b;
375 PyFPE_END_PROTECT(a)
376 return PyFloat_FromDouble(a);
379 static PyObject *
380 float_mul(PyObject *v, PyObject *w)
382 double a,b;
383 CONVERT_TO_DOUBLE(v, a);
384 CONVERT_TO_DOUBLE(w, b);
385 PyFPE_START_PROTECT("multiply", return 0)
386 a = a * b;
387 PyFPE_END_PROTECT(a)
388 return PyFloat_FromDouble(a);
391 static PyObject *
392 float_div(PyObject *v, PyObject *w)
394 double a,b;
395 CONVERT_TO_DOUBLE(v, a);
396 CONVERT_TO_DOUBLE(w, b);
397 if (b == 0.0) {
398 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
399 return NULL;
401 PyFPE_START_PROTECT("divide", return 0)
402 a = a / b;
403 PyFPE_END_PROTECT(a)
404 return PyFloat_FromDouble(a);
407 static PyObject *
408 float_rem(PyObject *v, PyObject *w)
410 double vx, wx;
411 double mod;
412 CONVERT_TO_DOUBLE(v, vx);
413 CONVERT_TO_DOUBLE(w, wx);
414 if (wx == 0.0) {
415 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
416 return NULL;
418 PyFPE_START_PROTECT("modulo", return 0)
419 mod = fmod(vx, wx);
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))) {
423 mod += wx;
425 PyFPE_END_PROTECT(mod)
426 return PyFloat_FromDouble(mod);
429 static PyObject *
430 float_divmod(PyObject *v, PyObject *w)
432 double vx, wx;
433 double div, mod, floordiv;
434 CONVERT_TO_DOUBLE(v, vx);
435 CONVERT_TO_DOUBLE(w, wx);
436 if (wx == 0.0) {
437 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
438 return NULL;
440 PyFPE_START_PROTECT("divmod", return 0)
441 mod = fmod(vx, wx);
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))) {
452 mod += wx;
453 div -= 1.0;
455 /* snap quotient to nearest integral value */
456 floordiv = floor(div);
457 if (div - floordiv > 0.5)
458 floordiv += 1.0;
459 PyFPE_END_PROTECT(div)
460 return Py_BuildValue("(dd)", floordiv, mod);
463 static double powu(double x, long n)
465 double r = 1.;
466 double p = x;
467 long mask = 1;
468 while (mask > 0 && n >= mask) {
469 if (n & mask)
470 r *= p;
471 mask <<= 1;
472 p *= p;
474 return r;
477 static PyObject *
478 float_pow(PyObject *v, PyObject *w, PyObject *z)
480 double iv, iw, ix;
481 long intw;
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.
485 * [AMK]
487 CONVERT_TO_DOUBLE(v, iv);
488 CONVERT_TO_DOUBLE(w, iw);
489 intw = (long)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) {
495 double iz;
496 CONVERT_TO_DOUBLE(z, iz);
497 ix=fmod(1.0, iz);
498 if (ix!=0 && iz<0) ix+=iz;
500 else
501 ix = 1.0;
502 PyFPE_END_PROTECT(ix)
503 return PyFloat_FromDouble(ix);
505 if (iv == 0.0) {
506 if (iw < 0.0) {
507 PyErr_SetString(PyExc_ZeroDivisionError,
508 "0.0 cannot be raised to a negative power");
509 return NULL;
511 return PyFloat_FromDouble(0.0);
514 if (iw == intw && intw > LONG_MIN) {
515 /* ruled out LONG_MIN because -LONG_MIN isn't representable */
516 errno = 0;
517 PyFPE_START_PROTECT("pow", return NULL)
518 if (intw > 0)
519 ix = powu(iv, intw);
520 else
521 ix = 1./powu(iv, -intw);
522 PyFPE_END_PROTECT(ix)
524 else {
525 /* Sort out special cases here instead of relying on pow() */
526 if (iv < 0.0) {
527 PyErr_SetString(PyExc_ValueError,
528 "negative number cannot be raised to a fractional power");
529 return NULL;
531 errno = 0;
532 PyFPE_START_PROTECT("pow", return NULL)
533 ix = pow(iv, iw);
534 PyFPE_END_PROTECT(ix)
536 CHECK(ix);
537 if (errno != 0) {
538 /* XXX could it be another type of error? */
539 PyErr_SetFromErrno(PyExc_OverflowError);
540 return NULL;
542 if ((PyObject *)z != Py_None) {
543 double iz;
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) )) {
548 ix+=iz;
550 PyFPE_END_PROTECT(ix)
552 return PyFloat_FromDouble(ix);
555 static PyObject *
556 float_neg(PyFloatObject *v)
558 return PyFloat_FromDouble(-v->ob_fval);
561 static PyObject *
562 float_pos(PyFloatObject *v)
564 Py_INCREF(v);
565 return (PyObject *)v;
568 static PyObject *
569 float_abs(PyFloatObject *v)
571 if (v->ob_fval < 0)
572 return float_neg(v);
573 else
574 return float_pos(v);
577 static int
578 float_nonzero(PyFloatObject *v)
580 return v->ob_fval != 0.0;
583 static int
584 float_coerce(PyObject **pv, PyObject **pw)
586 if (PyInt_Check(*pw)) {
587 long x = PyInt_AsLong(*pw);
588 *pw = PyFloat_FromDouble((double)x);
589 Py_INCREF(*pv);
590 return 0;
592 else if (PyLong_Check(*pw)) {
593 *pw = PyFloat_FromDouble(PyLong_AsDouble(*pw));
594 Py_INCREF(*pv);
595 return 0;
597 return 1; /* Can't do it */
600 static PyObject *
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");
608 return NULL;
610 return PyInt_FromLong((long)x);
613 static PyObject *
614 float_long(PyObject *v)
616 double x = PyFloat_AsDouble(v);
617 return PyLong_FromDouble(x);
620 static PyObject *
621 float_float(PyObject *v)
623 Py_INCREF(v);
624 return 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*/
640 0, /*nb_invert*/
641 0, /*nb_lshift*/
642 0, /*nb_rshift*/
643 0, /*nb_and*/
644 0, /*nb_xor*/
645 0, /*nb_or*/
646 (coercion)float_coerce, /*nb_coerce*/
647 (unaryfunc)float_int, /*nb_int*/
648 (unaryfunc)float_long, /*nb_long*/
649 (unaryfunc)float_float, /*nb_float*/
650 0, /*nb_oct*/
651 0, /*nb_hex*/
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*/
662 0, /*nb_inplace_or*/
665 PyTypeObject PyFloat_Type = {
666 PyObject_HEAD_INIT(&PyType_Type)
668 "float",
669 sizeof(PyFloatObject),
671 (destructor)float_dealloc, /*tp_dealloc*/
672 (printfunc)float_print, /*tp_print*/
673 0, /*tp_getattr*/
674 0, /*tp_setattr*/
675 (cmpfunc)float_compare, /*tp_compare*/
676 (reprfunc)float_repr, /*tp_repr*/
677 &float_as_number, /*tp_as_number*/
678 0, /*tp_as_sequence*/
679 0, /*tp_as_mapping*/
680 (hashfunc)float_hash, /*tp_hash*/
681 0, /*tp_call*/
682 (reprfunc)float_str, /*tp_str*/
683 0, /*tp_getattro*/
684 0, /*tp_setattro*/
685 0, /*tp_as_buffer*/
686 Py_TPFLAGS_CHECKTYPES /*tp_flags*/
689 void
690 PyFloat_Fini(void)
692 PyFloatObject *p;
693 PyFloatBlock *list, *next;
694 int i;
695 int bc, bf; /* block count, number of freed blocks */
696 int frem, fsum; /* remaining unfreed floats per block, total */
698 bc = 0;
699 bf = 0;
700 fsum = 0;
701 list = block_list;
702 block_list = NULL;
703 free_list = NULL;
704 while (list != NULL) {
705 bc++;
706 frem = 0;
707 for (i = 0, p = &list->objects[0];
708 i < N_FLOATOBJECTS;
709 i++, p++) {
710 if (PyFloat_Check(p) && p->ob_refcnt != 0)
711 frem++;
713 next = list->next;
714 if (frem) {
715 list->next = block_list;
716 block_list = list;
717 for (i = 0, p = &list->objects[0];
718 i < N_FLOATOBJECTS;
719 i++, p++) {
720 if (!PyFloat_Check(p) || p->ob_refcnt == 0) {
721 p->ob_type = (struct _typeobject *)
722 free_list;
723 free_list = p;
727 else {
728 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
729 bf++;
731 fsum += frem;
732 list = next;
734 if (!Py_VerboseFlag)
735 return;
736 fprintf(stderr, "# cleanup floats");
737 if (!fsum) {
738 fprintf(stderr, "\n");
740 else {
741 fprintf(stderr,
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) {
747 list = block_list;
748 while (list != NULL) {
749 for (i = 0, p = &list->objects[0];
750 i < N_FLOATOBJECTS;
751 i++, p++) {
752 if (PyFloat_Check(p) && p->ob_refcnt != 0) {
753 char buf[100];
754 PyFloat_AsString(buf, p);
755 fprintf(stderr,
756 "# <float at %p, refcnt=%d, val=%s>\n",
757 p, p->ob_refcnt, buf);
760 list = list->next;