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