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