Added 'description' class attribute to every command class (to help the
[python/dscho.git] / Objects / floatobject.c
blob6430a98e78c82901e604e34663262e6e9cd5ac55
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
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
15 permission.
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. */
37 #include "Python.h"
39 #include <ctype.h>
40 #include "mymath.h"
42 #ifdef i860
43 /* Cray APP has bogus definition of HUGE_VAL in <math.h> */
44 #undef HUGE_VAL
45 #endif
47 #if defined(HUGE_VAL) && !defined(CHECK)
48 #define CHECK(x) if (errno != 0) ; \
49 else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \
50 else errno = ERANGE
51 #endif
53 #ifndef CHECK
54 #define CHECK(x) /* Don't know how to check */
55 #endif
57 #ifdef HAVE_LIMITS_H
58 #include <limits.h>
59 #endif
61 #ifndef LONG_MAX
62 #define LONG_MAX 0X7FFFFFFFL
63 #endif
65 #ifndef LONG_MIN
66 #define LONG_MIN (-LONG_MAX-1)
67 #endif
69 #ifdef __NeXT__
70 #ifdef __sparc__
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
76 #undef LONG_MIN
77 #define LONG_MIN (-LONG_MAX-1)
78 #endif
79 #endif
81 #if !defined(__STDC__) && !defined(macintosh)
82 extern double fmod Py_PROTO((double, double));
83 extern double pow Py_PROTO((double, double));
84 #endif
86 #ifdef sun
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
94 #endif
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
104 struct _floatblock {
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 *
115 fill_free_list()
117 PyFloatObject *p, *q;
118 p = (PyFloatObject *)PyMem_MALLOC(sizeof(PyFloatBlock));
119 if (p == NULL)
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;
125 while (--q > p)
126 q->ob_type = (struct _typeobject *)(q-1);
127 q->ob_type = NULL;
128 return p + N_FLOATOBJECTS - 1;
131 PyObject *
132 #ifdef __SC__
133 PyFloat_FromDouble(double fval)
134 #else
135 PyFloat_FromDouble(fval)
136 double fval;
137 #endif
139 register PyFloatObject *op;
140 if (free_list == NULL) {
141 if ((free_list = fill_free_list()) == NULL)
142 return NULL;
144 op = free_list;
145 free_list = (PyFloatObject *)op->ob_type;
146 op->ob_type = &PyFloat_Type;
147 op->ob_fval = fval;
148 _Py_NewReference((PyObject *)op);
149 return (PyObject *) op;
152 PyObject *
153 PyFloat_FromString(v, pend)
154 PyObject *v;
155 char **pend;
157 extern double strtod Py_PROTO((const char *, char **));
158 char *s, *last, *end;
159 double x;
160 char buffer[256]; /* For errors */
162 if (!PyString_Check(v))
163 return NULL;
164 s = PyString_AS_STRING(v);
166 last = s + PyString_GET_SIZE(v);
167 while (*s && isspace(Py_CHARMASK(*s)))
168 s++;
169 if (s[0] == '\0') {
170 PyErr_SetString(PyExc_ValueError, "empty string for float()");
171 return NULL;
173 errno = 0;
174 PyFPE_START_PROTECT("PyFloat_FromString", return 0)
175 x = strtod(s, &end);
176 PyFPE_END_PROTECT(x)
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) */
179 if (end > last)
180 end = last;
181 while (*end && isspace(Py_CHARMASK(*end)))
182 end++;
183 if (*end != '\0') {
184 sprintf(buffer, "invalid literal for float(): %.200s", s);
185 PyErr_SetString(PyExc_ValueError, buffer);
186 return NULL;
188 else if (end != PyString_AS_STRING(v) + PyString_GET_SIZE(v)) {
189 PyErr_SetString(PyExc_ValueError,
190 "null byte in argument for float()");
191 return NULL;
193 else if (errno != 0) {
194 sprintf(buffer, "float() literal too large: %.200s", s);
195 PyErr_SetString(PyExc_ValueError, buffer);
196 return NULL;
198 if (pend)
199 *pend = end;
200 return PyFloat_FromDouble(x);
203 static void
204 float_dealloc(op)
205 PyFloatObject *op;
207 op->ob_type = (struct _typeobject *)free_list;
208 free_list = op;
211 double
212 PyFloat_AsDouble(op)
213 PyObject *op;
215 PyNumberMethods *nb;
216 PyFloatObject *fo;
217 double val;
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) {
224 PyErr_BadArgument();
225 return -1;
228 fo = (PyFloatObject*) (*nb->nb_float) (op);
229 if (fo == NULL)
230 return -1;
231 if (!PyFloat_Check(fo)) {
232 PyErr_SetString(PyExc_TypeError,
233 "nb_float should return float object");
234 return -1;
237 val = PyFloat_AS_DOUBLE(fo);
238 Py_DECREF(fo);
240 return val;
243 /* Methods */
245 void
246 PyFloat_AsStringEx(buf, v, precision)
247 char *buf;
248 PyFloatObject *v;
249 int precision;
251 register char *cp;
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);
258 cp = buf;
259 if (*cp == '-')
260 cp++;
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)))
265 break;
267 if (*cp == '\0') {
268 *cp++ = '.';
269 *cp++ = '0';
270 *cp++ = '\0';
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
280 hardware.
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.
288 #define PREC_REPR 17
289 #define PREC_STR 12
291 void
292 PyFloat_AsString(buf, v)
293 char *buf;
294 PyFloatObject *v;
296 PyFloat_AsStringEx(buf, v, PREC_STR);
299 /* ARGSUSED */
300 static int
301 float_print(v, fp, flags)
302 PyFloatObject *v;
303 FILE *fp;
304 int flags; /* Not used but required by interface */
306 char buf[100];
307 PyFloat_AsStringEx(buf, v, flags&Py_PRINT_RAW ? PREC_STR : PREC_REPR);
308 fputs(buf, fp);
309 return 0;
312 static PyObject *
313 float_repr(v)
314 PyFloatObject *v;
316 char buf[100];
317 PyFloat_AsStringEx(buf, v, PREC_REPR);
318 return PyString_FromString(buf);
321 static PyObject *
322 float_str(v)
323 PyFloatObject *v;
325 char buf[100];
326 PyFloat_AsStringEx(buf, v, PREC_STR);
327 return PyString_FromString(buf);
330 static int
331 float_compare(v, w)
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;
339 static long
340 float_hash(v)
341 PyFloatObject *v;
343 double intpart, fractpart;
344 int expo;
345 long x;
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 */
352 extended e;
353 fractpart = modf(v->ob_fval, &e);
354 intpart = e;
356 #else
357 fractpart = modf(v->ob_fval, &intpart);
358 #endif
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);
364 if (w == NULL)
365 return -1;
366 x = PyObject_Hash(w);
367 Py_DECREF(w);
368 return x;
370 x = (long)intpart;
372 else {
373 /* Note -- if you change this code, also change the copy
374 in complexobject.c */
375 long hipart;
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 */
384 if (x == -1)
385 x = -2;
386 return x;
389 static PyObject *
390 float_add(v, w)
391 PyFloatObject *v;
392 PyFloatObject *w;
394 double result;
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);
401 static PyObject *
402 float_sub(v, w)
403 PyFloatObject *v;
404 PyFloatObject *w;
406 double 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);
413 static PyObject *
414 float_mul(v, w)
415 PyFloatObject *v;
416 PyFloatObject *w;
418 double 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);
426 static PyObject *
427 float_div(v, w)
428 PyFloatObject *v;
429 PyFloatObject *w;
431 double result;
432 if (w->ob_fval == 0) {
433 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
434 return NULL;
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);
442 static PyObject *
443 float_rem(v, w)
444 PyFloatObject *v;
445 PyFloatObject *w;
447 double vx, wx;
448 double mod;
449 wx = w->ob_fval;
450 if (wx == 0.0) {
451 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
452 return NULL;
454 PyFPE_START_PROTECT("modulo", return 0)
455 vx = v->ob_fval;
456 mod = fmod(vx, wx);
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))) {
460 mod += wx;
462 PyFPE_END_PROTECT(mod)
463 return PyFloat_FromDouble(mod);
466 static PyObject *
467 float_divmod(v, w)
468 PyFloatObject *v;
469 PyFloatObject *w;
471 double vx, wx;
472 double div, mod, floordiv;
473 wx = w->ob_fval;
474 if (wx == 0.0) {
475 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
476 return NULL;
478 PyFPE_START_PROTECT("divmod", return 0)
479 vx = v->ob_fval;
480 mod = fmod(vx, wx);
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))) {
491 mod += wx;
492 div -= 1.0;
494 /* snap quotient to nearest integral value */
495 floordiv = floor(div);
496 if (div - floordiv > 0.5)
497 floordiv += 1.0;
498 PyFPE_END_PROTECT(div)
499 return Py_BuildValue("(dd)", floordiv, mod);
502 static double powu(x, n)
503 double x;
504 long n;
506 double r = 1.;
507 double p = x;
508 long mask = 1;
509 while (mask > 0 && n >= mask) {
510 if (n & mask)
511 r *= p;
512 mask <<= 1;
513 p *= p;
515 return r;
518 static PyObject *
519 float_pow(v, w, z)
520 PyFloatObject *v;
521 PyObject *w;
522 PyFloatObject *z;
524 double iv, iw, ix;
525 long intw;
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.
529 * [AMK]
531 iv = v->ob_fval;
532 iw = ((PyFloatObject *)w)->ob_fval;
533 intw = (long)iw;
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;
542 else ix=1.0;
543 PyFPE_END_PROTECT(ix)
544 return PyFloat_FromDouble(ix);
546 errno = 0;
547 PyFPE_START_PROTECT("pow", return 0)
548 if (intw > 0)
549 ix = powu(iv, intw);
550 else
551 ix = 1./powu(iv, -intw);
552 PyFPE_END_PROTECT(ix)
554 else {
555 /* Sort out special cases here instead of relying on pow() */
556 if (iv == 0.0) {
557 if (iw < 0.0) {
558 PyErr_SetString(PyExc_ValueError,
559 "0.0 to a negative power");
560 return NULL;
562 return PyFloat_FromDouble(0.0);
564 if (iv < 0.0) {
565 PyErr_SetString(PyExc_ValueError,
566 "negative number to a float power");
567 return NULL;
569 errno = 0;
570 PyFPE_START_PROTECT("pow", return 0)
571 ix = pow(iv, iw);
572 PyFPE_END_PROTECT(ix)
574 CHECK(ix);
575 if (errno != 0) {
576 /* XXX could it be another type of error? */
577 PyErr_SetFromErrno(PyExc_OverflowError);
578 return NULL;
580 if ((PyObject *)z!=Py_None) {
581 PyFPE_START_PROTECT("pow", return 0)
582 ix=fmod(ix, z->ob_fval); /* XXX To Be Rewritten */
583 if ( ix!=0 &&
584 ((iv<0 && z->ob_fval>0) || (iv>0 && z->ob_fval<0) )) {
585 ix+=z->ob_fval;
587 PyFPE_END_PROTECT(ix)
589 return PyFloat_FromDouble(ix);
592 static PyObject *
593 float_neg(v)
594 PyFloatObject *v;
596 return PyFloat_FromDouble(-v->ob_fval);
599 static PyObject *
600 float_pos(v)
601 PyFloatObject *v;
603 Py_INCREF(v);
604 return (PyObject *)v;
607 static PyObject *
608 float_abs(v)
609 PyFloatObject *v;
611 if (v->ob_fval < 0)
612 return float_neg(v);
613 else
614 return float_pos(v);
617 static int
618 float_nonzero(v)
619 PyFloatObject *v;
621 return v->ob_fval != 0.0;
624 static int
625 float_coerce(pv, pw)
626 PyObject **pv;
627 PyObject **pw;
629 if (PyInt_Check(*pw)) {
630 long x = PyInt_AsLong(*pw);
631 *pw = PyFloat_FromDouble((double)x);
632 Py_INCREF(*pv);
633 return 0;
635 else if (PyLong_Check(*pw)) {
636 *pw = PyFloat_FromDouble(PyLong_AsDouble(*pw));
637 Py_INCREF(*pv);
638 return 0;
640 return 1; /* Can't do it */
643 static PyObject *
644 float_int(v)
645 PyObject *v;
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");
652 return NULL;
654 return PyInt_FromLong((long)x);
657 static PyObject *
658 float_long(v)
659 PyObject *v;
661 double x = PyFloat_AsDouble(v);
662 return PyLong_FromDouble(x);
665 static PyObject *
666 float_float(v)
667 PyObject *v;
669 Py_INCREF(v);
670 return v;
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*/
686 0, /*nb_invert*/
687 0, /*nb_lshift*/
688 0, /*nb_rshift*/
689 0, /*nb_and*/
690 0, /*nb_xor*/
691 0, /*nb_or*/
692 (coercion)float_coerce, /*nb_coerce*/
693 (unaryfunc)float_int, /*nb_int*/
694 (unaryfunc)float_long, /*nb_long*/
695 (unaryfunc)float_float, /*nb_float*/
696 0, /*nb_oct*/
697 0, /*nb_hex*/
700 PyTypeObject PyFloat_Type = {
701 PyObject_HEAD_INIT(&PyType_Type)
703 "float",
704 sizeof(PyFloatObject),
706 (destructor)float_dealloc, /*tp_dealloc*/
707 (printfunc)float_print, /*tp_print*/
708 0, /*tp_getattr*/
709 0, /*tp_setattr*/
710 (cmpfunc)float_compare, /*tp_compare*/
711 (reprfunc)float_repr, /*tp_repr*/
712 &float_as_number, /*tp_as_number*/
713 0, /*tp_as_sequence*/
714 0, /*tp_as_mapping*/
715 (hashfunc)float_hash, /*tp_hash*/
716 0, /*tp_call*/
717 (reprfunc)float_str, /*tp_str*/
720 void
721 PyFloat_Fini()
723 PyFloatObject *p;
724 PyFloatBlock *list, *next;
725 int i;
726 int bc, bf; /* block count, number of freed blocks */
727 int frem, fsum; /* remaining unfreed floats per block, total */
729 bc = 0;
730 bf = 0;
731 fsum = 0;
732 list = block_list;
733 block_list = NULL;
734 free_list = NULL;
735 while (list != NULL) {
736 bc++;
737 frem = 0;
738 for (i = 0, p = &list->objects[0];
739 i < N_FLOATOBJECTS;
740 i++, p++) {
741 if (PyFloat_Check(p) && p->ob_refcnt != 0)
742 frem++;
744 next = list->next;
745 if (frem) {
746 list->next = block_list;
747 block_list = list;
748 for (i = 0, p = &list->objects[0];
749 i < N_FLOATOBJECTS;
750 i++, p++) {
751 if (!PyFloat_Check(p) || p->ob_refcnt == 0) {
752 p->ob_type = (struct _typeobject *)
753 free_list;
754 free_list = p;
758 else {
759 PyMem_FREE(list);
760 bf++;
762 fsum += frem;
763 list = next;
765 if (!Py_VerboseFlag)
766 return;
767 fprintf(stderr, "# cleanup floats");
768 if (!fsum) {
769 fprintf(stderr, "\n");
771 else {
772 fprintf(stderr,
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) {
778 list = block_list;
779 while (list != NULL) {
780 for (i = 0, p = &list->objects[0];
781 i < N_FLOATOBJECTS;
782 i++, p++) {
783 if (PyFloat_Check(p) && p->ob_refcnt != 0) {
784 char buf[100];
785 PyFloat_AsString(buf, p);
786 fprintf(stderr,
787 "# <float at %lx, refcnt=%d, val=%s>\n",
788 p, p->ob_refcnt, buf);
791 list = list->next;