LCOV - code coverage report
Current view: top level - Objects - floatobject.c (source / functions) Hit Total Coverage
Test: CPython lcov report Lines: 867 1095 79.2 %
Date: 2022-07-07 18:19:46 Functions: 57 59 96.6 %

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

Generated by: LCOV version 1.14