Python-2.7.3/Objects/floatobject.c

No issues found

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