1
2/* Float object implementation */
3
4/* XXX There should be overflow checks here, but it's hard to check
5   for any kind of float exception without losing portability. */
6
7#include "Python.h"
8#include "structseq.h"
9
10#include <ctype.h>
11#include <float.h>
12
13#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
18#ifdef _OSF_SOURCE
19/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20extern int finite(double);
21#endif
22
23/* Special free list -- see comments for same code in intobject.c. */
24#define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
25#define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
26#define N_FLOATOBJECTS  ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
27
28struct _floatblock {
29    struct _floatblock *next;
30    PyFloatObject objects[N_FLOATOBJECTS];
31};
32
33typedef struct _floatblock PyFloatBlock;
34
35static PyFloatBlock *block_list = NULL;
36static PyFloatObject *free_list = NULL;
37
38static PyFloatObject *
39fill_free_list(void)
40{
41    PyFloatObject *p, *q;
42    /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
43    p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
44    if (p == NULL)
45        return (PyFloatObject *) PyErr_NoMemory();
46    ((PyFloatBlock *)p)->next = block_list;
47    block_list = (PyFloatBlock *)p;
48    p = &((PyFloatBlock *)p)->objects[0];
49    q = p + N_FLOATOBJECTS;
50    while (--q > p)
51        Py_TYPE(q) = (struct _typeobject *)(q-1);
52    Py_TYPE(q) = NULL;
53    return p + N_FLOATOBJECTS - 1;
54}
55
56double
57PyFloat_GetMax(void)
58{
59    return DBL_MAX;
60}
61
62double
63PyFloat_GetMin(void)
64{
65    return DBL_MIN;
66}
67
68static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
69
70PyDoc_STRVAR(floatinfo__doc__,
71"sys.float_info\n\
72\n\
73A structseq holding information about the float type. It contains low level\n\
74information about the precision and internal representation. Please study\n\
75your system's :file:`float.h` for more information.");
76
77static PyStructSequence_Field floatinfo_fields[] = {
78    {"max",             "DBL_MAX -- maximum representable finite float"},
79    {"max_exp",         "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
80                    "is representable"},
81    {"max_10_exp",      "DBL_MAX_10_EXP -- maximum int e such that 10**e "
82                    "is representable"},
83    {"min",             "DBL_MIN -- Minimum positive normalizer float"},
84    {"min_exp",         "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
85                    "is a normalized float"},
86    {"min_10_exp",      "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
87                    "a normalized"},
88    {"dig",             "DBL_DIG -- digits"},
89    {"mant_dig",        "DBL_MANT_DIG -- mantissa digits"},
90    {"epsilon",         "DBL_EPSILON -- Difference between 1 and the next "
91                    "representable float"},
92    {"radix",           "FLT_RADIX -- radix of exponent"},
93    {"rounds",          "FLT_ROUNDS -- addition rounds"},
94    {0}
95};
96
97static PyStructSequence_Desc floatinfo_desc = {
98    "sys.float_info",           /* name */
99    floatinfo__doc__,           /* doc */
100    floatinfo_fields,           /* fields */
101    11
102};
103
104PyObject *
105PyFloat_GetInfo(void)
106{
107    PyObject* floatinfo;
108    int pos = 0;
109
110    floatinfo = PyStructSequence_New(&FloatInfoType);
111    if (floatinfo == NULL) {
112        return NULL;
113    }
114
115#define SetIntFlag(flag) \
116    PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
117#define SetDblFlag(flag) \
118    PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
119
120    SetDblFlag(DBL_MAX);
121    SetIntFlag(DBL_MAX_EXP);
122    SetIntFlag(DBL_MAX_10_EXP);
123    SetDblFlag(DBL_MIN);
124    SetIntFlag(DBL_MIN_EXP);
125    SetIntFlag(DBL_MIN_10_EXP);
126    SetIntFlag(DBL_DIG);
127    SetIntFlag(DBL_MANT_DIG);
128    SetDblFlag(DBL_EPSILON);
129    SetIntFlag(FLT_RADIX);
130    SetIntFlag(FLT_ROUNDS);
131#undef SetIntFlag
132#undef SetDblFlag
133
134    if (PyErr_Occurred()) {
135        Py_CLEAR(floatinfo);
136        return NULL;
137    }
138    return floatinfo;
139}
140
141PyObject *
142PyFloat_FromDouble(double fval)
143{
144    register PyFloatObject *op;
145    if (free_list == NULL) {
146        if ((free_list = fill_free_list()) == NULL)
147            return NULL;
148    }
149    /* Inline PyObject_New */
150    op = free_list;
151    free_list = (PyFloatObject *)Py_TYPE(op);
152    PyObject_INIT(op, &PyFloat_Type);
153    op->ob_fval = fval;
154    return (PyObject *) op;
155}
156
157/**************************************************************************
158RED_FLAG 22-Sep-2000 tim
159PyFloat_FromString's pend argument is braindead.  Prior to this RED_FLAG,
160
1611.  If v was a regular string, *pend was set to point to its terminating
162    null byte.  That's useless (the caller can find that without any
163    help from this function!).
164
1652.  If v was a Unicode string, or an object convertible to a character
166    buffer, *pend was set to point into stack trash (the auto temp
167    vector holding the character buffer).  That was downright dangerous.
168
169Since we can't change the interface of a public API function, pend is
170still supported but now *officially* useless:  if pend is not NULL,
171*pend is set to NULL.
172**************************************************************************/
173PyObject *
174PyFloat_FromString(PyObject *v, char **pend)
175{
176    const char *s, *last, *end;
177    double x;
178    char buffer[256]; /* for errors */
179#ifdef Py_USING_UNICODE
180    char *s_buffer = NULL;
181#endif
182    Py_ssize_t len;
183    PyObject *result = NULL;
184
185    if (pend)
186        *pend = NULL;
187    if (PyString_Check(v)) {
188        s = PyString_AS_STRING(v);
189        len = PyString_GET_SIZE(v);
190    }
191#ifdef Py_USING_UNICODE
192    else if (PyUnicode_Check(v)) {
193        s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
194        if (s_buffer == NULL)
195            return PyErr_NoMemory();
196        if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
197                                    PyUnicode_GET_SIZE(v),
198                                    s_buffer,
199                                    NULL))
200            goto error;
201        s = s_buffer;
202        len = strlen(s);
203    }
204#endif
205    else if (PyObject_AsCharBuffer(v, &s, &len)) {
206        PyErr_SetString(PyExc_TypeError,
207            "float() argument must be a string or a number");
208        return NULL;
209    }
210    last = s + len;
211
212    while (Py_ISSPACE(*s))
213        s++;
214    /* We don't care about overflow or underflow.  If the platform
215     * supports them, infinities and signed zeroes (on underflow) are
216     * fine. */
217    x = PyOS_string_to_double(s, (char **)&end, NULL);
218    if (x == -1.0 && PyErr_Occurred())
219        goto error;
220    while (Py_ISSPACE(*end))
221        end++;
222    if (end == last)
223        result = PyFloat_FromDouble(x);
224    else {
225        PyOS_snprintf(buffer, sizeof(buffer),
226                      "invalid literal for float(): %.200s", s);
227        PyErr_SetString(PyExc_ValueError, buffer);
228        result = NULL;
229    }
230
231  error:
232#ifdef Py_USING_UNICODE
233    if (s_buffer)
234        PyMem_FREE(s_buffer);
235#endif
236    return result;
237}
238
239static void
240float_dealloc(PyFloatObject *op)
241{
242    if (PyFloat_CheckExact(op)) {
243        Py_TYPE(op) = (struct _typeobject *)free_list;
244        free_list = op;
245    }
246    else
247        Py_TYPE(op)->tp_free((PyObject *)op);
248}
249
250double
251PyFloat_AsDouble(PyObject *op)
252{
253    PyNumberMethods *nb;
254    PyFloatObject *fo;
255    double val;
256
257    if (op && PyFloat_Check(op))
258        return PyFloat_AS_DOUBLE((PyFloatObject*) op);
259
260    if (op == NULL) {
261        PyErr_BadArgument();
262        return -1;
263    }
264
265    if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
266        PyErr_SetString(PyExc_TypeError, "a float is required");
267        return -1;
268    }
269
270    fo = (PyFloatObject*) (*nb->nb_float) (op);
271    if (fo == NULL)
272        return -1;
273    if (!PyFloat_Check(fo)) {
274        Py_DECREF(fo);
275        PyErr_SetString(PyExc_TypeError,
276                        "nb_float should return float object");
277        return -1;
278    }
279
280    val = PyFloat_AS_DOUBLE(fo);
281    Py_DECREF(fo);
282
283    return val;
284}
285
286/* Methods */
287
288/* Macro and helper that convert PyObject obj to a C double and store
289   the value in dbl; this replaces the functionality of the coercion
290   slot function.  If conversion to double raises an exception, obj is
291   set to NULL, and the function invoking this macro returns NULL.  If
292   obj is not of float, int or long type, Py_NotImplemented is incref'ed,
293   stored in obj, and returned from the function invoking this macro.
294*/
295#define CONVERT_TO_DOUBLE(obj, dbl)                     \
296    if (PyFloat_Check(obj))                             \
297        dbl = PyFloat_AS_DOUBLE(obj);                   \
298    else if (convert_to_double(&(obj), &(dbl)) < 0)     \
299        return obj;
300
301static int
302convert_to_double(PyObject **v, double *dbl)
303{
304    register PyObject *obj = *v;
305
306    if (PyInt_Check(obj)) {
307        *dbl = (double)PyInt_AS_LONG(obj);
308    }
309    else if (PyLong_Check(obj)) {
310        *dbl = PyLong_AsDouble(obj);
311        if (*dbl == -1.0 && PyErr_Occurred()) {
312            *v = NULL;
313            return -1;
314        }
315    }
316    else {
317        Py_INCREF(Py_NotImplemented);
318        *v = Py_NotImplemented;
319        return -1;
320    }
321    return 0;
322}
323
324/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
325   XXX they pass a char buffer without passing a length.
326*/
327void
328PyFloat_AsString(char *buf, PyFloatObject *v)
329{
330    char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
331                    PyFloat_STR_PRECISION,
332                    Py_DTSF_ADD_DOT_0, NULL);
333    strcpy(buf, tmp);
334    PyMem_Free(tmp);
335}
336
337void
338PyFloat_AsReprString(char *buf, PyFloatObject *v)
339{
340    char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
341                    Py_DTSF_ADD_DOT_0, NULL);
342    strcpy(buf, tmp);
343    PyMem_Free(tmp);
344}
345
346/* ARGSUSED */
347static int
348float_print(PyFloatObject *v, FILE *fp, int flags)
349{
350    char *buf;
351    if (flags & Py_PRINT_RAW)
352        buf = PyOS_double_to_string(v->ob_fval,
353                                    'g', PyFloat_STR_PRECISION,
354                                    Py_DTSF_ADD_DOT_0, NULL);
355    else
356        buf = PyOS_double_to_string(v->ob_fval,
357                            'r', 0, Py_DTSF_ADD_DOT_0, NULL);
358    Py_BEGIN_ALLOW_THREADS
359    fputs(buf, fp);
360    Py_END_ALLOW_THREADS
361    PyMem_Free(buf);
362    return 0;
363}
364
365static PyObject *
366float_str_or_repr(PyFloatObject *v, int precision, char format_code)
367{
368    PyObject *result;
369    char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
370                                  format_code, precision,
371                                  Py_DTSF_ADD_DOT_0,
372                                  NULL);
373    if (!buf)
374        return PyErr_NoMemory();
375    result = PyString_FromString(buf);
376    PyMem_Free(buf);
377    return result;
378}
379
380static PyObject *
381float_repr(PyFloatObject *v)
382{
383    return float_str_or_repr(v, 0, 'r');
384}
385
386static PyObject *
387float_str(PyFloatObject *v)
388{
389    return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
390}
391
392/* Comparison is pretty much a nightmare.  When comparing float to float,
393 * we do it as straightforwardly (and long-windedly) as conceivable, so
394 * that, e.g., Python x == y delivers the same result as the platform
395 * C x == y when x and/or y is a NaN.
396 * When mixing float with an integer type, there's no good *uniform* approach.
397 * Converting the double to an integer obviously doesn't work, since we
398 * may lose info from fractional bits.  Converting the integer to a double
399 * also has two failure modes:  (1) a long int may trigger overflow (too
400 * large to fit in the dynamic range of a C double); (2) even a C long may have
401 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
402 * 63 bits of precision, but a C double probably has only 53), and then
403 * we can falsely claim equality when low-order integer bits are lost by
404 * coercion to double.  So this part is painful too.
405 */
406
407static PyObject*
408float_richcompare(PyObject *v, PyObject *w, int op)
409{
410    double i, j;
411    int r = 0;
412
413    assert(PyFloat_Check(v));
414    i = PyFloat_AS_DOUBLE(v);
415
416    /* Switch on the type of w.  Set i and j to doubles to be compared,
417     * and op to the richcomp to use.
418     */
419    if (PyFloat_Check(w))
420        j = PyFloat_AS_DOUBLE(w);
421
422    else if (!Py_IS_FINITE(i)) {
423        if (PyInt_Check(w) || PyLong_Check(w))
424            /* If i is an infinity, its magnitude exceeds any
425             * finite integer, so it doesn't matter which int we
426             * compare i with.  If i is a NaN, similarly.
427             */
428            j = 0.0;
429        else
430            goto Unimplemented;
431    }
432
433    else if (PyInt_Check(w)) {
434        long jj = PyInt_AS_LONG(w);
435        /* In the worst realistic case I can imagine, C double is a
436         * Cray single with 48 bits of precision, and long has 64
437         * bits.
438         */
439#if SIZEOF_LONG > 6
440        unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
441        if (abs >> 48) {
442            /* Needs more than 48 bits.  Make it take the
443             * PyLong path.
444             */
445            PyObject *result;
446            PyObject *ww = PyLong_FromLong(jj);
447
448            if (ww == NULL)
449                return NULL;
450            result = float_richcompare(v, ww, op);
451            Py_DECREF(ww);
452            return result;
453        }
454#endif
455        j = (double)jj;
456        assert((long)j == jj);
457    }
458
459    else if (PyLong_Check(w)) {
460        int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
461        int wsign = _PyLong_Sign(w);
462        size_t nbits;
463        int exponent;
464
465        if (vsign != wsign) {
466            /* Magnitudes are irrelevant -- the signs alone
467             * determine the outcome.
468             */
469            i = (double)vsign;
470            j = (double)wsign;
471            goto Compare;
472        }
473        /* The signs are the same. */
474        /* Convert w to a double if it fits.  In particular, 0 fits. */
475        nbits = _PyLong_NumBits(w);
476        if (nbits == (size_t)-1 && PyErr_Occurred()) {
477            /* This long is so large that size_t isn't big enough
478             * to hold the # of bits.  Replace with little doubles
479             * that give the same outcome -- w is so large that
480             * its magnitude must exceed the magnitude of any
481             * finite float.
482             */
483            PyErr_Clear();
484            i = (double)vsign;
485            assert(wsign != 0);
486            j = wsign * 2.0;
487            goto Compare;
488        }
489        if (nbits <= 48) {
490            j = PyLong_AsDouble(w);
491            /* It's impossible that <= 48 bits overflowed. */
492            assert(j != -1.0 || ! PyErr_Occurred());
493            goto Compare;
494        }
495        assert(wsign != 0); /* else nbits was 0 */
496        assert(vsign != 0); /* if vsign were 0, then since wsign is
497                             * not 0, we would have taken the
498                             * vsign != wsign branch at the start */
499        /* We want to work with non-negative numbers. */
500        if (vsign < 0) {
501            /* "Multiply both sides" by -1; this also swaps the
502             * comparator.
503             */
504            i = -i;
505            op = _Py_SwappedOp[op];
506        }
507        assert(i > 0.0);
508        (void) frexp(i, &exponent);
509        /* exponent is the # of bits in v before the radix point;
510         * we know that nbits (the # of bits in w) > 48 at this point
511         */
512        if (exponent < 0 || (size_t)exponent < nbits) {
513            i = 1.0;
514            j = 2.0;
515            goto Compare;
516        }
517        if ((size_t)exponent > nbits) {
518            i = 2.0;
519            j = 1.0;
520            goto Compare;
521        }
522        /* v and w have the same number of bits before the radix
523         * point.  Construct two longs that have the same comparison
524         * outcome.
525         */
526        {
527            double fracpart;
528            double intpart;
529            PyObject *result = NULL;
530            PyObject *one = NULL;
531            PyObject *vv = NULL;
532            PyObject *ww = w;
533
534            if (wsign < 0) {
535                ww = PyNumber_Negative(w);
536                if (ww == NULL)
537                    goto Error;
538            }
539            else
540                Py_INCREF(ww);
541
542            fracpart = modf(i, &intpart);
543            vv = PyLong_FromDouble(intpart);
544            if (vv == NULL)
545                goto Error;
546
547            if (fracpart != 0.0) {
548                /* Shift left, and or a 1 bit into vv
549                 * to represent the lost fraction.
550                 */
551                PyObject *temp;
552
553                one = PyInt_FromLong(1);
554                if (one == NULL)
555                    goto Error;
556
557                temp = PyNumber_Lshift(ww, one);
558                if (temp == NULL)
559                    goto Error;
560                Py_DECREF(ww);
561                ww = temp;
562
563                temp = PyNumber_Lshift(vv, one);
564                if (temp == NULL)
565                    goto Error;
566                Py_DECREF(vv);
567                vv = temp;
568
569                temp = PyNumber_Or(vv, one);
570                if (temp == NULL)
571                    goto Error;
572                Py_DECREF(vv);
573                vv = temp;
574            }
575
576            r = PyObject_RichCompareBool(vv, ww, op);
577            if (r < 0)
578                goto Error;
579            result = PyBool_FromLong(r);
580         Error:
581            Py_XDECREF(vv);
582            Py_XDECREF(ww);
583            Py_XDECREF(one);
584            return result;
585        }
586    } /* else if (PyLong_Check(w)) */
587
588    else        /* w isn't float, int, or long */
589        goto Unimplemented;
590
591 Compare:
592    PyFPE_START_PROTECT("richcompare", return NULL)
593    switch (op) {
594    case Py_EQ:
595        r = i == j;
596        break;
597    case Py_NE:
598        r = i != j;
599        break;
600    case Py_LE:
601        r = i <= j;
602        break;
603    case Py_GE:
604        r = i >= j;
605        break;
606    case Py_LT:
607        r = i < j;
608        break;
609    case Py_GT:
610        r = i > j;
611        break;
612    }
613    PyFPE_END_PROTECT(r)
614    return PyBool_FromLong(r);
615
616 Unimplemented:
617    Py_INCREF(Py_NotImplemented);
618    return Py_NotImplemented;
619}
620
621static long
622float_hash(PyFloatObject *v)
623{
624    return _Py_HashDouble(v->ob_fval);
625}
626
627static PyObject *
628float_add(PyObject *v, PyObject *w)
629{
630    double a,b;
631    CONVERT_TO_DOUBLE(v, a);
632    CONVERT_TO_DOUBLE(w, b);
633    PyFPE_START_PROTECT("add", return 0)
634    a = a + b;
635    PyFPE_END_PROTECT(a)
636    return PyFloat_FromDouble(a);
637}
638
639static PyObject *
640float_sub(PyObject *v, PyObject *w)
641{
642    double a,b;
643    CONVERT_TO_DOUBLE(v, a);
644    CONVERT_TO_DOUBLE(w, b);
645    PyFPE_START_PROTECT("subtract", return 0)
646    a = a - b;
647    PyFPE_END_PROTECT(a)
648    return PyFloat_FromDouble(a);
649}
650
651static PyObject *
652float_mul(PyObject *v, PyObject *w)
653{
654    double a,b;
655    CONVERT_TO_DOUBLE(v, a);
656    CONVERT_TO_DOUBLE(w, b);
657    PyFPE_START_PROTECT("multiply", return 0)
658    a = a * b;
659    PyFPE_END_PROTECT(a)
660    return PyFloat_FromDouble(a);
661}
662
663static PyObject *
664float_div(PyObject *v, PyObject *w)
665{
666    double a,b;
667    CONVERT_TO_DOUBLE(v, a);
668    CONVERT_TO_DOUBLE(w, b);
669#ifdef Py_NAN
670    if (b == 0.0) {
671        PyErr_SetString(PyExc_ZeroDivisionError,
672                        "float division by zero");
673        return NULL;
674    }
675#endif
676    PyFPE_START_PROTECT("divide", return 0)
677    a = a / b;
678    PyFPE_END_PROTECT(a)
679    return PyFloat_FromDouble(a);
680}
681
682static PyObject *
683float_classic_div(PyObject *v, PyObject *w)
684{
685    double a,b;
686    CONVERT_TO_DOUBLE(v, a);
687    CONVERT_TO_DOUBLE(w, b);
688    if (Py_DivisionWarningFlag >= 2 &&
689        PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
690        return NULL;
691#ifdef Py_NAN
692    if (b == 0.0) {
693        PyErr_SetString(PyExc_ZeroDivisionError,
694                        "float division by zero");
695        return NULL;
696    }
697#endif
698    PyFPE_START_PROTECT("divide", return 0)
699    a = a / b;
700    PyFPE_END_PROTECT(a)
701    return PyFloat_FromDouble(a);
702}
703
704static PyObject *
705float_rem(PyObject *v, PyObject *w)
706{
707    double vx, wx;
708    double mod;
709    CONVERT_TO_DOUBLE(v, vx);
710    CONVERT_TO_DOUBLE(w, wx);
711#ifdef Py_NAN
712    if (wx == 0.0) {
713        PyErr_SetString(PyExc_ZeroDivisionError,
714                        "float modulo");
715        return NULL;
716    }
717#endif
718    PyFPE_START_PROTECT("modulo", return 0)
719    mod = fmod(vx, wx);
720    if (mod) {
721        /* ensure the remainder has the same sign as the denominator */
722        if ((wx < 0) != (mod < 0)) {
723            mod += wx;
724        }
725    }
726    else {
727        /* the remainder is zero, and in the presence of signed zeroes
728           fmod returns different results across platforms; ensure
729           it has the same sign as the denominator; we'd like to do
730           "mod = wx * 0.0", but that may get optimized away */
731        mod *= mod;  /* hide "mod = +0" from optimizer */
732        if (wx < 0.0)
733            mod = -mod;
734    }
735    PyFPE_END_PROTECT(mod)
736    return PyFloat_FromDouble(mod);
737}
738
739static PyObject *
740float_divmod(PyObject *v, PyObject *w)
741{
742    double vx, wx;
743    double div, mod, floordiv;
744    CONVERT_TO_DOUBLE(v, vx);
745    CONVERT_TO_DOUBLE(w, wx);
746    if (wx == 0.0) {
747        PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
748        return NULL;
749    }
750    PyFPE_START_PROTECT("divmod", return 0)
751    mod = fmod(vx, wx);
752    /* fmod is typically exact, so vx-mod is *mathematically* an
753       exact multiple of wx.  But this is fp arithmetic, and fp
754       vx - mod is an approximation; the result is that div may
755       not be an exact integral value after the division, although
756       it will always be very close to one.
757    */
758    div = (vx - mod) / wx;
759    if (mod) {
760        /* ensure the remainder has the same sign as the denominator */
761        if ((wx < 0) != (mod < 0)) {
762            mod += wx;
763            div -= 1.0;
764        }
765    }
766    else {
767        /* the remainder is zero, and in the presence of signed zeroes
768           fmod returns different results across platforms; ensure
769           it has the same sign as the denominator; we'd like to do
770           "mod = wx * 0.0", but that may get optimized away */
771        mod *= mod;  /* hide "mod = +0" from optimizer */
772        if (wx < 0.0)
773            mod = -mod;
774    }
775    /* snap quotient to nearest integral value */
776    if (div) {
777        floordiv = floor(div);
778        if (div - floordiv > 0.5)
779            floordiv += 1.0;
780    }
781    else {
782        /* div is zero - get the same sign as the true quotient */
783        div *= div;             /* hide "div = +0" from optimizers */
784        floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
785    }
786    PyFPE_END_PROTECT(floordiv)
787    return Py_BuildValue("(dd)", floordiv, mod);
788}
789
790static PyObject *
791float_floor_div(PyObject *v, PyObject *w)
792{
793    PyObject *t, *r;
794
795    t = float_divmod(v, w);
796    if (t == NULL || t == Py_NotImplemented)
797        return t;
798    assert(PyTuple_CheckExact(t));
799    r = PyTuple_GET_ITEM(t, 0);
800    Py_INCREF(r);
801    Py_DECREF(t);
802    return r;
803}
804
805/* determine whether x is an odd integer or not;  assumes that
806   x is not an infinity or nan. */
807#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
808
809static PyObject *
810float_pow(PyObject *v, PyObject *w, PyObject *z)
811{
812    double iv, iw, ix;
813    int negate_result = 0;
814
815    if ((PyObject *)z != Py_None) {
816        PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
817            "allowed unless all arguments are integers");
818        return NULL;
819    }
820
821    CONVERT_TO_DOUBLE(v, iv);
822    CONVERT_TO_DOUBLE(w, iw);
823
824    /* Sort out special cases here instead of relying on pow() */
825    if (iw == 0) {              /* v**0 is 1, even 0**0 */
826        return PyFloat_FromDouble(1.0);
827    }
828    if (Py_IS_NAN(iv)) {        /* nan**w = nan, unless w == 0 */
829        return PyFloat_FromDouble(iv);
830    }
831    if (Py_IS_NAN(iw)) {        /* v**nan = nan, unless v == 1; 1**nan = 1 */
832        return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
833    }
834    if (Py_IS_INFINITY(iw)) {
835        /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
836         *     abs(v) > 1 (including case where v infinite)
837         *
838         * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
839         *     abs(v) > 1 (including case where v infinite)
840         */
841        iv = fabs(iv);
842        if (iv == 1.0)
843            return PyFloat_FromDouble(1.0);
844        else if ((iw > 0.0) == (iv > 1.0))
845            return PyFloat_FromDouble(fabs(iw)); /* return inf */
846        else
847            return PyFloat_FromDouble(0.0);
848    }
849    if (Py_IS_INFINITY(iv)) {
850        /* (+-inf)**w is: inf for w positive, 0 for w negative; in
851         *     both cases, we need to add the appropriate sign if w is
852         *     an odd integer.
853         */
854        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
855        if (iw > 0.0)
856            return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
857        else
858            return PyFloat_FromDouble(iw_is_odd ?
859                                      copysign(0.0, iv) : 0.0);
860    }
861    if (iv == 0.0) {  /* 0**w is: 0 for w positive, 1 for w zero
862                         (already dealt with above), and an error
863                         if w is negative. */
864        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
865        if (iw < 0.0) {
866            PyErr_SetString(PyExc_ZeroDivisionError,
867                            "0.0 cannot be raised to a "
868                            "negative power");
869            return NULL;
870        }
871        /* use correct sign if iw is odd */
872        return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
873    }
874
875    if (iv < 0.0) {
876        /* Whether this is an error is a mess, and bumps into libm
877         * bugs so we have to figure it out ourselves.
878         */
879        if (iw != floor(iw)) {
880            PyErr_SetString(PyExc_ValueError, "negative number "
881                "cannot be raised to a fractional power");
882            return NULL;
883        }
884        /* iw is an exact integer, albeit perhaps a very large
885         * one.  Replace iv by its absolute value and remember
886         * to negate the pow result if iw is odd.
887         */
888        iv = -iv;
889        negate_result = DOUBLE_IS_ODD_INTEGER(iw);
890    }
891
892    if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
893        /* (-1) ** large_integer also ends up here.  Here's an
894         * extract from the comments for the previous
895         * implementation explaining why this special case is
896         * necessary:
897         *
898         * -1 raised to an exact integer should never be exceptional.
899         * Alas, some libms (chiefly glibc as of early 2003) return
900         * NaN and set EDOM on pow(-1, large_int) if the int doesn't
901         * happen to be representable in a *C* integer.  That's a
902         * bug.
903         */
904        return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
905    }
906
907    /* Now iv and iw are finite, iw is nonzero, and iv is
908     * positive and not equal to 1.0.  We finally allow
909     * the platform pow to step in and do the rest.
910     */
911    errno = 0;
912    PyFPE_START_PROTECT("pow", return NULL)
913    ix = pow(iv, iw);
914    PyFPE_END_PROTECT(ix)
915    Py_ADJUST_ERANGE1(ix);
916    if (negate_result)
917        ix = -ix;
918
919    if (errno != 0) {
920        /* We don't expect any errno value other than ERANGE, but
921         * the range of libm bugs appears unbounded.
922         */
923        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
924                             PyExc_ValueError);
925        return NULL;
926    }
927    return PyFloat_FromDouble(ix);
928}
929
930#undef DOUBLE_IS_ODD_INTEGER
931
932static PyObject *
933float_neg(PyFloatObject *v)
934{
935    return PyFloat_FromDouble(-v->ob_fval);
936}
937
938static PyObject *
939float_abs(PyFloatObject *v)
940{
941    return PyFloat_FromDouble(fabs(v->ob_fval));
942}
943
944static int
945float_nonzero(PyFloatObject *v)
946{
947    return v->ob_fval != 0.0;
948}
949
950static int
951float_coerce(PyObject **pv, PyObject **pw)
952{
953    if (PyInt_Check(*pw)) {
954        long x = PyInt_AsLong(*pw);
955        *pw = PyFloat_FromDouble((double)x);
956        Py_INCREF(*pv);
957        return 0;
958    }
959    else if (PyLong_Check(*pw)) {
960        double x = PyLong_AsDouble(*pw);
961        if (x == -1.0 && PyErr_Occurred())
962            return -1;
963        *pw = PyFloat_FromDouble(x);
964        Py_INCREF(*pv);
965        return 0;
966    }
967    else if (PyFloat_Check(*pw)) {
968        Py_INCREF(*pv);
969        Py_INCREF(*pw);
970        return 0;
971    }
972    return 1; /* Can't do it */
973}
974
975static PyObject *
976float_is_integer(PyObject *v)
977{
978    double x = PyFloat_AsDouble(v);
979    PyObject *o;
980
981    if (x == -1.0 && PyErr_Occurred())
982        return NULL;
983    if (!Py_IS_FINITE(x))
984        Py_RETURN_FALSE;
985    errno = 0;
986    PyFPE_START_PROTECT("is_integer", return NULL)
987    o = (floor(x) == x) ? Py_True : Py_False;
988    PyFPE_END_PROTECT(x)
989    if (errno != 0) {
990        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
991                             PyExc_ValueError);
992        return NULL;
993    }
994    Py_INCREF(o);
995    return o;
996}
997
998#if 0
999static PyObject *
1000float_is_inf(PyObject *v)
1001{
1002    double x = PyFloat_AsDouble(v);
1003    if (x == -1.0 && PyErr_Occurred())
1004        return NULL;
1005    return PyBool_FromLong((long)Py_IS_INFINITY(x));
1006}
1007
1008static PyObject *
1009float_is_nan(PyObject *v)
1010{
1011    double x = PyFloat_AsDouble(v);
1012    if (x == -1.0 && PyErr_Occurred())
1013        return NULL;
1014    return PyBool_FromLong((long)Py_IS_NAN(x));
1015}
1016
1017static PyObject *
1018float_is_finite(PyObject *v)
1019{
1020    double x = PyFloat_AsDouble(v);
1021    if (x == -1.0 && PyErr_Occurred())
1022        return NULL;
1023    return PyBool_FromLong((long)Py_IS_FINITE(x));
1024}
1025#endif
1026
1027static PyObject *
1028float_trunc(PyObject *v)
1029{
1030    double x = PyFloat_AsDouble(v);
1031    double wholepart;           /* integral portion of x, rounded toward 0 */
1032
1033    (void)modf(x, &wholepart);
1034    /* Try to get out cheap if this fits in a Python int.  The attempt
1035     * to cast to long must be protected, as C doesn't define what
1036     * happens if the double is too big to fit in a long.  Some rare
1037     * systems raise an exception then (RISCOS was mentioned as one,
1038     * and someone using a non-default option on Sun also bumped into
1039     * that).  Note that checking for <= LONG_MAX is unsafe: if a long
1040     * has more bits of precision than a double, casting LONG_MAX to
1041     * double may yield an approximation, and if that's rounded up,
1042     * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
1043     * expression wholepart<=LONG_MAX, despite that wholepart is
1044     * actually greater than LONG_MAX.  However, assuming a two's complement
1045     * machine with no trap representation, LONG_MIN will be a power of 2 (and
1046     * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
1047     * the comparisons with (double)LONG_MIN below should be safe.
1048     */
1049    if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {
1050        const long aslong = (long)wholepart;
1051        return PyInt_FromLong(aslong);
1052    }
1053    return PyLong_FromDouble(wholepart);
1054}
1055
1056static PyObject *
1057float_long(PyObject *v)
1058{
1059    double x = PyFloat_AsDouble(v);
1060    return PyLong_FromDouble(x);
1061}
1062
1063/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
1064   10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1065   ndigits <= 323).  Returns a Python float, or sets a Python error and
1066   returns NULL on failure (OverflowError and memory errors are possible). */
1067
1068#ifndef PY_NO_SHORT_FLOAT_REPR
1069/* version of _Py_double_round that uses the correctly-rounded string<->double
1070   conversions from Python/dtoa.c */
1071
1072/* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1073   a double.  Since we're using the code in Python/dtoa.c, it should be safe
1074   to assume that C doubles are IEEE 754 binary64 format.  To be on the safe
1075   side, we check this. */
1076#if DBL_MANT_DIG == 53
1077#define FIVE_POW_LIMIT 22
1078#else
1079#error "C doubles do not appear to be IEEE 754 binary64 format"
1080#endif
1081
1082PyObject *
1083_Py_double_round(double x, int ndigits) {
1084
1085    double rounded, m;
1086    Py_ssize_t buflen, mybuflen=100;
1087    char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
1088    int decpt, sign, val, halfway_case;
1089    PyObject *result = NULL;
1090    _Py_SET_53BIT_PRECISION_HEADER;
1091
1092    /* Easy path for the common case ndigits == 0. */
1093    if (ndigits == 0) {
1094        rounded = round(x);
1095        if (fabs(rounded - x) == 0.5)
1096            /* halfway between two integers; use round-away-from-zero */
1097            rounded = x + (x > 0.0 ? 0.5 : -0.5);
1098        return PyFloat_FromDouble(rounded);
1099    }
1100
1101    /* The basic idea is very simple: convert and round the double to a
1102       decimal string using _Py_dg_dtoa, then convert that decimal string
1103       back to a double with _Py_dg_strtod.  There's one minor difficulty:
1104       Python 2.x expects round to do round-half-away-from-zero, while
1105       _Py_dg_dtoa does round-half-to-even.  So we need some way to detect
1106       and correct the halfway cases.
1107
1108       Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1109       some odd integer k.  Or in other words, a rational number x is
1110       exactly halfway between two multiples of 10**-ndigits if its
1111       2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1112       -ndigits.  For ndigits >= 0 the latter condition is automatically
1113       satisfied for a binary float x, since any such float has
1114       nonnegative 5-valuation.  For 0 > ndigits >= -22, x needs to be an
1115       integral multiple of 5**-ndigits; we can check this using fmod.
1116       For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1117       to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1118       23 takes at least 54 bits of precision to represent exactly.
1119
1120       Correction: a simple strategy for dealing with halfway cases is to
1121       (for the halfway cases only) call _Py_dg_dtoa with an argument of
1122       ndigits+1 instead of ndigits (thus doing an exact conversion to
1123       decimal), round the resulting string manually, and then convert
1124       back using _Py_dg_strtod.
1125    */
1126
1127    /* nans, infinities and zeros should have already been dealt
1128       with by the caller (in this case, builtin_round) */
1129    assert(Py_IS_FINITE(x) && x != 0.0);
1130
1131    /* find 2-valuation val of x */
1132    m = frexp(x, &val);
1133    while (m != floor(m)) {
1134        m *= 2.0;
1135        val--;
1136    }
1137
1138    /* determine whether this is a halfway case */
1139    if (val == -ndigits-1) {
1140        if (ndigits >= 0)
1141            halfway_case = 1;
1142        else if (ndigits >= -FIVE_POW_LIMIT) {
1143            double five_pow = 1.0;
1144            int i;
1145            for (i=0; i < -ndigits; i++)
1146                five_pow *= 5.0;
1147            halfway_case = fmod(x, five_pow) == 0.0;
1148        }
1149        else
1150            halfway_case = 0;
1151    }
1152    else
1153        halfway_case = 0;
1154
1155    /* round to a decimal string; use an extra place for halfway case */
1156    _Py_SET_53BIT_PRECISION_START;
1157    buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
1158    _Py_SET_53BIT_PRECISION_END;
1159    if (buf == NULL) {
1160        PyErr_NoMemory();
1161        return NULL;
1162    }
1163    buflen = buf_end - buf;
1164
1165    /* in halfway case, do the round-half-away-from-zero manually */
1166    if (halfway_case) {
1167        int i, carry;
1168        /* sanity check: _Py_dg_dtoa should not have stripped
1169           any zeros from the result: there should be exactly
1170           ndigits+1 places following the decimal point, and
1171           the last digit in the buffer should be a '5'.*/
1172        assert(buflen - decpt == ndigits+1);
1173        assert(buf[buflen-1] == '5');
1174
1175        /* increment and shift right at the same time. */
1176        decpt += 1;
1177        carry = 1;
1178        for (i=buflen-1; i-- > 0;) {
1179            carry += buf[i] - '0';
1180            buf[i+1] = carry % 10 + '0';
1181            carry /= 10;
1182        }
1183        buf[0] = carry + '0';
1184    }
1185
1186    /* Get new buffer if shortbuf is too small.  Space needed <= buf_end -
1187       buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1188    if (buflen + 8 > mybuflen) {
1189        mybuflen = buflen+8;
1190        mybuf = (char *)PyMem_Malloc(mybuflen);
1191        if (mybuf == NULL) {
1192            PyErr_NoMemory();
1193            goto exit;
1194        }
1195    }
1196    /* copy buf to mybuf, adding exponent, sign and leading 0 */
1197    PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
1198                  buf, decpt - (int)buflen);
1199
1200    /* and convert the resulting string back to a double */
1201    errno = 0;
1202    _Py_SET_53BIT_PRECISION_START;
1203    rounded = _Py_dg_strtod(mybuf, NULL);
1204    _Py_SET_53BIT_PRECISION_END;
1205    if (errno == ERANGE && fabs(rounded) >= 1.)
1206        PyErr_SetString(PyExc_OverflowError,
1207                        "rounded value too large to represent");
1208    else
1209        result = PyFloat_FromDouble(rounded);
1210
1211    /* done computing value;  now clean up */
1212    if (mybuf != shortbuf)
1213        PyMem_Free(mybuf);
1214  exit:
1215    _Py_dg_freedtoa(buf);
1216    return result;
1217}
1218
1219#undef FIVE_POW_LIMIT
1220
1221#else /* PY_NO_SHORT_FLOAT_REPR */
1222
1223/* fallback version, to be used when correctly rounded binary<->decimal
1224   conversions aren't available */
1225
1226PyObject *
1227_Py_double_round(double x, int ndigits) {
1228    double pow1, pow2, y, z;
1229    if (ndigits >= 0) {
1230        if (ndigits > 22) {
1231            /* pow1 and pow2 are each safe from overflow, but
1232               pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1233            pow1 = pow(10.0, (double)(ndigits-22));
1234            pow2 = 1e22;
1235        }
1236        else {
1237            pow1 = pow(10.0, (double)ndigits);
1238            pow2 = 1.0;
1239        }
1240        y = (x*pow1)*pow2;
1241        /* if y overflows, then rounded value is exactly x */
1242        if (!Py_IS_FINITE(y))
1243            return PyFloat_FromDouble(x);
1244    }
1245    else {
1246        pow1 = pow(10.0, (double)-ndigits);
1247        pow2 = 1.0; /* unused; silences a gcc compiler warning */
1248        y = x / pow1;
1249    }
1250
1251    z = round(y);
1252    if (fabs(y-z) == 0.5)
1253        /* halfway between two integers; use round-away-from-zero */
1254        z = y + copysign(0.5, y);
1255
1256    if (ndigits >= 0)
1257        z = (z / pow2) / pow1;
1258    else
1259        z *= pow1;
1260
1261    /* if computation resulted in overflow, raise OverflowError */
1262    if (!Py_IS_FINITE(z)) {
1263        PyErr_SetString(PyExc_OverflowError,
1264                        "overflow occurred during round");
1265        return NULL;
1266    }
1267
1268    return PyFloat_FromDouble(z);
1269}
1270
1271#endif /* PY_NO_SHORT_FLOAT_REPR */
1272
1273static PyObject *
1274float_float(PyObject *v)
1275{
1276    if (PyFloat_CheckExact(v))
1277        Py_INCREF(v);
1278    else
1279        v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1280    return v;
1281}
1282
1283/* turn ASCII hex characters into integer values and vice versa */
1284
1285static char
1286char_from_hex(int x)
1287{
1288    assert(0 <= x && x < 16);
1289    return "0123456789abcdef"[x];
1290}
1291
1292static int
1293hex_from_char(char c) {
1294    int x;
1295    switch(c) {
1296    case '0':
1297        x = 0;
1298        break;
1299    case '1':
1300        x = 1;
1301        break;
1302    case '2':
1303        x = 2;
1304        break;
1305    case '3':
1306        x = 3;
1307        break;
1308    case '4':
1309        x = 4;
1310        break;
1311    case '5':
1312        x = 5;
1313        break;
1314    case '6':
1315        x = 6;
1316        break;
1317    case '7':
1318        x = 7;
1319        break;
1320    case '8':
1321        x = 8;
1322        break;
1323    case '9':
1324        x = 9;
1325        break;
1326    case 'a':
1327    case 'A':
1328        x = 10;
1329        break;
1330    case 'b':
1331    case 'B':
1332        x = 11;
1333        break;
1334    case 'c':
1335    case 'C':
1336        x = 12;
1337        break;
1338    case 'd':
1339    case 'D':
1340        x = 13;
1341        break;
1342    case 'e':
1343    case 'E':
1344        x = 14;
1345        break;
1346    case 'f':
1347    case 'F':
1348        x = 15;
1349        break;
1350    default:
1351        x = -1;
1352        break;
1353    }
1354    return x;
1355}
1356
1357/* convert a float to a hexadecimal string */
1358
1359/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1360   of the form 4k+1. */
1361#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1362
1363static PyObject *
1364float_hex(PyObject *v)
1365{
1366    double x, m;
1367    int e, shift, i, si, esign;
1368    /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1369       trailing NUL byte. */
1370    char s[(TOHEX_NBITS-1)/4+3];
1371
1372    CONVERT_TO_DOUBLE(v, x);
1373
1374    if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1375        return float_str((PyFloatObject *)v);
1376
1377    if (x == 0.0) {
1378        if (copysign(1.0, x) == -1.0)
1379            return PyString_FromString("-0x0.0p+0");
1380        else
1381            return PyString_FromString("0x0.0p+0");
1382    }
1383
1384    m = frexp(fabs(x), &e);
1385    shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1386    m = ldexp(m, shift);
1387    e -= shift;
1388
1389    si = 0;
1390    s[si] = char_from_hex((int)m);
1391    si++;
1392    m -= (int)m;
1393    s[si] = '.';
1394    si++;
1395    for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1396        m *= 16.0;
1397        s[si] = char_from_hex((int)m);
1398        si++;
1399        m -= (int)m;
1400    }
1401    s[si] = '\0';
1402
1403    if (e < 0) {
1404        esign = (int)'-';
1405        e = -e;
1406    }
1407    else
1408        esign = (int)'+';
1409
1410    if (x < 0.0)
1411        return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1412    else
1413        return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1414}
1415
1416PyDoc_STRVAR(float_hex_doc,
1417"float.hex() -> string\n\
1418\n\
1419Return a hexadecimal representation of a floating-point number.\n\
1420>>> (-0.1).hex()\n\
1421'-0x1.999999999999ap-4'\n\
1422>>> 3.14159.hex()\n\
1423'0x1.921f9f01b866ep+1'");
1424
1425/* Case-insensitive locale-independent string match used for nan and inf
1426   detection. t should be lower-case and null-terminated.  Return a nonzero
1427   result if the first strlen(t) characters of s match t and 0 otherwise. */
1428
1429static int
1430case_insensitive_match(const char *s, const char *t)
1431{
1432    while(*t && Py_TOLOWER(*s) == *t) {
1433        s++;
1434        t++;
1435    }
1436    return *t ? 0 : 1;
1437}
1438
1439/* Convert a hexadecimal string to a float. */
1440
1441static PyObject *
1442float_fromhex(PyObject *cls, PyObject *arg)
1443{
1444    PyObject *result_as_float, *result;
1445    double x;
1446    long exp, top_exp, lsb, key_digit;
1447    char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1448    int half_eps, digit, round_up, sign=1;
1449    Py_ssize_t length, ndigits, fdigits, i;
1450
1451    /*
1452     * For the sake of simplicity and correctness, we impose an artificial
1453     * limit on ndigits, the total number of hex digits in the coefficient
1454     * The limit is chosen to ensure that, writing exp for the exponent,
1455     *
1456     *   (1) if exp > LONG_MAX/2 then the value of the hex string is
1457     *   guaranteed to overflow (provided it's nonzero)
1458     *
1459     *   (2) if exp < LONG_MIN/2 then the value of the hex string is
1460     *   guaranteed to underflow to 0.
1461     *
1462     *   (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1463     *   overflow in the calculation of exp and top_exp below.
1464     *
1465     * More specifically, ndigits is assumed to satisfy the following
1466     * inequalities:
1467     *
1468     *   4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1469     *   4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1470     *
1471     * If either of these inequalities is not satisfied, a ValueError is
1472     * raised.  Otherwise, write x for the value of the hex string, and
1473     * assume x is nonzero.  Then
1474     *
1475     *   2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1476     *
1477     * Now if exp > LONG_MAX/2 then:
1478     *
1479     *   exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1480     *                    = DBL_MAX_EXP
1481     *
1482     * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1483     * double, so overflows.  If exp < LONG_MIN/2, then
1484     *
1485     *   exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1486     *                      DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1487     *                    = DBL_MIN_EXP - DBL_MANT_DIG - 1
1488     *
1489     * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1490     * when converted to a C double.
1491     *
1492     * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1493     * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1494     */
1495
1496    if (PyString_AsStringAndSize(arg, &s, &length))
1497        return NULL;
1498    s_end = s + length;
1499
1500    /********************
1501     * Parse the string *
1502     ********************/
1503
1504    /* leading whitespace and optional sign */
1505    while (Py_ISSPACE(*s))
1506        s++;
1507    if (*s == '-') {
1508        s++;
1509        sign = -1;
1510    }
1511    else if (*s == '+')
1512        s++;
1513
1514    /* infinities and nans */
1515    if (*s == 'i' || *s == 'I') {
1516        if (!case_insensitive_match(s+1, "nf"))
1517            goto parse_error;
1518        s += 3;
1519        x = Py_HUGE_VAL;
1520        if (case_insensitive_match(s, "inity"))
1521            s += 5;
1522        goto finished;
1523    }
1524    if (*s == 'n' || *s == 'N') {
1525        if (!case_insensitive_match(s+1, "an"))
1526            goto parse_error;
1527        s += 3;
1528        x = Py_NAN;
1529        goto finished;
1530    }
1531
1532    /* [0x] */
1533    s_store = s;
1534    if (*s == '0') {
1535        s++;
1536        if (*s == 'x' || *s == 'X')
1537            s++;
1538        else
1539            s = s_store;
1540    }
1541
1542    /* coefficient: <integer> [. <fraction>] */
1543    coeff_start = s;
1544    while (hex_from_char(*s) >= 0)
1545        s++;
1546    s_store = s;
1547    if (*s == '.') {
1548        s++;
1549        while (hex_from_char(*s) >= 0)
1550            s++;
1551        coeff_end = s-1;
1552    }
1553    else
1554        coeff_end = s;
1555
1556    /* ndigits = total # of hex digits; fdigits = # after point */
1557    ndigits = coeff_end - coeff_start;
1558    fdigits = coeff_end - s_store;
1559    if (ndigits == 0)
1560        goto parse_error;
1561    if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1562                      LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1563        goto insane_length_error;
1564
1565    /* [p <exponent>] */
1566    if (*s == 'p' || *s == 'P') {
1567        s++;
1568        exp_start = s;
1569        if (*s == '-' || *s == '+')
1570            s++;
1571        if (!('0' <= *s && *s <= '9'))
1572            goto parse_error;
1573        s++;
1574        while ('0' <= *s && *s <= '9')
1575            s++;
1576        exp = strtol(exp_start, NULL, 10);
1577    }
1578    else
1579        exp = 0;
1580
1581/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1582#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ?            \
1583                     coeff_end-(j) :                                    \
1584                     coeff_end-1-(j)))
1585
1586    /*******************************************
1587     * Compute rounded value of the hex string *
1588     *******************************************/
1589
1590    /* Discard leading zeros, and catch extreme overflow and underflow */
1591    while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1592        ndigits--;
1593    if (ndigits == 0 || exp < LONG_MIN/2) {
1594        x = 0.0;
1595        goto finished;
1596    }
1597    if (exp > LONG_MAX/2)
1598        goto overflow_error;
1599
1600    /* Adjust exponent for fractional part. */
1601    exp = exp - 4*((long)fdigits);
1602
1603    /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1604    top_exp = exp + 4*((long)ndigits - 1);
1605    for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1606        top_exp++;
1607
1608    /* catch almost all nonextreme cases of overflow and underflow here */
1609    if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1610        x = 0.0;
1611        goto finished;
1612    }
1613    if (top_exp > DBL_MAX_EXP)
1614        goto overflow_error;
1615
1616    /* lsb = exponent of least significant bit of the *rounded* value.
1617       This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1618    lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1619
1620    x = 0.0;
1621    if (exp >= lsb) {
1622        /* no rounding required */
1623        for (i = ndigits-1; i >= 0; i--)
1624            x = 16.0*x + HEX_DIGIT(i);
1625        x = ldexp(x, (int)(exp));
1626        goto finished;
1627    }
1628    /* rounding required.  key_digit is the index of the hex digit
1629       containing the first bit to be rounded away. */
1630    half_eps = 1 << (int)((lsb - exp - 1) % 4);
1631    key_digit = (lsb - exp - 1) / 4;
1632    for (i = ndigits-1; i > key_digit; i--)
1633        x = 16.0*x + HEX_DIGIT(i);
1634    digit = HEX_DIGIT(key_digit);
1635    x = 16.0*x + (double)(digit & (16-2*half_eps));
1636
1637    /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1638       bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1639    if ((digit & half_eps) != 0) {
1640        round_up = 0;
1641        if ((digit & (3*half_eps-1)) != 0 ||
1642            (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1643            round_up = 1;
1644        else
1645            for (i = key_digit-1; i >= 0; i--)
1646                if (HEX_DIGIT(i) != 0) {
1647                    round_up = 1;
1648                    break;
1649                }
1650        if (round_up == 1) {
1651            x += 2*half_eps;
1652            if (top_exp == DBL_MAX_EXP &&
1653                x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1654                /* overflow corner case: pre-rounded value <
1655                   2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1656                goto overflow_error;
1657        }
1658    }
1659    x = ldexp(x, (int)(exp+4*key_digit));
1660
1661  finished:
1662    /* optional trailing whitespace leading to the end of the string */
1663    while (Py_ISSPACE(*s))
1664        s++;
1665    if (s != s_end)
1666        goto parse_error;
1667    result_as_float = Py_BuildValue("(d)", sign * x);
1668    if (result_as_float == NULL)
1669        return NULL;
1670    result = PyObject_CallObject(cls, result_as_float);
1671    Py_DECREF(result_as_float);
1672    return result;
1673
1674  overflow_error:
1675    PyErr_SetString(PyExc_OverflowError,
1676                    "hexadecimal value too large to represent as a float");
1677    return NULL;
1678
1679  parse_error:
1680    PyErr_SetString(PyExc_ValueError,
1681                    "invalid hexadecimal floating-point string");
1682    return NULL;
1683
1684  insane_length_error:
1685    PyErr_SetString(PyExc_ValueError,
1686                    "hexadecimal string too long to convert");
1687    return NULL;
1688}
1689
1690PyDoc_STRVAR(float_fromhex_doc,
1691"float.fromhex(string) -> float\n\
1692\n\
1693Create a floating-point number from a hexadecimal string.\n\
1694>>> float.fromhex('0x1.ffffp10')\n\
16952047.984375\n\
1696>>> float.fromhex('-0x1p-1074')\n\
1697-4.9406564584124654e-324");
1698
1699
1700static PyObject *
1701float_as_integer_ratio(PyObject *v, PyObject *unused)
1702{
1703    double self;
1704    double float_part;
1705    int exponent;
1706    int i;
1707
1708    PyObject *prev;
1709    PyObject *py_exponent = NULL;
1710    PyObject *numerator = NULL;
1711    PyObject *denominator = NULL;
1712    PyObject *result_pair = NULL;
1713    PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
1714
1715#define INPLACE_UPDATE(obj, call) \
1716    prev = obj; \
1717    obj = call; \
1718    Py_DECREF(prev); \
1719
1720    CONVERT_TO_DOUBLE(v, self);
1721
1722    if (Py_IS_INFINITY(self)) {
1723      PyErr_SetString(PyExc_OverflowError,
1724                      "Cannot pass infinity to float.as_integer_ratio.");
1725      return NULL;
1726    }
1727#ifdef Py_NAN
1728    if (Py_IS_NAN(self)) {
1729      PyErr_SetString(PyExc_ValueError,
1730                      "Cannot pass NaN to float.as_integer_ratio.");
1731      return NULL;
1732    }
1733#endif
1734
1735    PyFPE_START_PROTECT("as_integer_ratio", goto error);
1736    float_part = frexp(self, &exponent);        /* self == float_part * 2**exponent exactly */
1737    PyFPE_END_PROTECT(float_part);
1738
1739    for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1740        float_part *= 2.0;
1741        exponent--;
1742    }
1743    /* self == float_part * 2**exponent exactly and float_part is integral.
1744       If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1745       to be truncated by PyLong_FromDouble(). */
1746
1747    numerator = PyLong_FromDouble(float_part);
1748    if (numerator == NULL) goto error;
1749
1750    /* fold in 2**exponent */
1751    denominator = PyLong_FromLong(1);
1752    py_exponent = PyLong_FromLong(labs((long)exponent));
1753    if (py_exponent == NULL) goto error;
1754    INPLACE_UPDATE(py_exponent,
1755                   long_methods->nb_lshift(denominator, py_exponent));
1756    if (py_exponent == NULL) goto error;
1757    if (exponent > 0) {
1758        INPLACE_UPDATE(numerator,
1759                       long_methods->nb_multiply(numerator, py_exponent));
1760        if (numerator == NULL) goto error;
1761    }
1762    else {
1763        Py_DECREF(denominator);
1764        denominator = py_exponent;
1765        py_exponent = NULL;
1766    }
1767
1768    /* Returns ints instead of longs where possible */
1769    INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1770    if (numerator == NULL) goto error;
1771    INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1772    if (denominator == NULL) goto error;
1773
1774    result_pair = PyTuple_Pack(2, numerator, denominator);
1775
1776#undef INPLACE_UPDATE
1777error:
1778    Py_XDECREF(py_exponent);
1779    Py_XDECREF(denominator);
1780    Py_XDECREF(numerator);
1781    return result_pair;
1782}
1783
1784PyDoc_STRVAR(float_as_integer_ratio_doc,
1785"float.as_integer_ratio() -> (int, int)\n"
1786"\n"
1787"Return a pair of integers, whose ratio is exactly equal to the original\n"
1788"float and with a positive denominator.\n"
1789"Raise OverflowError on infinities and a ValueError on NaNs.\n"
1790"\n"
1791">>> (10.0).as_integer_ratio()\n"
1792"(10, 1)\n"
1793">>> (0.0).as_integer_ratio()\n"
1794"(0, 1)\n"
1795">>> (-.25).as_integer_ratio()\n"
1796"(-1, 4)");
1797
1798
1799static PyObject *
1800float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1801
1802static PyObject *
1803float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1804{
1805    PyObject *x = Py_False; /* Integer zero */
1806    static char *kwlist[] = {"x", 0};
1807
1808    if (type != &PyFloat_Type)
1809        return float_subtype_new(type, args, kwds); /* Wimp out */
1810    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1811        return NULL;
1812    /* If it's a string, but not a string subclass, use
1813       PyFloat_FromString. */
1814    if (PyString_CheckExact(x))
1815        return PyFloat_FromString(x, NULL);
1816    return PyNumber_Float(x);
1817}
1818
1819/* Wimpy, slow approach to tp_new calls for subtypes of float:
1820   first create a regular float from whatever arguments we got,
1821   then allocate a subtype instance and initialize its ob_fval
1822   from the regular float.  The regular float is then thrown away.
1823*/
1824static PyObject *
1825float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1826{
1827    PyObject *tmp, *newobj;
1828
1829    assert(PyType_IsSubtype(type, &PyFloat_Type));
1830    tmp = float_new(&PyFloat_Type, args, kwds);
1831    if (tmp == NULL)
1832        return NULL;
1833    assert(PyFloat_CheckExact(tmp));
1834    newobj = type->tp_alloc(type, 0);
1835    if (newobj == NULL) {
1836        Py_DECREF(tmp);
1837        return NULL;
1838    }
1839    ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1840    Py_DECREF(tmp);
1841    return newobj;
1842}
1843
1844static PyObject *
1845float_getnewargs(PyFloatObject *v)
1846{
1847    return Py_BuildValue("(d)", v->ob_fval);
1848}
1849
1850/* this is for the benefit of the pack/unpack routines below */
1851
1852typedef enum {
1853    unknown_format, ieee_big_endian_format, ieee_little_endian_format
1854} float_format_type;
1855
1856static float_format_type double_format, float_format;
1857static float_format_type detected_double_format, detected_float_format;
1858
1859static PyObject *
1860float_getformat(PyTypeObject *v, PyObject* arg)
1861{
1862    char* s;
1863    float_format_type r;
1864
1865    if (!PyString_Check(arg)) {
1866        PyErr_Format(PyExc_TypeError,
1867         "__getformat__() argument must be string, not %.500s",
1868                         Py_TYPE(arg)->tp_name);
1869        return NULL;
1870    }
1871    s = PyString_AS_STRING(arg);
1872    if (strcmp(s, "double") == 0) {
1873        r = double_format;
1874    }
1875    else if (strcmp(s, "float") == 0) {
1876        r = float_format;
1877    }
1878    else {
1879        PyErr_SetString(PyExc_ValueError,
1880                        "__getformat__() argument 1 must be "
1881                        "'double' or 'float'");
1882        return NULL;
1883    }
1884
1885    switch (r) {
1886    case unknown_format:
1887        return PyString_FromString("unknown");
1888    case ieee_little_endian_format:
1889        return PyString_FromString("IEEE, little-endian");
1890    case ieee_big_endian_format:
1891        return PyString_FromString("IEEE, big-endian");
1892    default:
1893        Py_FatalError("insane float_format or double_format");
1894        return NULL;
1895    }
1896}
1897
1898PyDoc_STRVAR(float_getformat_doc,
1899"float.__getformat__(typestr) -> string\n"
1900"\n"
1901"You probably don't want to use this function.  It exists mainly to be\n"
1902"used in Python's test suite.\n"
1903"\n"
1904"typestr must be 'double' or 'float'.  This function returns whichever of\n"
1905"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1906"format of floating point numbers used by the C type named by typestr.");
1907
1908static PyObject *
1909float_setformat(PyTypeObject *v, PyObject* args)
1910{
1911    char* typestr;
1912    char* format;
1913    float_format_type f;
1914    float_format_type detected;
1915    float_format_type *p;
1916
1917    if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1918        return NULL;
1919
1920    if (strcmp(typestr, "double") == 0) {
1921        p = &double_format;
1922        detected = detected_double_format;
1923    }
1924    else if (strcmp(typestr, "float") == 0) {
1925        p = &float_format;
1926        detected = detected_float_format;
1927    }
1928    else {
1929        PyErr_SetString(PyExc_ValueError,
1930                        "__setformat__() argument 1 must "
1931                        "be 'double' or 'float'");
1932        return NULL;
1933    }
1934
1935    if (strcmp(format, "unknown") == 0) {
1936        f = unknown_format;
1937    }
1938    else if (strcmp(format, "IEEE, little-endian") == 0) {
1939        f = ieee_little_endian_format;
1940    }
1941    else if (strcmp(format, "IEEE, big-endian") == 0) {
1942        f = ieee_big_endian_format;
1943    }
1944    else {
1945        PyErr_SetString(PyExc_ValueError,
1946                        "__setformat__() argument 2 must be "
1947                        "'unknown', 'IEEE, little-endian' or "
1948                        "'IEEE, big-endian'");
1949        return NULL;
1950
1951    }
1952
1953    if (f != unknown_format && f != detected) {
1954        PyErr_Format(PyExc_ValueError,
1955                     "can only set %s format to 'unknown' or the "
1956                     "detected platform value", typestr);
1957        return NULL;
1958    }
1959
1960    *p = f;
1961    Py_RETURN_NONE;
1962}
1963
1964PyDoc_STRVAR(float_setformat_doc,
1965"float.__setformat__(typestr, fmt) -> None\n"
1966"\n"
1967"You probably don't want to use this function.  It exists mainly to be\n"
1968"used in Python's test suite.\n"
1969"\n"
1970"typestr must be 'double' or 'float'.  fmt must be one of 'unknown',\n"
1971"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1972"one of the latter two if it appears to match the underlying C reality.\n"
1973"\n"
1974"Override the automatic determination of C-level floating point type.\n"
1975"This affects how floats are converted to and from binary strings.");
1976
1977static PyObject *
1978float_getzero(PyObject *v, void *closure)
1979{
1980    return PyFloat_FromDouble(0.0);
1981}
1982
1983static PyObject *
1984float__format__(PyObject *self, PyObject *args)
1985{
1986    PyObject *format_spec;
1987
1988    if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1989        return NULL;
1990    if (PyBytes_Check(format_spec))
1991        return _PyFloat_FormatAdvanced(self,
1992                                       PyBytes_AS_STRING(format_spec),
1993                                       PyBytes_GET_SIZE(format_spec));
1994    if (PyUnicode_Check(format_spec)) {
1995        /* Convert format_spec to a str */
1996        PyObject *result;
1997        PyObject *str_spec = PyObject_Str(format_spec);
1998
1999        if (str_spec == NULL)
2000            return NULL;
2001
2002        result = _PyFloat_FormatAdvanced(self,
2003                                         PyBytes_AS_STRING(str_spec),
2004                                         PyBytes_GET_SIZE(str_spec));
2005
2006        Py_DECREF(str_spec);
2007        return result;
2008    }
2009    PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
2010    return NULL;
2011}
2012
2013PyDoc_STRVAR(float__format__doc,
2014"float.__format__(format_spec) -> string\n"
2015"\n"
2016"Formats the float according to format_spec.");
2017
2018
2019static PyMethodDef float_methods[] = {
2020    {"conjugate",       (PyCFunction)float_float,       METH_NOARGS,
2021     "Return self, the complex conjugate of any float."},
2022    {"__trunc__",       (PyCFunction)float_trunc, METH_NOARGS,
2023     "Return the Integral closest to x between 0 and x."},
2024    {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
2025     float_as_integer_ratio_doc},
2026    {"fromhex", (PyCFunction)float_fromhex,
2027     METH_O|METH_CLASS, float_fromhex_doc},
2028    {"hex", (PyCFunction)float_hex,
2029     METH_NOARGS, float_hex_doc},
2030    {"is_integer",      (PyCFunction)float_is_integer,  METH_NOARGS,
2031     "Return True if the float is an integer."},
2032#if 0
2033    {"is_inf",          (PyCFunction)float_is_inf,      METH_NOARGS,
2034     "Return True if the float is positive or negative infinite."},
2035    {"is_finite",       (PyCFunction)float_is_finite,   METH_NOARGS,
2036     "Return True if the float is finite, neither infinite nor NaN."},
2037    {"is_nan",          (PyCFunction)float_is_nan,      METH_NOARGS,
2038     "Return True if the float is not a number (NaN)."},
2039#endif
2040    {"__getnewargs__",          (PyCFunction)float_getnewargs,  METH_NOARGS},
2041    {"__getformat__",           (PyCFunction)float_getformat,
2042     METH_O|METH_CLASS,                 float_getformat_doc},
2043    {"__setformat__",           (PyCFunction)float_setformat,
2044     METH_VARARGS|METH_CLASS,           float_setformat_doc},
2045    {"__format__",          (PyCFunction)float__format__,
2046     METH_VARARGS,                  float__format__doc},
2047    {NULL,              NULL}           /* sentinel */
2048};
2049
2050static PyGetSetDef float_getset[] = {
2051    {"real",
2052     (getter)float_float, (setter)NULL,
2053     "the real part of a complex number",
2054     NULL},
2055    {"imag",
2056     (getter)float_getzero, (setter)NULL,
2057     "the imaginary part of a complex number",
2058     NULL},
2059    {NULL}  /* Sentinel */
2060};
2061
2062PyDoc_STRVAR(float_doc,
2063"float(x) -> floating point number\n\
2064\n\
2065Convert a string or number to a floating point number, if possible.");
2066
2067
2068static PyNumberMethods float_as_number = {
2069    float_add,          /*nb_add*/
2070    float_sub,          /*nb_subtract*/
2071    float_mul,          /*nb_multiply*/
2072    float_classic_div, /*nb_divide*/
2073    float_rem,          /*nb_remainder*/
2074    float_divmod,       /*nb_divmod*/
2075    float_pow,          /*nb_power*/
2076    (unaryfunc)float_neg, /*nb_negative*/
2077    (unaryfunc)float_float, /*nb_positive*/
2078    (unaryfunc)float_abs, /*nb_absolute*/
2079    (inquiry)float_nonzero, /*nb_nonzero*/
2080    0,                  /*nb_invert*/
2081    0,                  /*nb_lshift*/
2082    0,                  /*nb_rshift*/
2083    0,                  /*nb_and*/
2084    0,                  /*nb_xor*/
2085    0,                  /*nb_or*/
2086    float_coerce,       /*nb_coerce*/
2087    float_trunc,        /*nb_int*/
2088    float_long,         /*nb_long*/
2089    float_float,        /*nb_float*/
2090    0,                  /* nb_oct */
2091    0,                  /* nb_hex */
2092    0,                  /* nb_inplace_add */
2093    0,                  /* nb_inplace_subtract */
2094    0,                  /* nb_inplace_multiply */
2095    0,                  /* nb_inplace_divide */
2096    0,                  /* nb_inplace_remainder */
2097    0,                  /* nb_inplace_power */
2098    0,                  /* nb_inplace_lshift */
2099    0,                  /* nb_inplace_rshift */
2100    0,                  /* nb_inplace_and */
2101    0,                  /* nb_inplace_xor */
2102    0,                  /* nb_inplace_or */
2103    float_floor_div, /* nb_floor_divide */
2104    float_div,          /* nb_true_divide */
2105    0,                  /* nb_inplace_floor_divide */
2106    0,                  /* nb_inplace_true_divide */
2107};
2108
2109PyTypeObject PyFloat_Type = {
2110    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2111    "float",
2112    sizeof(PyFloatObject),
2113    0,
2114    (destructor)float_dealloc,                  /* tp_dealloc */
2115    (printfunc)float_print,                     /* tp_print */
2116    0,                                          /* tp_getattr */
2117    0,                                          /* tp_setattr */
2118    0,                                          /* tp_compare */
2119    (reprfunc)float_repr,                       /* tp_repr */
2120    &float_as_number,                           /* tp_as_number */
2121    0,                                          /* tp_as_sequence */
2122    0,                                          /* tp_as_mapping */
2123    (hashfunc)float_hash,                       /* tp_hash */
2124    0,                                          /* tp_call */
2125    (reprfunc)float_str,                        /* tp_str */
2126    PyObject_GenericGetAttr,                    /* tp_getattro */
2127    0,                                          /* tp_setattro */
2128    0,                                          /* tp_as_buffer */
2129    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2130        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
2131    float_doc,                                  /* tp_doc */
2132    0,                                          /* tp_traverse */
2133    0,                                          /* tp_clear */
2134    float_richcompare,                          /* tp_richcompare */
2135    0,                                          /* tp_weaklistoffset */
2136    0,                                          /* tp_iter */
2137    0,                                          /* tp_iternext */
2138    float_methods,                              /* tp_methods */
2139    0,                                          /* tp_members */
2140    float_getset,                               /* tp_getset */
2141    0,                                          /* tp_base */
2142    0,                                          /* tp_dict */
2143    0,                                          /* tp_descr_get */
2144    0,                                          /* tp_descr_set */
2145    0,                                          /* tp_dictoffset */
2146    0,                                          /* tp_init */
2147    0,                                          /* tp_alloc */
2148    float_new,                                  /* tp_new */
2149};
2150
2151void
2152_PyFloat_Init(void)
2153{
2154    /* We attempt to determine if this machine is using IEEE
2155       floating point formats by peering at the bits of some
2156       carefully chosen values.  If it looks like we are on an
2157       IEEE platform, the float packing/unpacking routines can
2158       just copy bits, if not they resort to arithmetic & shifts
2159       and masks.  The shifts & masks approach works on all finite
2160       values, but what happens to infinities, NaNs and signed
2161       zeroes on packing is an accident, and attempting to unpack
2162       a NaN or an infinity will raise an exception.
2163
2164       Note that if we're on some whacked-out platform which uses
2165       IEEE formats but isn't strictly little-endian or big-
2166       endian, we will fall back to the portable shifts & masks
2167       method. */
2168
2169#if SIZEOF_DOUBLE == 8
2170    {
2171        double x = 9006104071832581.0;
2172        if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2173            detected_double_format = ieee_big_endian_format;
2174        else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2175            detected_double_format = ieee_little_endian_format;
2176        else
2177            detected_double_format = unknown_format;
2178    }
2179#else
2180    detected_double_format = unknown_format;
2181#endif
2182
2183#if SIZEOF_FLOAT == 4
2184    {
2185        float y = 16711938.0;
2186        if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2187            detected_float_format = ieee_big_endian_format;
2188        else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2189            detected_float_format = ieee_little_endian_format;
2190        else
2191            detected_float_format = unknown_format;
2192    }
2193#else
2194    detected_float_format = unknown_format;
2195#endif
2196
2197    double_format = detected_double_format;
2198    float_format = detected_float_format;
2199
2200    /* Init float info */
2201    if (FloatInfoType.tp_name == 0)
2202        PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
2203}
2204
2205int
2206PyFloat_ClearFreeList(void)
2207{
2208    PyFloatObject *p;
2209    PyFloatBlock *list, *next;
2210    int i;
2211    int u;                      /* remaining unfreed ints per block */
2212    int freelist_size = 0;
2213
2214    list = block_list;
2215    block_list = NULL;
2216    free_list = NULL;
2217    while (list != NULL) {
2218        u = 0;
2219        for (i = 0, p = &list->objects[0];
2220             i < N_FLOATOBJECTS;
2221             i++, p++) {
2222            if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
2223                u++;
2224        }
2225        next = list->next;
2226        if (u) {
2227            list->next = block_list;
2228            block_list = list;
2229            for (i = 0, p = &list->objects[0];
2230                 i < N_FLOATOBJECTS;
2231                 i++, p++) {
2232                if (!PyFloat_CheckExact(p) ||
2233                    Py_REFCNT(p) == 0) {
2234                    Py_TYPE(p) = (struct _typeobject *)
2235                        free_list;
2236                    free_list = p;
2237                }
2238            }
2239        }
2240        else {
2241            PyMem_FREE(list);
2242        }
2243        freelist_size += u;
2244        list = next;
2245    }
2246    return freelist_size;
2247}
2248
2249void
2250PyFloat_Fini(void)
2251{
2252    PyFloatObject *p;
2253    PyFloatBlock *list;
2254    int i;
2255    int u;                      /* total unfreed floats per block */
2256
2257    u = PyFloat_ClearFreeList();
2258
2259    if (!Py_VerboseFlag)
2260        return;
2261    fprintf(stderr, "# cleanup floats");
2262    if (!u) {
2263        fprintf(stderr, "\n");
2264    }
2265    else {
2266        fprintf(stderr,
2267            ": %d unfreed float%s\n",
2268            u, u == 1 ? "" : "s");
2269    }
2270    if (Py_VerboseFlag > 1) {
2271        list = block_list;
2272        while (list != NULL) {
2273            for (i = 0, p = &list->objects[0];
2274                 i < N_FLOATOBJECTS;
2275                 i++, p++) {
2276                if (PyFloat_CheckExact(p) &&
2277                    Py_REFCNT(p) != 0) {
2278                    char *buf = PyOS_double_to_string(
2279                        PyFloat_AS_DOUBLE(p), 'r',
2280                        0, 0, NULL);
2281                    if (buf) {
2282                        /* XXX(twouters) cast
2283                           refcount to long
2284                           until %zd is
2285                           universally
2286                           available
2287                        */
2288                        fprintf(stderr,
2289                 "#   <float at %p, refcnt=%ld, val=%s>\n",
2290                                    p, (long)Py_REFCNT(p), buf);
2291                                    PyMem_Free(buf);
2292                            }
2293                }
2294            }
2295            list = list->next;
2296        }
2297    }
2298}
2299
2300/*----------------------------------------------------------------------------
2301 * _PyFloat_{Pack,Unpack}{4,8}.  See floatobject.h.
2302 */
2303int
2304_PyFloat_Pack4(double x, unsigned char *p, int le)
2305{
2306    if (float_format == unknown_format) {
2307        unsigned char sign;
2308        int e;
2309        double f;
2310        unsigned int fbits;
2311        int incr = 1;
2312
2313        if (le) {
2314            p += 3;
2315            incr = -1;
2316        }
2317
2318        if (x < 0) {
2319            sign = 1;
2320            x = -x;
2321        }
2322        else
2323            sign = 0;
2324
2325        f = frexp(x, &e);
2326
2327        /* Normalize f to be in the range [1.0, 2.0) */
2328        if (0.5 <= f && f < 1.0) {
2329            f *= 2.0;
2330            e--;
2331        }
2332        else if (f == 0.0)
2333            e = 0;
2334        else {
2335            PyErr_SetString(PyExc_SystemError,
2336                            "frexp() result out of range");
2337            return -1;
2338        }
2339
2340        if (e >= 128)
2341            goto Overflow;
2342        else if (e < -126) {
2343            /* Gradual underflow */
2344            f = ldexp(f, 126 + e);
2345            e = 0;
2346        }
2347        else if (!(e == 0 && f == 0.0)) {
2348            e += 127;
2349            f -= 1.0; /* Get rid of leading 1 */
2350        }
2351
2352        f *= 8388608.0; /* 2**23 */
2353        fbits = (unsigned int)(f + 0.5); /* Round */
2354        assert(fbits <= 8388608);
2355        if (fbits >> 23) {
2356            /* The carry propagated out of a string of 23 1 bits. */
2357            fbits = 0;
2358            ++e;
2359            if (e >= 255)
2360                goto Overflow;
2361        }
2362
2363        /* First byte */
2364        *p = (sign << 7) | (e >> 1);
2365        p += incr;
2366
2367        /* Second byte */
2368        *p = (char) (((e & 1) << 7) | (fbits >> 16));
2369        p += incr;
2370
2371        /* Third byte */
2372        *p = (fbits >> 8) & 0xFF;
2373        p += incr;
2374
2375        /* Fourth byte */
2376        *p = fbits & 0xFF;
2377
2378        /* Done */
2379        return 0;
2380
2381    }
2382    else {
2383        float y = (float)x;
2384        const char *s = (char*)&y;
2385        int i, incr = 1;
2386
2387        if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2388            goto Overflow;
2389
2390        if ((float_format == ieee_little_endian_format && !le)
2391            || (float_format == ieee_big_endian_format && le)) {
2392            p += 3;
2393            incr = -1;
2394        }
2395
2396        for (i = 0; i < 4; i++) {
2397            *p = *s++;
2398            p += incr;
2399        }
2400        return 0;
2401    }
2402  Overflow:
2403    PyErr_SetString(PyExc_OverflowError,
2404                    "float too large to pack with f format");
2405    return -1;
2406}
2407
2408int
2409_PyFloat_Pack8(double x, unsigned char *p, int le)
2410{
2411    if (double_format == unknown_format) {
2412        unsigned char sign;
2413        int e;
2414        double f;
2415        unsigned int fhi, flo;
2416        int incr = 1;
2417
2418        if (le) {
2419            p += 7;
2420            incr = -1;
2421        }
2422
2423        if (x < 0) {
2424            sign = 1;
2425            x = -x;
2426        }
2427        else
2428            sign = 0;
2429
2430        f = frexp(x, &e);
2431
2432        /* Normalize f to be in the range [1.0, 2.0) */
2433        if (0.5 <= f && f < 1.0) {
2434            f *= 2.0;
2435            e--;
2436        }
2437        else if (f == 0.0)
2438            e = 0;
2439        else {
2440            PyErr_SetString(PyExc_SystemError,
2441                            "frexp() result out of range");
2442            return -1;
2443        }
2444
2445        if (e >= 1024)
2446            goto Overflow;
2447        else if (e < -1022) {
2448            /* Gradual underflow */
2449            f = ldexp(f, 1022 + e);
2450            e = 0;
2451        }
2452        else if (!(e == 0 && f == 0.0)) {
2453            e += 1023;
2454            f -= 1.0; /* Get rid of leading 1 */
2455        }
2456
2457        /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2458        f *= 268435456.0; /* 2**28 */
2459        fhi = (unsigned int)f; /* Truncate */
2460        assert(fhi < 268435456);
2461
2462        f -= (double)fhi;
2463        f *= 16777216.0; /* 2**24 */
2464        flo = (unsigned int)(f + 0.5); /* Round */
2465        assert(flo <= 16777216);
2466        if (flo >> 24) {
2467            /* The carry propagated out of a string of 24 1 bits. */
2468            flo = 0;
2469            ++fhi;
2470            if (fhi >> 28) {
2471                /* And it also progagated out of the next 28 bits. */
2472                fhi = 0;
2473                ++e;
2474                if (e >= 2047)
2475                    goto Overflow;
2476            }
2477        }
2478
2479        /* First byte */
2480        *p = (sign << 7) | (e >> 4);
2481        p += incr;
2482
2483        /* Second byte */
2484        *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2485        p += incr;
2486
2487        /* Third byte */
2488        *p = (fhi >> 16) & 0xFF;
2489        p += incr;
2490
2491        /* Fourth byte */
2492        *p = (fhi >> 8) & 0xFF;
2493        p += incr;
2494
2495        /* Fifth byte */
2496        *p = fhi & 0xFF;
2497        p += incr;
2498
2499        /* Sixth byte */
2500        *p = (flo >> 16) & 0xFF;
2501        p += incr;
2502
2503        /* Seventh byte */
2504        *p = (flo >> 8) & 0xFF;
2505        p += incr;
2506
2507        /* Eighth byte */
2508        *p = flo & 0xFF;
2509        /* p += incr; Unneeded (for now) */
2510
2511        /* Done */
2512        return 0;
2513
2514      Overflow:
2515        PyErr_SetString(PyExc_OverflowError,
2516                        "float too large to pack with d format");
2517        return -1;
2518    }
2519    else {
2520        const char *s = (char*)&x;
2521        int i, incr = 1;
2522
2523        if ((double_format == ieee_little_endian_format && !le)
2524            || (double_format == ieee_big_endian_format && le)) {
2525            p += 7;
2526            incr = -1;
2527        }
2528
2529        for (i = 0; i < 8; i++) {
2530            *p = *s++;
2531            p += incr;
2532        }
2533        return 0;
2534    }
2535}
2536
2537double
2538_PyFloat_Unpack4(const unsigned char *p, int le)
2539{
2540    if (float_format == unknown_format) {
2541        unsigned char sign;
2542        int e;
2543        unsigned int f;
2544        double x;
2545        int incr = 1;
2546
2547        if (le) {
2548            p += 3;
2549            incr = -1;
2550        }
2551
2552        /* First byte */
2553        sign = (*p >> 7) & 1;
2554        e = (*p & 0x7F) << 1;
2555        p += incr;
2556
2557        /* Second byte */
2558        e |= (*p >> 7) & 1;
2559        f = (*p & 0x7F) << 16;
2560        p += incr;
2561
2562        if (e == 255) {
2563            PyErr_SetString(
2564                PyExc_ValueError,
2565                "can't unpack IEEE 754 special value "
2566                "on non-IEEE platform");
2567            return -1;
2568        }
2569
2570        /* Third byte */
2571        f |= *p << 8;
2572        p += incr;
2573
2574        /* Fourth byte */
2575        f |= *p;
2576
2577        x = (double)f / 8388608.0;
2578
2579        /* XXX This sadly ignores Inf/NaN issues */
2580        if (e == 0)
2581            e = -126;
2582        else {
2583            x += 1.0;
2584            e -= 127;
2585        }
2586        x = ldexp(x, e);
2587
2588        if (sign)
2589            x = -x;
2590
2591        return x;
2592    }
2593    else {
2594        float x;
2595
2596        if ((float_format == ieee_little_endian_format && !le)
2597            || (float_format == ieee_big_endian_format && le)) {
2598            char buf[4];
2599            char *d = &buf[3];
2600            int i;
2601
2602            for (i = 0; i < 4; i++) {
2603                *d-- = *p++;
2604            }
2605            memcpy(&x, buf, 4);
2606        }
2607        else {
2608            memcpy(&x, p, 4);
2609        }
2610
2611        return x;
2612    }
2613}
2614
2615double
2616_PyFloat_Unpack8(const unsigned char *p, int le)
2617{
2618    if (double_format == unknown_format) {
2619        unsigned char sign;
2620        int e;
2621        unsigned int fhi, flo;
2622        double x;
2623        int incr = 1;
2624
2625        if (le) {
2626            p += 7;
2627            incr = -1;
2628        }
2629
2630        /* First byte */
2631        sign = (*p >> 7) & 1;
2632        e = (*p & 0x7F) << 4;
2633
2634        p += incr;
2635
2636        /* Second byte */
2637        e |= (*p >> 4) & 0xF;
2638        fhi = (*p & 0xF) << 24;
2639        p += incr;
2640
2641        if (e == 2047) {
2642            PyErr_SetString(
2643                PyExc_ValueError,
2644                "can't unpack IEEE 754 special value "
2645                "on non-IEEE platform");
2646            return -1.0;
2647        }
2648
2649        /* Third byte */
2650        fhi |= *p << 16;
2651        p += incr;
2652
2653        /* Fourth byte */
2654        fhi |= *p  << 8;
2655        p += incr;
2656
2657        /* Fifth byte */
2658        fhi |= *p;
2659        p += incr;
2660
2661        /* Sixth byte */
2662        flo = *p << 16;
2663        p += incr;
2664
2665        /* Seventh byte */
2666        flo |= *p << 8;
2667        p += incr;
2668
2669        /* Eighth byte */
2670        flo |= *p;
2671
2672        x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2673        x /= 268435456.0; /* 2**28 */
2674
2675        if (e == 0)
2676            e = -1022;
2677        else {
2678            x += 1.0;
2679            e -= 1023;
2680        }
2681        x = ldexp(x, e);
2682
2683        if (sign)
2684            x = -x;
2685
2686        return x;
2687    }
2688    else {
2689        double x;
2690
2691        if ((double_format == ieee_little_endian_format && !le)
2692            || (double_format == ieee_big_endian_format && le)) {
2693            char buf[8];
2694            char *d = &buf[7];
2695            int i;
2696
2697            for (i = 0; i < 8; i++) {
2698                *d-- = *p++;
2699            }
2700            memcpy(&x, buf, 8);
2701        }
2702        else {
2703            memcpy(&x, p, 8);
2704        }
2705
2706        return x;
2707    }
2708}
2709