This commit was manufactured by cvs2svn to create tag 'r23b1-mac'.
[python/dscho.git] / Objects / floatobject.c
blobf7601ba9e7d46daecb1a1b78a5706651ea8027b4
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 #if !defined(__STDC__) && !defined(macintosh)
12 extern double fmod(double, double);
13 extern double pow(double, double);
14 #endif
16 #if defined(sun) && !defined(__SVR4)
17 /* On SunOS4.1 only libm.a exists. Make sure that references to all
18 needed math functions exist in the executable, so that dynamic
19 loading of mathmodule does not fail. */
20 double (*_Py_math_funcs_hack[])() = {
21 acos, asin, atan, atan2, ceil, cos, cosh, exp, fabs, floor,
22 fmod, log, log10, pow, sin, sinh, sqrt, tan, tanh
24 #endif
26 /* Special free list -- see comments for same code in intobject.c. */
27 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
28 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
29 #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
31 struct _floatblock {
32 struct _floatblock *next;
33 PyFloatObject objects[N_FLOATOBJECTS];
36 typedef struct _floatblock PyFloatBlock;
38 static PyFloatBlock *block_list = NULL;
39 static PyFloatObject *free_list = NULL;
41 static PyFloatObject *
42 fill_free_list(void)
44 PyFloatObject *p, *q;
45 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
46 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
47 if (p == NULL)
48 return (PyFloatObject *) PyErr_NoMemory();
49 ((PyFloatBlock *)p)->next = block_list;
50 block_list = (PyFloatBlock *)p;
51 p = &((PyFloatBlock *)p)->objects[0];
52 q = p + N_FLOATOBJECTS;
53 while (--q > p)
54 q->ob_type = (struct _typeobject *)(q-1);
55 q->ob_type = NULL;
56 return p + N_FLOATOBJECTS - 1;
59 PyObject *
60 PyFloat_FromDouble(double fval)
62 register PyFloatObject *op;
63 if (free_list == NULL) {
64 if ((free_list = fill_free_list()) == NULL)
65 return NULL;
67 /* Inline PyObject_New */
68 op = free_list;
69 free_list = (PyFloatObject *)op->ob_type;
70 PyObject_INIT(op, &PyFloat_Type);
71 op->ob_fval = fval;
72 return (PyObject *) op;
75 /**************************************************************************
76 RED_FLAG 22-Sep-2000 tim
77 PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
79 1. If v was a regular string, *pend was set to point to its terminating
80 null byte. That's useless (the caller can find that without any
81 help from this function!).
83 2. If v was a Unicode string, or an object convertible to a character
84 buffer, *pend was set to point into stack trash (the auto temp
85 vector holding the character buffer). That was downright dangerous.
87 Since we can't change the interface of a public API function, pend is
88 still supported but now *officially* useless: if pend is not NULL,
89 *pend is set to NULL.
90 **************************************************************************/
91 PyObject *
92 PyFloat_FromString(PyObject *v, char **pend)
94 const char *s, *last, *end;
95 double x;
96 char buffer[256]; /* for errors */
97 #ifdef Py_USING_UNICODE
98 char s_buffer[256]; /* for objects convertible to a char buffer */
99 #endif
100 int len;
102 if (pend)
103 *pend = NULL;
104 if (PyString_Check(v)) {
105 s = PyString_AS_STRING(v);
106 len = PyString_GET_SIZE(v);
108 #ifdef Py_USING_UNICODE
109 else if (PyUnicode_Check(v)) {
110 if (PyUnicode_GET_SIZE(v) >= sizeof(s_buffer)) {
111 PyErr_SetString(PyExc_ValueError,
112 "Unicode float() literal too long to convert");
113 return NULL;
115 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
116 PyUnicode_GET_SIZE(v),
117 s_buffer,
118 NULL))
119 return NULL;
120 s = s_buffer;
121 len = (int)strlen(s);
123 #endif
124 else if (PyObject_AsCharBuffer(v, &s, &len)) {
125 PyErr_SetString(PyExc_TypeError,
126 "float() argument must be a string or a number");
127 return NULL;
130 last = s + len;
131 while (*s && isspace(Py_CHARMASK(*s)))
132 s++;
133 if (*s == '\0') {
134 PyErr_SetString(PyExc_ValueError, "empty string for float()");
135 return NULL;
137 /* We don't care about overflow or underflow. If the platform supports
138 * them, infinities and signed zeroes (on underflow) are fine.
139 * However, strtod can return 0 for denormalized numbers, where atof
140 * does not. So (alas!) we special-case a zero result. Note that
141 * whether strtod sets errno on underflow is not defined, so we can't
142 * key off errno.
144 PyFPE_START_PROTECT("strtod", return NULL)
145 x = strtod(s, (char **)&end);
146 PyFPE_END_PROTECT(x)
147 errno = 0;
148 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
149 byte at the end of the string, when the input is inf(inity). */
150 if (end > last)
151 end = last;
152 if (end == s) {
153 PyOS_snprintf(buffer, sizeof(buffer),
154 "invalid literal for float(): %.200s", s);
155 PyErr_SetString(PyExc_ValueError, buffer);
156 return NULL;
158 /* Since end != s, the platform made *some* kind of sense out
159 of the input. Trust it. */
160 while (*end && isspace(Py_CHARMASK(*end)))
161 end++;
162 if (*end != '\0') {
163 PyOS_snprintf(buffer, sizeof(buffer),
164 "invalid literal for float(): %.200s", s);
165 PyErr_SetString(PyExc_ValueError, buffer);
166 return NULL;
168 else if (end != last) {
169 PyErr_SetString(PyExc_ValueError,
170 "null byte in argument for float()");
171 return NULL;
173 if (x == 0.0) {
174 /* See above -- may have been strtod being anal
175 about denorms. */
176 PyFPE_START_PROTECT("atof", return NULL)
177 x = atof(s);
178 PyFPE_END_PROTECT(x)
179 errno = 0; /* whether atof ever set errno is undefined */
181 return PyFloat_FromDouble(x);
184 static void
185 float_dealloc(PyFloatObject *op)
187 if (PyFloat_CheckExact(op)) {
188 op->ob_type = (struct _typeobject *)free_list;
189 free_list = op;
191 else
192 op->ob_type->tp_free((PyObject *)op);
195 double
196 PyFloat_AsDouble(PyObject *op)
198 PyNumberMethods *nb;
199 PyFloatObject *fo;
200 double val;
202 if (op && PyFloat_Check(op))
203 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
205 if (op == NULL) {
206 PyErr_BadArgument();
207 return -1;
210 if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) {
211 PyErr_SetString(PyExc_TypeError, "a float is required");
212 return -1;
215 fo = (PyFloatObject*) (*nb->nb_float) (op);
216 if (fo == NULL)
217 return -1;
218 if (!PyFloat_Check(fo)) {
219 PyErr_SetString(PyExc_TypeError,
220 "nb_float should return float object");
221 return -1;
224 val = PyFloat_AS_DOUBLE(fo);
225 Py_DECREF(fo);
227 return val;
230 /* Methods */
232 static void
233 format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
235 register char *cp;
236 /* Subroutine for float_repr and float_print.
237 We want float numbers to be recognizable as such,
238 i.e., they should contain a decimal point or an exponent.
239 However, %g may print the number as an integer;
240 in such cases, we append ".0" to the string. */
242 assert(PyFloat_Check(v));
243 PyOS_snprintf(buf, buflen, "%.*g", precision, v->ob_fval);
244 cp = buf;
245 if (*cp == '-')
246 cp++;
247 for (; *cp != '\0'; cp++) {
248 /* Any non-digit means it's not an integer;
249 this takes care of NAN and INF as well. */
250 if (!isdigit(Py_CHARMASK(*cp)))
251 break;
253 if (*cp == '\0') {
254 *cp++ = '.';
255 *cp++ = '0';
256 *cp++ = '\0';
260 /* XXX PyFloat_AsStringEx should not be a public API function (for one
261 XXX thing, its signature passes a buffer without a length; for another,
262 XXX it isn't useful outside this file).
264 void
265 PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
267 format_float(buf, 100, v, precision);
270 /* Macro and helper that convert PyObject obj to a C double and store
271 the value in dbl; this replaces the functionality of the coercion
272 slot function. If conversion to double raises an exception, obj is
273 set to NULL, and the function invoking this macro returns NULL. If
274 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
275 stored in obj, and returned from the function invoking this macro.
277 #define CONVERT_TO_DOUBLE(obj, dbl) \
278 if (PyFloat_Check(obj)) \
279 dbl = PyFloat_AS_DOUBLE(obj); \
280 else if (convert_to_double(&(obj), &(dbl)) < 0) \
281 return obj;
283 static int
284 convert_to_double(PyObject **v, double *dbl)
286 register PyObject *obj = *v;
288 if (PyInt_Check(obj)) {
289 *dbl = (double)PyInt_AS_LONG(obj);
291 else if (PyLong_Check(obj)) {
292 *dbl = PyLong_AsDouble(obj);
293 if (*dbl == -1.0 && PyErr_Occurred()) {
294 *v = NULL;
295 return -1;
298 else {
299 Py_INCREF(Py_NotImplemented);
300 *v = Py_NotImplemented;
301 return -1;
303 return 0;
306 /* Precisions used by repr() and str(), respectively.
308 The repr() precision (17 significant decimal digits) is the minimal number
309 that is guaranteed to have enough precision so that if the number is read
310 back in the exact same binary value is recreated. This is true for IEEE
311 floating point by design, and also happens to work for all other modern
312 hardware.
314 The str() precision is chosen so that in most cases, the rounding noise
315 created by various operations is suppressed, while giving plenty of
316 precision for practical use.
320 #define PREC_REPR 17
321 #define PREC_STR 12
323 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
324 XXX they pass a char buffer without passing a length.
326 void
327 PyFloat_AsString(char *buf, PyFloatObject *v)
329 format_float(buf, 100, v, PREC_STR);
332 void
333 PyFloat_AsReprString(char *buf, PyFloatObject *v)
335 format_float(buf, 100, v, PREC_REPR);
338 /* ARGSUSED */
339 static int
340 float_print(PyFloatObject *v, FILE *fp, int flags)
342 char buf[100];
343 format_float(buf, sizeof(buf), v,
344 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
345 fputs(buf, fp);
346 return 0;
349 static PyObject *
350 float_repr(PyFloatObject *v)
352 char buf[100];
353 format_float(buf, sizeof(buf), v, PREC_REPR);
354 return PyString_FromString(buf);
357 static PyObject *
358 float_str(PyFloatObject *v)
360 char buf[100];
361 format_float(buf, sizeof(buf), v, PREC_STR);
362 return PyString_FromString(buf);
365 static int
366 float_compare(PyFloatObject *v, PyFloatObject *w)
368 double i = v->ob_fval;
369 double j = w->ob_fval;
370 return (i < j) ? -1 : (i > j) ? 1 : 0;
373 static long
374 float_hash(PyFloatObject *v)
376 return _Py_HashDouble(v->ob_fval);
379 static PyObject *
380 float_add(PyObject *v, PyObject *w)
382 double a,b;
383 CONVERT_TO_DOUBLE(v, a);
384 CONVERT_TO_DOUBLE(w, b);
385 PyFPE_START_PROTECT("add", return 0)
386 a = a + b;
387 PyFPE_END_PROTECT(a)
388 return PyFloat_FromDouble(a);
391 static PyObject *
392 float_sub(PyObject *v, PyObject *w)
394 double a,b;
395 CONVERT_TO_DOUBLE(v, a);
396 CONVERT_TO_DOUBLE(w, b);
397 PyFPE_START_PROTECT("subtract", return 0)
398 a = a - b;
399 PyFPE_END_PROTECT(a)
400 return PyFloat_FromDouble(a);
403 static PyObject *
404 float_mul(PyObject *v, PyObject *w)
406 double a,b;
407 CONVERT_TO_DOUBLE(v, a);
408 CONVERT_TO_DOUBLE(w, b);
409 PyFPE_START_PROTECT("multiply", return 0)
410 a = a * b;
411 PyFPE_END_PROTECT(a)
412 return PyFloat_FromDouble(a);
415 static PyObject *
416 float_div(PyObject *v, PyObject *w)
418 double a,b;
419 CONVERT_TO_DOUBLE(v, a);
420 CONVERT_TO_DOUBLE(w, b);
421 if (b == 0.0) {
422 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
423 return NULL;
425 PyFPE_START_PROTECT("divide", return 0)
426 a = a / b;
427 PyFPE_END_PROTECT(a)
428 return PyFloat_FromDouble(a);
431 static PyObject *
432 float_classic_div(PyObject *v, PyObject *w)
434 double a,b;
435 CONVERT_TO_DOUBLE(v, a);
436 CONVERT_TO_DOUBLE(w, b);
437 if (Py_DivisionWarningFlag >= 2 &&
438 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
439 return NULL;
440 if (b == 0.0) {
441 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
442 return NULL;
444 PyFPE_START_PROTECT("divide", return 0)
445 a = a / b;
446 PyFPE_END_PROTECT(a)
447 return PyFloat_FromDouble(a);
450 static PyObject *
451 float_rem(PyObject *v, PyObject *w)
453 double vx, wx;
454 double mod;
455 CONVERT_TO_DOUBLE(v, vx);
456 CONVERT_TO_DOUBLE(w, wx);
457 if (wx == 0.0) {
458 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
459 return NULL;
461 PyFPE_START_PROTECT("modulo", return 0)
462 mod = fmod(vx, wx);
463 /* note: checking mod*wx < 0 is incorrect -- underflows to
464 0 if wx < sqrt(smallest nonzero double) */
465 if (mod && ((wx < 0) != (mod < 0))) {
466 mod += wx;
468 PyFPE_END_PROTECT(mod)
469 return PyFloat_FromDouble(mod);
472 static PyObject *
473 float_divmod(PyObject *v, PyObject *w)
475 double vx, wx;
476 double div, mod, floordiv;
477 CONVERT_TO_DOUBLE(v, vx);
478 CONVERT_TO_DOUBLE(w, wx);
479 if (wx == 0.0) {
480 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
481 return NULL;
483 PyFPE_START_PROTECT("divmod", return 0)
484 mod = fmod(vx, wx);
485 /* fmod is typically exact, so vx-mod is *mathematically* an
486 exact multiple of wx. But this is fp arithmetic, and fp
487 vx - mod is an approximation; the result is that div may
488 not be an exact integral value after the division, although
489 it will always be very close to one.
491 div = (vx - mod) / wx;
492 if (mod) {
493 /* ensure the remainder has the same sign as the denominator */
494 if ((wx < 0) != (mod < 0)) {
495 mod += wx;
496 div -= 1.0;
499 else {
500 /* the remainder is zero, and in the presence of signed zeroes
501 fmod returns different results across platforms; ensure
502 it has the same sign as the denominator; we'd like to do
503 "mod = wx * 0.0", but that may get optimized away */
504 mod *= mod; /* hide "mod = +0" from optimizer */
505 if (wx < 0.0)
506 mod = -mod;
508 /* snap quotient to nearest integral value */
509 if (div) {
510 floordiv = floor(div);
511 if (div - floordiv > 0.5)
512 floordiv += 1.0;
514 else {
515 /* div is zero - get the same sign as the true quotient */
516 div *= div; /* hide "div = +0" from optimizers */
517 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
519 PyFPE_END_PROTECT(floordiv)
520 return Py_BuildValue("(dd)", floordiv, mod);
523 static PyObject *
524 float_floor_div(PyObject *v, PyObject *w)
526 PyObject *t, *r;
528 t = float_divmod(v, w);
529 if (t == NULL || t == Py_NotImplemented)
530 return t;
531 assert(PyTuple_CheckExact(t));
532 r = PyTuple_GET_ITEM(t, 0);
533 Py_INCREF(r);
534 Py_DECREF(t);
535 return r;
538 static PyObject *
539 float_pow(PyObject *v, PyObject *w, PyObject *z)
541 double iv, iw, ix;
543 if ((PyObject *)z != Py_None) {
544 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
545 "allowed unless all arguments are integers");
546 return NULL;
549 CONVERT_TO_DOUBLE(v, iv);
550 CONVERT_TO_DOUBLE(w, iw);
552 /* Sort out special cases here instead of relying on pow() */
553 if (iw == 0) { /* v**0 is 1, even 0**0 */
554 PyFPE_START_PROTECT("pow", return NULL)
555 if ((PyObject *)z != Py_None) {
556 double iz;
557 CONVERT_TO_DOUBLE(z, iz);
558 ix = fmod(1.0, iz);
559 if (ix != 0 && iz < 0)
560 ix += iz;
562 else
563 ix = 1.0;
564 PyFPE_END_PROTECT(ix)
565 return PyFloat_FromDouble(ix);
567 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
568 if (iw < 0.0) {
569 PyErr_SetString(PyExc_ZeroDivisionError,
570 "0.0 cannot be raised to a negative power");
571 return NULL;
573 return PyFloat_FromDouble(0.0);
575 if (iv < 0.0 && iw != floor(iw)) {
576 PyErr_SetString(PyExc_ValueError,
577 "negative number cannot be raised to a fractional power");
578 return NULL;
580 errno = 0;
581 PyFPE_START_PROTECT("pow", return NULL)
582 ix = pow(iv, iw);
583 PyFPE_END_PROTECT(ix)
584 Py_ADJUST_ERANGE1(ix);
585 if (errno != 0) {
586 assert(errno == ERANGE);
587 PyErr_SetFromErrno(PyExc_OverflowError);
588 return NULL;
590 return PyFloat_FromDouble(ix);
593 static PyObject *
594 float_neg(PyFloatObject *v)
596 return PyFloat_FromDouble(-v->ob_fval);
599 static PyObject *
600 float_pos(PyFloatObject *v)
602 if (PyFloat_CheckExact(v)) {
603 Py_INCREF(v);
604 return (PyObject *)v;
606 else
607 return PyFloat_FromDouble(v->ob_fval);
610 static PyObject *
611 float_abs(PyFloatObject *v)
613 return PyFloat_FromDouble(fabs(v->ob_fval));
616 static int
617 float_nonzero(PyFloatObject *v)
619 return v->ob_fval != 0.0;
622 static int
623 float_coerce(PyObject **pv, PyObject **pw)
625 if (PyInt_Check(*pw)) {
626 long x = PyInt_AsLong(*pw);
627 *pw = PyFloat_FromDouble((double)x);
628 Py_INCREF(*pv);
629 return 0;
631 else if (PyLong_Check(*pw)) {
632 double x = PyLong_AsDouble(*pw);
633 if (x == -1.0 && PyErr_Occurred())
634 return -1;
635 *pw = PyFloat_FromDouble(x);
636 Py_INCREF(*pv);
637 return 0;
639 else if (PyFloat_Check(*pw)) {
640 Py_INCREF(*pv);
641 Py_INCREF(*pw);
642 return 0;
644 return 1; /* Can't do it */
647 static PyObject *
648 float_long(PyObject *v)
650 double x = PyFloat_AsDouble(v);
651 return PyLong_FromDouble(x);
654 static PyObject *
655 float_int(PyObject *v)
657 double x = PyFloat_AsDouble(v);
658 double wholepart; /* integral portion of x, rounded toward 0 */
660 (void)modf(x, &wholepart);
661 /* Try to get out cheap if this fits in a Python int. The attempt
662 * to cast to long must be protected, as C doesn't define what
663 * happens if the double is too big to fit in a long. Some rare
664 * systems raise an exception then (RISCOS was mentioned as one,
665 * and someone using a non-default option on Sun also bumped into
666 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
667 * still be vulnerable: if a long has more bits of precision than
668 * a double, casting MIN/MAX to double may yield an approximation,
669 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
670 * yield true from the C expression wholepart<=LONG_MAX, despite
671 * that wholepart is actually greater than LONG_MAX.
673 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
674 const long aslong = (long)wholepart;
675 return PyInt_FromLong(aslong);
677 return PyLong_FromDouble(wholepart);
680 static PyObject *
681 float_float(PyObject *v)
683 Py_INCREF(v);
684 return v;
688 static PyObject *
689 float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
691 static PyObject *
692 float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
694 PyObject *x = Py_False; /* Integer zero */
695 static char *kwlist[] = {"x", 0};
697 if (type != &PyFloat_Type)
698 return float_subtype_new(type, args, kwds); /* Wimp out */
699 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
700 return NULL;
701 if (PyString_Check(x))
702 return PyFloat_FromString(x, NULL);
703 return PyNumber_Float(x);
706 /* Wimpy, slow approach to tp_new calls for subtypes of float:
707 first create a regular float from whatever arguments we got,
708 then allocate a subtype instance and initialize its ob_fval
709 from the regular float. The regular float is then thrown away.
711 static PyObject *
712 float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
714 PyObject *tmp, *new;
716 assert(PyType_IsSubtype(type, &PyFloat_Type));
717 tmp = float_new(&PyFloat_Type, args, kwds);
718 if (tmp == NULL)
719 return NULL;
720 assert(PyFloat_CheckExact(tmp));
721 new = type->tp_alloc(type, 0);
722 if (new == NULL)
723 return NULL;
724 ((PyFloatObject *)new)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
725 Py_DECREF(tmp);
726 return new;
729 static PyObject *
730 float_getnewargs(PyFloatObject *v)
732 return Py_BuildValue("(d)", v->ob_fval);
735 static PyMethodDef float_methods[] = {
736 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
737 {NULL, NULL} /* sentinel */
740 PyDoc_STRVAR(float_doc,
741 "float(x) -> floating point number\n\
743 Convert a string or number to a floating point number, if possible.");
746 static PyNumberMethods float_as_number = {
747 (binaryfunc)float_add, /*nb_add*/
748 (binaryfunc)float_sub, /*nb_subtract*/
749 (binaryfunc)float_mul, /*nb_multiply*/
750 (binaryfunc)float_classic_div, /*nb_divide*/
751 (binaryfunc)float_rem, /*nb_remainder*/
752 (binaryfunc)float_divmod, /*nb_divmod*/
753 (ternaryfunc)float_pow, /*nb_power*/
754 (unaryfunc)float_neg, /*nb_negative*/
755 (unaryfunc)float_pos, /*nb_positive*/
756 (unaryfunc)float_abs, /*nb_absolute*/
757 (inquiry)float_nonzero, /*nb_nonzero*/
758 0, /*nb_invert*/
759 0, /*nb_lshift*/
760 0, /*nb_rshift*/
761 0, /*nb_and*/
762 0, /*nb_xor*/
763 0, /*nb_or*/
764 (coercion)float_coerce, /*nb_coerce*/
765 (unaryfunc)float_int, /*nb_int*/
766 (unaryfunc)float_long, /*nb_long*/
767 (unaryfunc)float_float, /*nb_float*/
768 0, /* nb_oct */
769 0, /* nb_hex */
770 0, /* nb_inplace_add */
771 0, /* nb_inplace_subtract */
772 0, /* nb_inplace_multiply */
773 0, /* nb_inplace_divide */
774 0, /* nb_inplace_remainder */
775 0, /* nb_inplace_power */
776 0, /* nb_inplace_lshift */
777 0, /* nb_inplace_rshift */
778 0, /* nb_inplace_and */
779 0, /* nb_inplace_xor */
780 0, /* nb_inplace_or */
781 float_floor_div, /* nb_floor_divide */
782 float_div, /* nb_true_divide */
783 0, /* nb_inplace_floor_divide */
784 0, /* nb_inplace_true_divide */
787 PyTypeObject PyFloat_Type = {
788 PyObject_HEAD_INIT(&PyType_Type)
790 "float",
791 sizeof(PyFloatObject),
793 (destructor)float_dealloc, /* tp_dealloc */
794 (printfunc)float_print, /* tp_print */
795 0, /* tp_getattr */
796 0, /* tp_setattr */
797 (cmpfunc)float_compare, /* tp_compare */
798 (reprfunc)float_repr, /* tp_repr */
799 &float_as_number, /* tp_as_number */
800 0, /* tp_as_sequence */
801 0, /* tp_as_mapping */
802 (hashfunc)float_hash, /* tp_hash */
803 0, /* tp_call */
804 (reprfunc)float_str, /* tp_str */
805 PyObject_GenericGetAttr, /* tp_getattro */
806 0, /* tp_setattro */
807 0, /* tp_as_buffer */
808 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
809 Py_TPFLAGS_BASETYPE, /* tp_flags */
810 float_doc, /* tp_doc */
811 0, /* tp_traverse */
812 0, /* tp_clear */
813 0, /* tp_richcompare */
814 0, /* tp_weaklistoffset */
815 0, /* tp_iter */
816 0, /* tp_iternext */
817 float_methods, /* tp_methods */
818 0, /* tp_members */
819 0, /* tp_getset */
820 0, /* tp_base */
821 0, /* tp_dict */
822 0, /* tp_descr_get */
823 0, /* tp_descr_set */
824 0, /* tp_dictoffset */
825 0, /* tp_init */
826 0, /* tp_alloc */
827 float_new, /* tp_new */
830 void
831 PyFloat_Fini(void)
833 PyFloatObject *p;
834 PyFloatBlock *list, *next;
835 int i;
836 int bc, bf; /* block count, number of freed blocks */
837 int frem, fsum; /* remaining unfreed floats per block, total */
839 bc = 0;
840 bf = 0;
841 fsum = 0;
842 list = block_list;
843 block_list = NULL;
844 free_list = NULL;
845 while (list != NULL) {
846 bc++;
847 frem = 0;
848 for (i = 0, p = &list->objects[0];
849 i < N_FLOATOBJECTS;
850 i++, p++) {
851 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
852 frem++;
854 next = list->next;
855 if (frem) {
856 list->next = block_list;
857 block_list = list;
858 for (i = 0, p = &list->objects[0];
859 i < N_FLOATOBJECTS;
860 i++, p++) {
861 if (!PyFloat_CheckExact(p) ||
862 p->ob_refcnt == 0) {
863 p->ob_type = (struct _typeobject *)
864 free_list;
865 free_list = p;
869 else {
870 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
871 bf++;
873 fsum += frem;
874 list = next;
876 if (!Py_VerboseFlag)
877 return;
878 fprintf(stderr, "# cleanup floats");
879 if (!fsum) {
880 fprintf(stderr, "\n");
882 else {
883 fprintf(stderr,
884 ": %d unfreed float%s in %d out of %d block%s\n",
885 fsum, fsum == 1 ? "" : "s",
886 bc - bf, bc, bc == 1 ? "" : "s");
888 if (Py_VerboseFlag > 1) {
889 list = block_list;
890 while (list != NULL) {
891 for (i = 0, p = &list->objects[0];
892 i < N_FLOATOBJECTS;
893 i++, p++) {
894 if (PyFloat_CheckExact(p) &&
895 p->ob_refcnt != 0) {
896 char buf[100];
897 PyFloat_AsString(buf, p);
898 fprintf(stderr,
899 "# <float at %p, refcnt=%d, val=%s>\n",
900 p, p->ob_refcnt, buf);
903 list = list->next;
908 /*----------------------------------------------------------------------------
909 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
911 * TODO: On platforms that use the standard IEEE-754 single and double
912 * formats natively, these routines could simply copy the bytes.
915 _PyFloat_Pack4(double x, unsigned char *p, int le)
917 unsigned char sign;
918 int e;
919 double f;
920 unsigned int fbits;
921 int incr = 1;
923 if (le) {
924 p += 3;
925 incr = -1;
928 if (x < 0) {
929 sign = 1;
930 x = -x;
932 else
933 sign = 0;
935 f = frexp(x, &e);
937 /* Normalize f to be in the range [1.0, 2.0) */
938 if (0.5 <= f && f < 1.0) {
939 f *= 2.0;
940 e--;
942 else if (f == 0.0)
943 e = 0;
944 else {
945 PyErr_SetString(PyExc_SystemError,
946 "frexp() result out of range");
947 return -1;
950 if (e >= 128)
951 goto Overflow;
952 else if (e < -126) {
953 /* Gradual underflow */
954 f = ldexp(f, 126 + e);
955 e = 0;
957 else if (!(e == 0 && f == 0.0)) {
958 e += 127;
959 f -= 1.0; /* Get rid of leading 1 */
962 f *= 8388608.0; /* 2**23 */
963 fbits = (unsigned int)(f + 0.5); /* Round */
964 assert(fbits <= 8388608);
965 if (fbits >> 23) {
966 /* The carry propagated out of a string of 23 1 bits. */
967 fbits = 0;
968 ++e;
969 if (e >= 255)
970 goto Overflow;
973 /* First byte */
974 *p = (sign << 7) | (e >> 1);
975 p += incr;
977 /* Second byte */
978 *p = (char) (((e & 1) << 7) | (fbits >> 16));
979 p += incr;
981 /* Third byte */
982 *p = (fbits >> 8) & 0xFF;
983 p += incr;
985 /* Fourth byte */
986 *p = fbits & 0xFF;
988 /* Done */
989 return 0;
991 Overflow:
992 PyErr_SetString(PyExc_OverflowError,
993 "float too large to pack with f format");
994 return -1;
998 _PyFloat_Pack8(double x, unsigned char *p, int le)
1000 unsigned char sign;
1001 int e;
1002 double f;
1003 unsigned int fhi, flo;
1004 int incr = 1;
1006 if (le) {
1007 p += 7;
1008 incr = -1;
1011 if (x < 0) {
1012 sign = 1;
1013 x = -x;
1015 else
1016 sign = 0;
1018 f = frexp(x, &e);
1020 /* Normalize f to be in the range [1.0, 2.0) */
1021 if (0.5 <= f && f < 1.0) {
1022 f *= 2.0;
1023 e--;
1025 else if (f == 0.0)
1026 e = 0;
1027 else {
1028 PyErr_SetString(PyExc_SystemError,
1029 "frexp() result out of range");
1030 return -1;
1033 if (e >= 1024)
1034 goto Overflow;
1035 else if (e < -1022) {
1036 /* Gradual underflow */
1037 f = ldexp(f, 1022 + e);
1038 e = 0;
1040 else if (!(e == 0 && f == 0.0)) {
1041 e += 1023;
1042 f -= 1.0; /* Get rid of leading 1 */
1045 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1046 f *= 268435456.0; /* 2**28 */
1047 fhi = (unsigned int)f; /* Truncate */
1048 assert(fhi < 268435456);
1050 f -= (double)fhi;
1051 f *= 16777216.0; /* 2**24 */
1052 flo = (unsigned int)(f + 0.5); /* Round */
1053 assert(flo <= 16777216);
1054 if (flo >> 24) {
1055 /* The carry propagated out of a string of 24 1 bits. */
1056 flo = 0;
1057 ++fhi;
1058 if (fhi >> 28) {
1059 /* And it also progagated out of the next 28 bits. */
1060 fhi = 0;
1061 ++e;
1062 if (e >= 2047)
1063 goto Overflow;
1067 /* First byte */
1068 *p = (sign << 7) | (e >> 4);
1069 p += incr;
1071 /* Second byte */
1072 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1073 p += incr;
1075 /* Third byte */
1076 *p = (fhi >> 16) & 0xFF;
1077 p += incr;
1079 /* Fourth byte */
1080 *p = (fhi >> 8) & 0xFF;
1081 p += incr;
1083 /* Fifth byte */
1084 *p = fhi & 0xFF;
1085 p += incr;
1087 /* Sixth byte */
1088 *p = (flo >> 16) & 0xFF;
1089 p += incr;
1091 /* Seventh byte */
1092 *p = (flo >> 8) & 0xFF;
1093 p += incr;
1095 /* Eighth byte */
1096 *p = flo & 0xFF;
1097 p += incr;
1099 /* Done */
1100 return 0;
1102 Overflow:
1103 PyErr_SetString(PyExc_OverflowError,
1104 "float too large to pack with d format");
1105 return -1;
1108 double
1109 _PyFloat_Unpack4(const unsigned char *p, int le)
1111 unsigned char sign;
1112 int e;
1113 unsigned int f;
1114 double x;
1115 int incr = 1;
1117 if (le) {
1118 p += 3;
1119 incr = -1;
1122 /* First byte */
1123 sign = (*p >> 7) & 1;
1124 e = (*p & 0x7F) << 1;
1125 p += incr;
1127 /* Second byte */
1128 e |= (*p >> 7) & 1;
1129 f = (*p & 0x7F) << 16;
1130 p += incr;
1132 /* Third byte */
1133 f |= *p << 8;
1134 p += incr;
1136 /* Fourth byte */
1137 f |= *p;
1139 x = (double)f / 8388608.0;
1141 /* XXX This sadly ignores Inf/NaN issues */
1142 if (e == 0)
1143 e = -126;
1144 else {
1145 x += 1.0;
1146 e -= 127;
1148 x = ldexp(x, e);
1150 if (sign)
1151 x = -x;
1153 return x;
1156 double
1157 _PyFloat_Unpack8(const unsigned char *p, int le)
1159 unsigned char sign;
1160 int e;
1161 unsigned int fhi, flo;
1162 double x;
1163 int incr = 1;
1165 if (le) {
1166 p += 7;
1167 incr = -1;
1170 /* First byte */
1171 sign = (*p >> 7) & 1;
1172 e = (*p & 0x7F) << 4;
1173 p += incr;
1175 /* Second byte */
1176 e |= (*p >> 4) & 0xF;
1177 fhi = (*p & 0xF) << 24;
1178 p += incr;
1180 /* Third byte */
1181 fhi |= *p << 16;
1182 p += incr;
1184 /* Fourth byte */
1185 fhi |= *p << 8;
1186 p += incr;
1188 /* Fifth byte */
1189 fhi |= *p;
1190 p += incr;
1192 /* Sixth byte */
1193 flo = *p << 16;
1194 p += incr;
1196 /* Seventh byte */
1197 flo |= *p << 8;
1198 p += incr;
1200 /* Eighth byte */
1201 flo |= *p;
1203 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1204 x /= 268435456.0; /* 2**28 */
1206 /* XXX This sadly ignores Inf/NaN */
1207 if (e == 0)
1208 e = -1022;
1209 else {
1210 x += 1.0;
1211 e -= 1023;
1213 x = ldexp(x, e);
1215 if (sign)
1216 x = -x;
1218 return x;