Coverage Report

Created: 2026-04-12 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/floatobject.c
Line
Count
Source
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_abstract.h"      // _PyNumber_Index()
8
#include "pycore_dtoa.h"          // _Py_dg_dtoa()
9
#include "pycore_floatobject.h"   // _PyFloat_FormatAdvancedWriter()
10
#include "pycore_freelist.h"      // _Py_FREELIST_FREE(), _Py_FREELIST_POP()
11
#include "pycore_initconfig.h"    // _PyStatus_OK()
12
#include "pycore_long.h"          // _PyLong_GetOne()
13
#include "pycore_modsupport.h"    // _PyArg_NoKwnames()
14
#include "pycore_object.h"        // _PyObject_Init(), _PyDebugAllocatorStats()
15
#include "pycore_pymath.h"        // _PY_SHORT_FLOAT_REPR
16
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
17
#include "pycore_stackref.h"      // PyStackRef_AsPyObjectBorrow()
18
#include "pycore_structseq.h"     // _PyStructSequence_FiniBuiltin()
19
#include "pycore_tuple.h"         // _PyTuple_FromPair
20
21
#include <float.h>                // DBL_MAX
22
#include <stdlib.h>               // strtol()
23
24
/*[clinic input]
25
class float "PyObject *" "&PyFloat_Type"
26
[clinic start generated code]*/
27
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/
28
29
#include "clinic/floatobject.c.h"
30
31
32
double
33
PyFloat_GetMax(void)
34
0
{
35
0
    return DBL_MAX;
36
0
}
37
38
double
39
PyFloat_GetMin(void)
40
0
{
41
0
    return DBL_MIN;
42
0
}
43
44
static PyTypeObject FloatInfoType;
45
46
PyDoc_STRVAR(floatinfo__doc__,
47
"sys.float_info\n\
48
\n\
49
A named tuple holding information about the float type. It contains low level\n\
50
information about the precision and internal representation. Please study\n\
51
your system's :file:`float.h` for more information.");
52
53
static PyStructSequence_Field floatinfo_fields[] = {
54
    {"max",             "DBL_MAX -- maximum representable finite float"},
55
    {"max_exp",         "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
56
                    "is representable"},
57
    {"max_10_exp",      "DBL_MAX_10_EXP -- maximum int e such that 10**e "
58
                    "is representable"},
59
    {"min",             "DBL_MIN -- Minimum positive normalized float"},
60
    {"min_exp",         "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
61
                    "is a normalized float"},
62
    {"min_10_exp",      "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
63
                    "a normalized float"},
64
    {"dig",             "DBL_DIG -- maximum number of decimal digits that "
65
                    "can be faithfully represented in a float"},
66
    {"mant_dig",        "DBL_MANT_DIG -- mantissa digits"},
67
    {"epsilon",         "DBL_EPSILON -- Difference between 1 and the next "
68
                    "representable float"},
69
    {"radix",           "FLT_RADIX -- radix of exponent"},
70
    {"rounds",          "FLT_ROUNDS -- rounding mode used for arithmetic "
71
                    "operations"},
72
    {0}
73
};
74
75
static PyStructSequence_Desc floatinfo_desc = {
76
    "sys.float_info",           /* name */
77
    floatinfo__doc__,           /* doc */
78
    floatinfo_fields,           /* fields */
79
    11
80
};
81
82
PyObject *
83
PyFloat_GetInfo(void)
84
36
{
85
36
    PyObject* floatinfo;
86
36
    int pos = 0;
87
88
36
    floatinfo = PyStructSequence_New(&FloatInfoType);
89
36
    if (floatinfo == NULL) {
90
0
        return NULL;
91
0
    }
92
93
36
#define SetFlag(CALL) \
94
396
    do {                                                    \
95
396
        PyObject *flag = (CALL);                            \
96
396
        if (flag == NULL) {                                 \
97
0
            Py_CLEAR(floatinfo);                            \
98
0
            return NULL;                                    \
99
0
        }                                                   \
100
396
        PyStructSequence_SET_ITEM(floatinfo, pos++, flag);  \
101
396
    } while (0)
102
103
288
#define SetIntFlag(FLAG) SetFlag(PyLong_FromLong((FLAG)))
104
108
#define SetDblFlag(FLAG) SetFlag(PyFloat_FromDouble((FLAG)))
105
106
36
    SetDblFlag(DBL_MAX);
107
36
    SetIntFlag(DBL_MAX_EXP);
108
36
    SetIntFlag(DBL_MAX_10_EXP);
109
36
    SetDblFlag(DBL_MIN);
110
36
    SetIntFlag(DBL_MIN_EXP);
111
36
    SetIntFlag(DBL_MIN_10_EXP);
112
36
    SetIntFlag(DBL_DIG);
113
36
    SetIntFlag(DBL_MANT_DIG);
114
36
    SetDblFlag(DBL_EPSILON);
115
36
    SetIntFlag(FLT_RADIX);
116
36
    SetIntFlag(FLT_ROUNDS);
117
36
#undef SetIntFlag
118
36
#undef SetDblFlag
119
36
#undef SetFlag
120
121
36
    return floatinfo;
122
36
}
123
124
PyObject *
125
PyFloat_FromDouble(double fval)
126
9.41M
{
127
9.41M
    PyFloatObject *op = _Py_FREELIST_POP(PyFloatObject, floats);
128
9.41M
    if (op == NULL) {
129
1.64M
        op = PyObject_Malloc(sizeof(PyFloatObject));
130
1.64M
        if (!op) {
131
0
            return PyErr_NoMemory();
132
0
        }
133
1.64M
        _PyObject_Init((PyObject*)op, &PyFloat_Type);
134
1.64M
    }
135
9.41M
    op->ob_fval = fval;
136
9.41M
    return (PyObject *) op;
137
9.41M
}
138
139
static PyObject *
140
float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
141
1.21M
{
142
1.21M
    double x;
143
1.21M
    const char *end;
144
1.21M
    const char *last = s + len;
145
    /* strip leading whitespace */
146
1.21M
    while (s < last && Py_ISSPACE(*s)) {
147
0
        s++;
148
0
    }
149
1.21M
    if (s == last) {
150
0
        PyErr_Format(PyExc_ValueError,
151
0
                     "could not convert string to float: "
152
0
                     "%R", obj);
153
0
        return NULL;
154
0
    }
155
156
    /* strip trailing whitespace */
157
1.21M
    while (s < last - 1 && Py_ISSPACE(last[-1])) {
158
0
        last--;
159
0
    }
160
161
    /* We don't care about overflow or underflow.  If the platform
162
     * supports them, infinities and signed zeroes (on underflow) are
163
     * fine. */
164
1.21M
    x = PyOS_string_to_double(s, (char **)&end, NULL);
165
1.21M
    if (end != last) {
166
0
        PyErr_Format(PyExc_ValueError,
167
0
                     "could not convert string to float: "
168
0
                     "%R", obj);
169
0
        return NULL;
170
0
    }
171
1.21M
    else if (x == -1.0 && PyErr_Occurred()) {
172
0
        return NULL;
173
0
    }
174
1.21M
    else {
175
1.21M
        return PyFloat_FromDouble(x);
176
1.21M
    }
177
1.21M
}
178
179
PyObject *
180
PyFloat_FromString(PyObject *v)
181
1.21M
{
182
1.21M
    const char *s;
183
1.21M
    PyObject *s_buffer = NULL;
184
1.21M
    Py_ssize_t len;
185
1.21M
    Py_buffer view = {NULL, NULL};
186
1.21M
    PyObject *result = NULL;
187
188
1.21M
    if (PyUnicode_Check(v)) {
189
504k
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
190
504k
        if (s_buffer == NULL)
191
0
            return NULL;
192
504k
        assert(PyUnicode_IS_ASCII(s_buffer));
193
        /* Simply get a pointer to existing ASCII characters. */
194
504k
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
195
504k
        assert(s != NULL);
196
504k
    }
197
713k
    else if (PyBytes_Check(v)) {
198
713k
        s = PyBytes_AS_STRING(v);
199
713k
        len = PyBytes_GET_SIZE(v);
200
713k
    }
201
0
    else if (PyByteArray_Check(v)) {
202
0
        s = PyByteArray_AS_STRING(v);
203
0
        len = PyByteArray_GET_SIZE(v);
204
0
    }
205
0
    else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
206
0
        s = (const char *)view.buf;
207
0
        len = view.len;
208
        /* Copy to NUL-terminated buffer. */
209
0
        s_buffer = PyBytes_FromStringAndSize(s, len);
210
0
        if (s_buffer == NULL) {
211
0
            PyBuffer_Release(&view);
212
0
            return NULL;
213
0
        }
214
0
        s = PyBytes_AS_STRING(s_buffer);
215
0
    }
216
0
    else {
217
0
        PyErr_Format(PyExc_TypeError,
218
0
            "float() argument must be a string or a real number, not '%.200s'",
219
0
            Py_TYPE(v)->tp_name);
220
0
        return NULL;
221
0
    }
222
1.21M
    result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
223
1.21M
                                                   float_from_string_inner);
224
1.21M
    PyBuffer_Release(&view);
225
1.21M
    Py_XDECREF(s_buffer);
226
1.21M
    return result;
227
1.21M
}
228
229
void
230
_PyFloat_ExactDealloc(PyObject *obj)
231
9.40M
{
232
9.40M
    assert(PyFloat_CheckExact(obj));
233
9.40M
    _Py_FREELIST_FREE(floats, obj, PyObject_Free);
234
9.40M
}
235
236
static void
237
float_dealloc(PyObject *op)
238
8.94M
{
239
8.94M
    assert(PyFloat_Check(op));
240
8.94M
    if (PyFloat_CheckExact(op))
241
8.94M
        _PyFloat_ExactDealloc(op);
242
0
    else
243
0
        Py_TYPE(op)->tp_free(op);
244
8.94M
}
245
246
double
247
PyFloat_AsDouble(PyObject *op)
248
674
{
249
674
    PyNumberMethods *nb;
250
674
    PyObject *res;
251
674
    double val;
252
253
674
    if (op == NULL) {
254
0
        PyErr_BadArgument();
255
0
        return -1;
256
0
    }
257
258
674
    if (PyFloat_Check(op)) {
259
670
        return PyFloat_AS_DOUBLE(op);
260
670
    }
261
262
4
    nb = Py_TYPE(op)->tp_as_number;
263
4
    if (nb == NULL || nb->nb_float == NULL) {
264
0
        if (nb && nb->nb_index) {
265
0
            PyObject *res = _PyNumber_Index(op);
266
0
            if (!res) {
267
0
                return -1;
268
0
            }
269
0
            double val = PyLong_AsDouble(res);
270
0
            Py_DECREF(res);
271
0
            return val;
272
0
        }
273
0
        PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
274
0
                     Py_TYPE(op)->tp_name);
275
0
        return -1;
276
0
    }
277
278
4
    res = (*nb->nb_float) (op);
279
4
    if (res == NULL) {
280
0
        return -1;
281
0
    }
282
4
    if (!PyFloat_CheckExact(res)) {
283
0
        if (!PyFloat_Check(res)) {
284
0
            PyErr_Format(PyExc_TypeError,
285
0
                         "%T.__float__() must return a float, not %T",
286
0
                         op, res);
287
0
            Py_DECREF(res);
288
0
            return -1;
289
0
        }
290
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
291
0
                "%T.__float__() must return a float, not %T.  "
292
0
                "The ability to return an instance of a strict subclass of float "
293
0
                "is deprecated, and may be removed in a future version of Python.",
294
0
                op, res)) {
295
0
            Py_DECREF(res);
296
0
            return -1;
297
0
        }
298
0
    }
299
300
4
    val = PyFloat_AS_DOUBLE(res);
301
4
    Py_DECREF(res);
302
4
    return val;
303
4
}
304
305
/* Macro and helper that convert PyObject obj to a C double and store
306
   the value in dbl.  If conversion to double raises an exception, obj is
307
   set to NULL, and the function invoking this macro returns NULL.  If
308
   obj is not of float or int type, Py_NotImplemented is incref'ed,
309
   stored in obj, and returned from the function invoking this macro.
310
*/
311
#define CONVERT_TO_DOUBLE(obj, dbl)                         \
312
161k
    if (PyFloat_Check(obj))                                 \
313
161k
        dbl = PyFloat_AS_DOUBLE(obj);                       \
314
161k
    else if (_Py_convert_int_to_double(&(obj), &(dbl)) < 0) \
315
80.1k
        return obj;
316
317
/* Methods */
318
319
int
320
_Py_convert_int_to_double(PyObject **v, double *dbl)
321
80.1k
{
322
80.1k
    PyObject *obj = *v;
323
324
80.1k
    if (PyLong_Check(obj)) {
325
80.1k
        *dbl = PyLong_AsDouble(obj);
326
80.1k
        if (*dbl == -1.0 && PyErr_Occurred()) {
327
0
            *v = NULL;
328
0
            return -1;
329
0
        }
330
80.1k
    }
331
0
    else {
332
0
        *v = Py_NewRef(Py_NotImplemented);
333
0
        return -1;
334
0
    }
335
80.1k
    return 0;
336
80.1k
}
337
338
static PyObject *
339
float_repr(PyObject *op)
340
53.0k
{
341
53.0k
    PyFloatObject *v = _PyFloat_CAST(op);
342
53.0k
    PyObject *result;
343
53.0k
    char *buf;
344
345
53.0k
    buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
346
53.0k
                                'r', 0,
347
53.0k
                                Py_DTSF_ADD_DOT_0,
348
53.0k
                                NULL);
349
53.0k
    if (!buf)
350
0
        return PyErr_NoMemory();
351
53.0k
    result = _PyUnicode_FromASCII(buf, strlen(buf));
352
53.0k
    PyMem_Free(buf);
353
53.0k
    return result;
354
53.0k
}
355
356
/* Comparison is pretty much a nightmare.  When comparing float to float,
357
 * we do it as straightforwardly (and long-windedly) as conceivable, so
358
 * that, e.g., Python x == y delivers the same result as the platform
359
 * C x == y when x and/or y is a NaN.
360
 * When mixing float with an integer type, there's no good *uniform* approach.
361
 * Converting the double to an integer obviously doesn't work, since we
362
 * may lose info from fractional bits.  Converting the integer to a double
363
 * also has two failure modes:  (1) an int may trigger overflow (too
364
 * large to fit in the dynamic range of a C double); (2) even a C long may have
365
 * more bits than fit in a C double (e.g., on a 64-bit box long may have
366
 * 63 bits of precision, but a C double probably has only 53), and then
367
 * we can falsely claim equality when low-order integer bits are lost by
368
 * coercion to double.  So this part is painful too.
369
 */
370
371
static PyObject*
372
float_richcompare(PyObject *v, PyObject *w, int op)
373
10.8M
{
374
10.8M
    double i, j;
375
10.8M
    int r = 0;
376
377
10.8M
    assert(PyFloat_Check(v));
378
10.8M
    i = PyFloat_AS_DOUBLE(v);
379
380
    /* Switch on the type of w.  Set i and j to doubles to be compared,
381
     * and op to the richcomp to use.
382
     */
383
10.8M
    if (PyFloat_Check(w))
384
4.89M
        j = PyFloat_AS_DOUBLE(w);
385
386
5.91M
    else if (!isfinite(i)) {
387
55.9k
        if (PyLong_Check(w))
388
            /* If i is an infinity, its magnitude exceeds any
389
             * finite integer, so it doesn't matter which int we
390
             * compare i with.  If i is a NaN, similarly.
391
             */
392
55.9k
            j = 0.0;
393
0
        else
394
0
            goto Unimplemented;
395
55.9k
    }
396
397
5.86M
    else if (PyLong_Check(w)) {
398
5.86M
        int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
399
5.86M
        int wsign;
400
5.86M
        int exponent;
401
402
5.86M
        (void)PyLong_GetSign(w, &wsign);
403
5.86M
        if (vsign != wsign) {
404
            /* Magnitudes are irrelevant -- the signs alone
405
             * determine the outcome.
406
             */
407
2.99M
            i = (double)vsign;
408
2.99M
            j = (double)wsign;
409
2.99M
            goto Compare;
410
2.99M
        }
411
        /* The signs are the same. */
412
        /* Convert w to a double if it fits.  In particular, 0 fits. */
413
2.86M
        int64_t nbits64 = _PyLong_NumBits(w);
414
2.86M
        assert(nbits64 >= 0);
415
2.86M
        assert(!PyErr_Occurred());
416
2.86M
        if (nbits64 > DBL_MAX_EXP) {
417
            /* This Python integer is larger than any finite C double.
418
             * Replace with little doubles
419
             * that give the same outcome -- w is so large that
420
             * its magnitude must exceed the magnitude of any
421
             * finite float.
422
             */
423
0
            i = (double)vsign;
424
0
            assert(wsign != 0);
425
0
            j = wsign * 2.0;
426
0
            goto Compare;
427
0
        }
428
2.86M
        int nbits = (int)nbits64;
429
2.86M
        if (nbits <= 48) {
430
2.86M
            j = PyLong_AsDouble(w);
431
            /* It's impossible that <= 48 bits overflowed. */
432
2.86M
            assert(j != -1.0 || ! PyErr_Occurred());
433
2.86M
            goto Compare;
434
2.86M
        }
435
2.86M
        assert(wsign != 0); /* else nbits was 0 */
436
0
        assert(vsign != 0); /* if vsign were 0, then since wsign is
437
                             * not 0, we would have taken the
438
                             * vsign != wsign branch at the start */
439
0
        (void) frexp(i, &exponent);
440
        /* exponent is the # of bits in v before the radix point;
441
         * we know that nbits (the # of bits in w) > 48 at this point
442
         */
443
0
        if (exponent < nbits) {
444
0
            j = i;
445
0
            i = 0.0;
446
0
            goto Compare;
447
0
        }
448
0
        if (exponent > nbits) {
449
0
            j = 0.0;
450
0
            goto Compare;
451
0
        }
452
        /* v and w have the same number of bits before the radix
453
         * point.  Construct an int from the integer part of v and
454
         * update op if necessary, so comparing two ints has the same outcome.
455
         */
456
0
        {
457
0
            double fracpart;
458
0
            double intpart;
459
0
            PyObject *result = NULL;
460
0
            PyObject *vv = NULL;
461
462
0
            fracpart = modf(i, &intpart);
463
0
            if (fracpart != 0.0) {
464
0
                switch (op) {
465
                    /* Non-integer float never equals to an int. */
466
0
                    case Py_EQ:
467
0
                        Py_RETURN_FALSE;
468
0
                    case Py_NE:
469
0
                        Py_RETURN_TRUE;
470
                    /* For non-integer float, v <= w <=> v < w.
471
                     * If v > 0: trunc(v) < v < trunc(v) + 1
472
                     *   v < w => trunc(v) < w
473
                     *   trunc(v) < w => trunc(v) + 1 <= w => v < w
474
                     * If v < 0: trunc(v) - 1 < v < trunc(v)
475
                     *   v < w => trunc(v) - 1 < w => trunc(v) <= w
476
                     *   trunc(v) <= w => v < w
477
                     */
478
0
                    case Py_LT:
479
0
                    case Py_LE:
480
0
                        op = vsign > 0 ? Py_LT : Py_LE;
481
0
                        break;
482
                    /* The same as above, but with opposite directions. */
483
0
                    case Py_GT:
484
0
                    case Py_GE:
485
0
                        op = vsign > 0 ? Py_GE : Py_GT;
486
0
                        break;
487
0
                }
488
0
            }
489
490
0
            vv = PyLong_FromDouble(intpart);
491
0
            if (vv == NULL)
492
0
                goto Error;
493
494
0
            r = PyObject_RichCompareBool(vv, w, op);
495
0
            if (r < 0)
496
0
                goto Error;
497
0
            result = PyBool_FromLong(r);
498
0
         Error:
499
0
            Py_XDECREF(vv);
500
0
            return result;
501
0
        }
502
0
    } /* else if (PyLong_Check(w)) */
503
504
0
    else        /* w isn't float or int */
505
0
        goto Unimplemented;
506
507
10.8M
 Compare:
508
10.8M
    switch (op) {
509
4.95M
    case Py_EQ:
510
4.95M
        r = i == j;
511
4.95M
        break;
512
301k
    case Py_NE:
513
301k
        r = i != j;
514
301k
        break;
515
2.64M
    case Py_LE:
516
2.64M
        r = i <= j;
517
2.64M
        break;
518
2.64M
    case Py_GE:
519
2.64M
        r = i >= j;
520
2.64M
        break;
521
225k
    case Py_LT:
522
225k
        r = i < j;
523
225k
        break;
524
53.8k
    case Py_GT:
525
53.8k
        r = i > j;
526
53.8k
        break;
527
10.8M
    }
528
10.8M
    return PyBool_FromLong(r);
529
530
0
 Unimplemented:
531
0
    Py_RETURN_NOTIMPLEMENTED;
532
10.8M
}
533
534
static Py_hash_t
535
float_hash(PyObject *op)
536
2.68M
{
537
2.68M
    PyFloatObject *v = _PyFloat_CAST(op);
538
2.68M
    return _Py_HashDouble(op, v->ob_fval);
539
2.68M
}
540
541
static PyObject *
542
float_add(PyObject *v, PyObject *w)
543
79.7k
{
544
79.7k
    double a,b;
545
79.7k
    CONVERT_TO_DOUBLE(v, a);
546
79.7k
    CONVERT_TO_DOUBLE(w, b);
547
79.7k
    a = a + b;
548
79.7k
    return PyFloat_FromDouble(a);
549
79.7k
}
550
551
static PyObject *
552
float_sub(PyObject *v, PyObject *w)
553
388
{
554
388
    double a,b;
555
388
    CONVERT_TO_DOUBLE(v, a);
556
388
    CONVERT_TO_DOUBLE(w, b);
557
388
    a = a - b;
558
388
    return PyFloat_FromDouble(a);
559
388
}
560
561
static PyObject *
562
float_mul(PyObject *v, PyObject *w)
563
226
{
564
226
    double a,b;
565
226
    CONVERT_TO_DOUBLE(v, a);
566
226
    CONVERT_TO_DOUBLE(w, b);
567
226
    a = a * b;
568
226
    return PyFloat_FromDouble(a);
569
226
}
570
571
static PyObject *
572
float_div(PyObject *v, PyObject *w)
573
102
{
574
102
    double a,b;
575
102
    CONVERT_TO_DOUBLE(v, a);
576
102
    CONVERT_TO_DOUBLE(w, b);
577
102
    if (b == 0.0) {
578
0
        PyErr_SetString(PyExc_ZeroDivisionError,
579
0
                        "division by zero");
580
0
        return NULL;
581
0
    }
582
102
    a = a / b;
583
102
    return PyFloat_FromDouble(a);
584
102
}
585
586
static PyObject *
587
float_rem(PyObject *v, PyObject *w)
588
0
{
589
0
    double vx, wx;
590
0
    double mod;
591
0
    CONVERT_TO_DOUBLE(v, vx);
592
0
    CONVERT_TO_DOUBLE(w, wx);
593
0
    if (wx == 0.0) {
594
0
        PyErr_SetString(PyExc_ZeroDivisionError,
595
0
                        "division by zero");
596
0
        return NULL;
597
0
    }
598
0
    mod = fmod(vx, wx);
599
0
    if (mod) {
600
        /* ensure the remainder has the same sign as the denominator */
601
0
        if ((wx < 0) != (mod < 0)) {
602
0
            mod += wx;
603
0
        }
604
0
    }
605
0
    else {
606
        /* the remainder is zero, and in the presence of signed zeroes
607
           fmod returns different results across platforms; ensure
608
           it has the same sign as the denominator. */
609
0
        mod = copysign(0.0, wx);
610
0
    }
611
0
    return PyFloat_FromDouble(mod);
612
0
}
613
614
static void
615
_float_div_mod(double vx, double wx, double *floordiv, double *mod)
616
0
{
617
0
    double div;
618
0
    *mod = fmod(vx, wx);
619
    /* fmod is typically exact, so vx-mod is *mathematically* an
620
       exact multiple of wx.  But this is fp arithmetic, and fp
621
       vx - mod is an approximation; the result is that div may
622
       not be an exact integral value after the division, although
623
       it will always be very close to one.
624
    */
625
0
    div = (vx - *mod) / wx;
626
0
    if (*mod) {
627
        /* ensure the remainder has the same sign as the denominator */
628
0
        if ((wx < 0) != (*mod < 0)) {
629
0
            *mod += wx;
630
0
            div -= 1.0;
631
0
        }
632
0
    }
633
0
    else {
634
        /* the remainder is zero, and in the presence of signed zeroes
635
           fmod returns different results across platforms; ensure
636
           it has the same sign as the denominator. */
637
0
        *mod = copysign(0.0, wx);
638
0
    }
639
    /* snap quotient to nearest integral value */
640
0
    if (div) {
641
0
        *floordiv = floor(div);
642
0
        if (div - *floordiv > 0.5) {
643
0
            *floordiv += 1.0;
644
0
        }
645
0
    }
646
0
    else {
647
        /* div is zero - get the same sign as the true quotient */
648
0
        *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
649
0
    }
650
0
}
651
652
static PyObject *
653
float_divmod(PyObject *v, PyObject *w)
654
0
{
655
0
    double vx, wx;
656
0
    double mod, floordiv;
657
0
    CONVERT_TO_DOUBLE(v, vx);
658
0
    CONVERT_TO_DOUBLE(w, wx);
659
0
    if (wx == 0.0) {
660
0
        PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
661
0
        return NULL;
662
0
    }
663
0
    _float_div_mod(vx, wx, &floordiv, &mod);
664
0
    return Py_BuildValue("(dd)", floordiv, mod);
665
0
}
666
667
static PyObject *
668
float_floor_div(PyObject *v, PyObject *w)
669
0
{
670
0
    double vx, wx;
671
0
    double mod, floordiv;
672
0
    CONVERT_TO_DOUBLE(v, vx);
673
0
    CONVERT_TO_DOUBLE(w, wx);
674
0
    if (wx == 0.0) {
675
0
        PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
676
0
        return NULL;
677
0
    }
678
0
    _float_div_mod(vx, wx, &floordiv, &mod);
679
0
    return PyFloat_FromDouble(floordiv);
680
0
}
681
682
/* determine whether x is an odd integer or not;  assumes that
683
   x is not an infinity or nan. */
684
0
#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
685
686
static PyObject *
687
float_pow(PyObject *v, PyObject *w, PyObject *z)
688
76
{
689
76
    double iv, iw, ix;
690
76
    int negate_result = 0;
691
692
76
    if ((PyObject *)z != Py_None) {
693
0
        PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
694
0
            "allowed unless all arguments are integers");
695
0
        return NULL;
696
0
    }
697
698
76
    CONVERT_TO_DOUBLE(v, iv);
699
76
    CONVERT_TO_DOUBLE(w, iw);
700
701
    /* Sort out special cases here instead of relying on pow() */
702
76
    if (iw == 0) {              /* v**0 is 1, even 0**0 */
703
0
        return PyFloat_FromDouble(1.0);
704
0
    }
705
76
    if (isnan(iv)) {        /* nan**w = nan, unless w == 0 */
706
0
        return PyFloat_FromDouble(iv);
707
0
    }
708
76
    if (isnan(iw)) {        /* v**nan = nan, unless v == 1; 1**nan = 1 */
709
0
        return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
710
0
    }
711
76
    if (isinf(iw)) {
712
        /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
713
         *     abs(v) > 1 (including case where v infinite)
714
         *
715
         * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
716
         *     abs(v) > 1 (including case where v infinite)
717
         */
718
0
        iv = fabs(iv);
719
0
        if (iv == 1.0)
720
0
            return PyFloat_FromDouble(1.0);
721
0
        else if ((iw > 0.0) == (iv > 1.0))
722
0
            return PyFloat_FromDouble(fabs(iw)); /* return inf */
723
0
        else
724
0
            return PyFloat_FromDouble(0.0);
725
0
    }
726
76
    if (isinf(iv)) {
727
        /* (+-inf)**w is: inf for w positive, 0 for w negative; in
728
         *     both cases, we need to add the appropriate sign if w is
729
         *     an odd integer.
730
         */
731
0
        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
732
0
        if (iw > 0.0)
733
0
            return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
734
0
        else
735
0
            return PyFloat_FromDouble(iw_is_odd ?
736
0
                                      copysign(0.0, iv) : 0.0);
737
0
    }
738
76
    if (iv == 0.0) {  /* 0**w is: 0 for w positive, 1 for w zero
739
                         (already dealt with above), and an error
740
                         if w is negative. */
741
0
        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
742
0
        if (iw < 0.0) {
743
0
            PyErr_SetString(PyExc_ZeroDivisionError,
744
0
                            "zero to a negative power");
745
0
            return NULL;
746
0
        }
747
        /* use correct sign if iw is odd */
748
0
        return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
749
0
    }
750
751
76
    if (iv < 0.0) {
752
        /* Whether this is an error is a mess, and bumps into libm
753
         * bugs so we have to figure it out ourselves.
754
         */
755
0
        if (iw != floor(iw)) {
756
            /* Negative numbers raised to fractional powers
757
             * become complex.
758
             */
759
0
            return PyComplex_Type.tp_as_number->nb_power(v, w, z);
760
0
        }
761
        /* iw is an exact integer, albeit perhaps a very large
762
         * one.  Replace iv by its absolute value and remember
763
         * to negate the pow result if iw is odd.
764
         */
765
0
        iv = -iv;
766
0
        negate_result = DOUBLE_IS_ODD_INTEGER(iw);
767
0
    }
768
769
76
    if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
770
        /* (-1) ** large_integer also ends up here.  Here's an
771
         * extract from the comments for the previous
772
         * implementation explaining why this special case is
773
         * necessary:
774
         *
775
         * -1 raised to an exact integer should never be exceptional.
776
         * Alas, some libms (chiefly glibc as of early 2003) return
777
         * NaN and set EDOM on pow(-1, large_int) if the int doesn't
778
         * happen to be representable in a *C* integer.  That's a
779
         * bug.
780
         */
781
0
        return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
782
0
    }
783
784
    /* Now iv and iw are finite, iw is nonzero, and iv is
785
     * positive and not equal to 1.0.  We finally allow
786
     * the platform pow to step in and do the rest.
787
     */
788
76
    errno = 0;
789
76
    ix = pow(iv, iw);
790
76
    _Py_ADJUST_ERANGE1(ix);
791
76
    if (negate_result)
792
0
        ix = -ix;
793
794
76
    if (errno != 0) {
795
        /* We don't expect any errno value other than ERANGE, but
796
         * the range of libm bugs appears unbounded.
797
         */
798
0
        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
799
0
                             PyExc_ValueError);
800
0
        return NULL;
801
0
    }
802
76
    return PyFloat_FromDouble(ix);
803
76
}
804
805
#undef DOUBLE_IS_ODD_INTEGER
806
807
static PyObject *
808
float_neg(PyObject *op)
809
3.94k
{
810
3.94k
    PyFloatObject *v = _PyFloat_CAST(op);
811
3.94k
    return PyFloat_FromDouble(-v->ob_fval);
812
3.94k
}
813
814
static PyObject *
815
float_abs(PyObject *op)
816
0
{
817
0
    PyFloatObject *v = _PyFloat_CAST(op);
818
0
    return PyFloat_FromDouble(fabs(v->ob_fval));
819
0
}
820
821
static int
822
float_bool(PyObject *op)
823
4
{
824
4
    PyFloatObject *v = _PyFloat_CAST(op);
825
4
    return v->ob_fval != 0.0;
826
4
}
827
828
/*[clinic input]
829
float.is_integer
830
831
Return True if the float is an integer.
832
[clinic start generated code]*/
833
834
static PyObject *
835
float_is_integer_impl(PyObject *self)
836
/*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/
837
0
{
838
0
    double x = PyFloat_AsDouble(self);
839
0
    PyObject *o;
840
841
0
    if (x == -1.0 && PyErr_Occurred())
842
0
        return NULL;
843
0
    if (!isfinite(x))
844
0
        Py_RETURN_FALSE;
845
0
    errno = 0;
846
0
    o = (floor(x) == x) ? Py_True : Py_False;
847
0
    if (errno != 0) {
848
0
        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
849
0
                             PyExc_ValueError);
850
0
        return NULL;
851
0
    }
852
0
    return Py_NewRef(o);
853
0
}
854
855
/*[clinic input]
856
float.__trunc__
857
858
Return the Integral closest to x between 0 and x.
859
[clinic start generated code]*/
860
861
static PyObject *
862
float___trunc___impl(PyObject *self)
863
/*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/
864
14.2k
{
865
14.2k
    return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
866
14.2k
}
867
868
/*[clinic input]
869
float.__floor__
870
871
Return the floor as an Integral.
872
[clinic start generated code]*/
873
874
static PyObject *
875
float___floor___impl(PyObject *self)
876
/*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/
877
0
{
878
0
    double x = PyFloat_AS_DOUBLE(self);
879
0
    return PyLong_FromDouble(floor(x));
880
0
}
881
882
/*[clinic input]
883
float.__ceil__
884
885
Return the ceiling as an Integral.
886
[clinic start generated code]*/
887
888
static PyObject *
889
float___ceil___impl(PyObject *self)
890
/*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/
891
0
{
892
0
    double x = PyFloat_AS_DOUBLE(self);
893
0
    return PyLong_FromDouble(ceil(x));
894
0
}
895
896
/* double_round: rounds a finite double to the closest multiple of
897
   10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
898
   ndigits <= 323).  Returns a Python float, or sets a Python error and
899
   returns NULL on failure (OverflowError and memory errors are possible). */
900
901
#if _PY_SHORT_FLOAT_REPR == 1
902
/* version of double_round that uses the correctly-rounded string<->double
903
   conversions from Python/dtoa.c */
904
905
static PyObject *
906
0
double_round(double x, int ndigits) {
907
908
0
    double rounded;
909
0
    Py_ssize_t buflen, mybuflen=100;
910
0
    char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
911
0
    int decpt, sign;
912
0
    PyObject *result = NULL;
913
0
    _Py_SET_53BIT_PRECISION_HEADER;
914
915
    /* round to a decimal string */
916
0
    _Py_SET_53BIT_PRECISION_START;
917
0
    buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
918
0
    _Py_SET_53BIT_PRECISION_END;
919
0
    if (buf == NULL) {
920
0
        PyErr_NoMemory();
921
0
        return NULL;
922
0
    }
923
924
    /* Get new buffer if shortbuf is too small.  Space needed <= buf_end -
925
    buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0').  */
926
0
    buflen = buf_end - buf;
927
0
    if (buflen + 8 > mybuflen) {
928
0
        mybuflen = buflen+8;
929
0
        mybuf = (char *)PyMem_Malloc(mybuflen);
930
0
        if (mybuf == NULL) {
931
0
            PyErr_NoMemory();
932
0
            goto exit;
933
0
        }
934
0
    }
935
    /* copy buf to mybuf, adding exponent, sign and leading 0 */
936
0
    PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
937
0
                  buf, decpt - (int)buflen);
938
939
    /* and convert the resulting string back to a double */
940
0
    errno = 0;
941
0
    _Py_SET_53BIT_PRECISION_START;
942
0
    rounded = _Py_dg_strtod(mybuf, NULL);
943
0
    _Py_SET_53BIT_PRECISION_END;
944
0
    if (errno == ERANGE && fabs(rounded) >= 1.)
945
0
        PyErr_SetString(PyExc_OverflowError,
946
0
                        "rounded value too large to represent");
947
0
    else
948
0
        result = PyFloat_FromDouble(rounded);
949
950
    /* done computing value;  now clean up */
951
0
    if (mybuf != shortbuf)
952
0
        PyMem_Free(mybuf);
953
0
  exit:
954
0
    _Py_dg_freedtoa(buf);
955
0
    return result;
956
0
}
957
958
#else  // _PY_SHORT_FLOAT_REPR == 0
959
960
/* fallback version, to be used when correctly rounded binary<->decimal
961
   conversions aren't available */
962
963
static PyObject *
964
double_round(double x, int ndigits) {
965
    double pow1, pow2, y, z;
966
    if (ndigits >= 0) {
967
        if (ndigits > 22) {
968
            /* pow1 and pow2 are each safe from overflow, but
969
               pow1*pow2 ~= pow(10.0, ndigits) might overflow */
970
            pow1 = pow(10.0, (double)(ndigits-22));
971
            pow2 = 1e22;
972
        }
973
        else {
974
            pow1 = pow(10.0, (double)ndigits);
975
            pow2 = 1.0;
976
        }
977
        y = (x*pow1)*pow2;
978
        /* if y overflows, then rounded value is exactly x */
979
        if (!isfinite(y))
980
            return PyFloat_FromDouble(x);
981
    }
982
    else {
983
        pow1 = pow(10.0, (double)-ndigits);
984
        pow2 = 1.0; /* unused; silences a gcc compiler warning */
985
        y = x / pow1;
986
    }
987
988
    z = round(y);
989
    if (fabs(y-z) == 0.5)
990
        /* halfway between two integers; use round-half-even */
991
        z = 2.0*round(y/2.0);
992
993
    if (ndigits >= 0)
994
        z = (z / pow2) / pow1;
995
    else
996
        z *= pow1;
997
998
    /* if computation resulted in overflow, raise OverflowError */
999
    if (!isfinite(z)) {
1000
        PyErr_SetString(PyExc_OverflowError,
1001
                        "overflow occurred during round");
1002
        return NULL;
1003
    }
1004
1005
    return PyFloat_FromDouble(z);
1006
}
1007
1008
#endif  // _PY_SHORT_FLOAT_REPR == 0
1009
1010
/* round a Python float v to the closest multiple of 10**-ndigits */
1011
1012
/*[clinic input]
1013
float.__round__
1014
1015
    ndigits as o_ndigits: object = None
1016
    /
1017
1018
Return the Integral closest to x, rounding half toward even.
1019
1020
When an argument is passed, work like built-in round(x, ndigits).
1021
[clinic start generated code]*/
1022
1023
static PyObject *
1024
float___round___impl(PyObject *self, PyObject *o_ndigits)
1025
/*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/
1026
0
{
1027
0
    double x, rounded;
1028
0
    Py_ssize_t ndigits;
1029
1030
0
    x = PyFloat_AsDouble(self);
1031
0
    if (o_ndigits == Py_None) {
1032
        /* single-argument round or with None ndigits:
1033
         * round to nearest integer */
1034
0
        rounded = round(x);
1035
0
        if (fabs(x-rounded) == 0.5)
1036
            /* halfway case: round to even */
1037
0
            rounded = 2.0*round(x/2.0);
1038
0
        return PyLong_FromDouble(rounded);
1039
0
    }
1040
1041
    /* interpret second argument as a Py_ssize_t; clips on overflow */
1042
0
    ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1043
0
    if (ndigits == -1 && PyErr_Occurred())
1044
0
        return NULL;
1045
1046
    /* nans and infinities round to themselves */
1047
0
    if (!isfinite(x))
1048
0
        return PyFloat_FromDouble(x);
1049
1050
    /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1051
       always rounds to itself.  For ndigits < NDIGITS_MIN, x always
1052
       rounds to +-0.0.  Here 0.30103 is an upper bound for log10(2). */
1053
0
#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1054
0
#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
1055
0
    if (ndigits > NDIGITS_MAX)
1056
        /* return x */
1057
0
        return PyFloat_FromDouble(x);
1058
0
    else if (ndigits < NDIGITS_MIN)
1059
        /* return 0.0, but with sign of x */
1060
0
        return PyFloat_FromDouble(0.0*x);
1061
0
    else
1062
        /* finite x, and ndigits is not unreasonably large */
1063
0
        return double_round(x, (int)ndigits);
1064
0
#undef NDIGITS_MAX
1065
0
#undef NDIGITS_MIN
1066
0
}
1067
1068
static PyObject *
1069
float_float(PyObject *v)
1070
0
{
1071
0
    if (PyFloat_CheckExact(v)) {
1072
0
        return Py_NewRef(v);
1073
0
    }
1074
0
    else {
1075
0
        return PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1076
0
    }
1077
0
}
1078
1079
/*[clinic input]
1080
float.conjugate
1081
1082
Return self, the complex conjugate of any float.
1083
[clinic start generated code]*/
1084
1085
static PyObject *
1086
float_conjugate_impl(PyObject *self)
1087
/*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/
1088
0
{
1089
0
    return float_float(self);
1090
0
}
1091
1092
/* turn ASCII hex characters into integer values and vice versa */
1093
1094
static char
1095
char_from_hex(int x)
1096
0
{
1097
0
    assert(0 <= x && x < 16);
1098
0
    return Py_hexdigits[x];
1099
0
}
1100
1101
/* This table maps characters to their hexadecimal values, only
1102
 * works with encodings whose lower half is ASCII (like UTF-8).
1103
 * '0' maps to 0, ..., '9' maps to 9.
1104
 * 'a' and 'A' map to 10, ..., 'f' and 'F' map to 15.
1105
 * All other indices map to -1.
1106
 */
1107
static const int
1108
_CHAR_TO_HEX[256] = {
1109
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1110
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1111
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1112
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  -1, -1, -1, -1, -1, -1,
1113
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1114
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1115
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1116
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1117
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1118
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1119
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1120
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1121
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1122
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1123
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1124
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1125
};
1126
1127
/* Convert a character to its hexadecimal value, or -1 if it's not a
1128
 * valid hexadecimal character, only works with encodings whose lower
1129
 * half is ASCII (like UTF-8).
1130
 */
1131
static int
1132
0
hex_from_char(unsigned char c) {
1133
0
    return _CHAR_TO_HEX[c];
1134
0
}
1135
1136
/* convert a float to a hexadecimal string */
1137
1138
/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1139
   of the form 4k+1. */
1140
0
#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1141
1142
/*[clinic input]
1143
float.hex
1144
1145
Return a hexadecimal representation of a floating-point number.
1146
1147
>>> (-0.1).hex()
1148
'-0x1.999999999999ap-4'
1149
>>> 3.14159.hex()
1150
'0x1.921f9f01b866ep+1'
1151
[clinic start generated code]*/
1152
1153
static PyObject *
1154
float_hex_impl(PyObject *self)
1155
/*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/
1156
0
{
1157
0
    double x, m;
1158
0
    int e, shift, i, si, esign;
1159
    /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1160
       trailing NUL byte. */
1161
0
    char s[(TOHEX_NBITS-1)/4+3];
1162
1163
0
    CONVERT_TO_DOUBLE(self, x);
1164
1165
0
    if (isnan(x) || isinf(x))
1166
0
        return float_repr(self);
1167
1168
0
    if (x == 0.0) {
1169
0
        if (copysign(1.0, x) == -1.0)
1170
0
            return PyUnicode_FromString("-0x0.0p+0");
1171
0
        else
1172
0
            return PyUnicode_FromString("0x0.0p+0");
1173
0
    }
1174
1175
0
    m = frexp(fabs(x), &e);
1176
0
    shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
1177
0
    m = ldexp(m, shift);
1178
0
    e -= shift;
1179
1180
0
    si = 0;
1181
0
    s[si] = char_from_hex((int)m);
1182
0
    si++;
1183
0
    m -= (int)m;
1184
0
    s[si] = '.';
1185
0
    si++;
1186
0
    for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1187
0
        m *= 16.0;
1188
0
        s[si] = char_from_hex((int)m);
1189
0
        si++;
1190
0
        m -= (int)m;
1191
0
    }
1192
0
    s[si] = '\0';
1193
1194
0
    if (e < 0) {
1195
0
        esign = (int)'-';
1196
0
        e = -e;
1197
0
    }
1198
0
    else
1199
0
        esign = (int)'+';
1200
1201
0
    if (x < 0.0)
1202
0
        return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1203
0
    else
1204
0
        return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1205
0
}
1206
1207
/* Convert a hexadecimal string to a float. */
1208
1209
/*[clinic input]
1210
@classmethod
1211
float.fromhex
1212
1213
    string: object
1214
    /
1215
1216
Create a floating-point number from a hexadecimal string.
1217
1218
>>> float.fromhex('0x1.ffffp10')
1219
2047.984375
1220
>>> float.fromhex('-0x1p-1074')
1221
-5e-324
1222
[clinic start generated code]*/
1223
1224
static PyObject *
1225
float_fromhex_impl(PyTypeObject *type, PyObject *string)
1226
/*[clinic end generated code: output=c54b4923552e5af5 input=0407bebd354bca89]*/
1227
0
{
1228
0
    PyObject *result;
1229
0
    double x;
1230
0
    long exp, top_exp, lsb, key_digit;
1231
0
    const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1232
0
    int half_eps, digit, round_up, negate=0;
1233
0
    Py_ssize_t length, ndigits, fdigits, i;
1234
1235
    /*
1236
     * For the sake of simplicity and correctness, we impose an artificial
1237
     * limit on ndigits, the total number of hex digits in the coefficient
1238
     * The limit is chosen to ensure that, writing exp for the exponent,
1239
     *
1240
     *   (1) if exp > LONG_MAX/2 then the value of the hex string is
1241
     *   guaranteed to overflow (provided it's nonzero)
1242
     *
1243
     *   (2) if exp < LONG_MIN/2 then the value of the hex string is
1244
     *   guaranteed to underflow to 0.
1245
     *
1246
     *   (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1247
     *   overflow in the calculation of exp and top_exp below.
1248
     *
1249
     * More specifically, ndigits is assumed to satisfy the following
1250
     * inequalities:
1251
     *
1252
     *   4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1253
     *   4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1254
     *
1255
     * If either of these inequalities is not satisfied, a ValueError is
1256
     * raised.  Otherwise, write x for the value of the hex string, and
1257
     * assume x is nonzero.  Then
1258
     *
1259
     *   2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1260
     *
1261
     * Now if exp > LONG_MAX/2 then:
1262
     *
1263
     *   exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1264
     *                    = DBL_MAX_EXP
1265
     *
1266
     * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1267
     * double, so overflows.  If exp < LONG_MIN/2, then
1268
     *
1269
     *   exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1270
     *                      DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1271
     *                    = DBL_MIN_EXP - DBL_MANT_DIG - 1
1272
     *
1273
     * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1274
     * when converted to a C double.
1275
     *
1276
     * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1277
     * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1278
     */
1279
1280
0
    s = PyUnicode_AsUTF8AndSize(string, &length);
1281
0
    if (s == NULL)
1282
0
        return NULL;
1283
0
    s_end = s + length;
1284
1285
    /********************
1286
     * Parse the string *
1287
     ********************/
1288
1289
    /* leading whitespace */
1290
0
    while (Py_ISSPACE(*s))
1291
0
        s++;
1292
1293
    /* infinities and nans */
1294
0
    x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
1295
0
    if (coeff_end != s) {
1296
0
        s = coeff_end;
1297
0
        goto finished;
1298
0
    }
1299
1300
    /* optional sign */
1301
0
    if (*s == '-') {
1302
0
        s++;
1303
0
        negate = 1;
1304
0
    }
1305
0
    else if (*s == '+')
1306
0
        s++;
1307
1308
    /* [0x] */
1309
0
    s_store = s;
1310
0
    if (*s == '0') {
1311
0
        s++;
1312
0
        if (*s == 'x' || *s == 'X')
1313
0
            s++;
1314
0
        else
1315
0
            s = s_store;
1316
0
    }
1317
1318
    /* coefficient: <integer> [. <fraction>] */
1319
0
    coeff_start = s;
1320
0
    while (hex_from_char(*s) >= 0)
1321
0
        s++;
1322
0
    s_store = s;
1323
0
    if (*s == '.') {
1324
0
        s++;
1325
0
        while (hex_from_char(*s) >= 0)
1326
0
            s++;
1327
0
        coeff_end = s-1;
1328
0
    }
1329
0
    else
1330
0
        coeff_end = s;
1331
1332
    /* ndigits = total # of hex digits; fdigits = # after point */
1333
0
    ndigits = coeff_end - coeff_start;
1334
0
    fdigits = coeff_end - s_store;
1335
0
    if (ndigits == 0)
1336
0
        goto parse_error;
1337
0
    if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1338
0
                         LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1339
0
        goto insane_length_error;
1340
1341
    /* [p <exponent>] */
1342
0
    if (*s == 'p' || *s == 'P') {
1343
0
        s++;
1344
0
        exp_start = s;
1345
0
        if (*s == '-' || *s == '+')
1346
0
            s++;
1347
0
        if (!('0' <= *s && *s <= '9'))
1348
0
            goto parse_error;
1349
0
        s++;
1350
0
        while ('0' <= *s && *s <= '9')
1351
0
            s++;
1352
0
        exp = strtol(exp_start, NULL, 10);
1353
0
    }
1354
0
    else
1355
0
        exp = 0;
1356
1357
/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1358
0
#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ?            \
1359
0
                     coeff_end-(j) :                                    \
1360
0
                     coeff_end-1-(j)))
1361
1362
    /*******************************************
1363
     * Compute rounded value of the hex string *
1364
     *******************************************/
1365
1366
    /* Discard leading zeros, and catch extreme overflow and underflow */
1367
0
    while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1368
0
        ndigits--;
1369
0
    if (ndigits == 0 || exp < LONG_MIN/2) {
1370
0
        x = 0.0;
1371
0
        goto finished;
1372
0
    }
1373
0
    if (exp > LONG_MAX/2)
1374
0
        goto overflow_error;
1375
1376
    /* Adjust exponent for fractional part. */
1377
0
    exp = exp - 4*((long)fdigits);
1378
1379
    /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1380
0
    top_exp = exp + 4*((long)ndigits - 1);
1381
0
    for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1382
0
        top_exp++;
1383
1384
    /* catch almost all nonextreme cases of overflow and underflow here */
1385
0
    if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1386
0
        x = 0.0;
1387
0
        goto finished;
1388
0
    }
1389
0
    if (top_exp > DBL_MAX_EXP)
1390
0
        goto overflow_error;
1391
1392
    /* lsb = exponent of least significant bit of the *rounded* value.
1393
       This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1394
0
    lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1395
1396
0
    x = 0.0;
1397
0
    if (exp >= lsb) {
1398
        /* no rounding required */
1399
0
        for (i = ndigits-1; i >= 0; i--)
1400
0
            x = 16.0*x + HEX_DIGIT(i);
1401
0
        x = ldexp(x, (int)(exp));
1402
0
        goto finished;
1403
0
    }
1404
    /* rounding required.  key_digit is the index of the hex digit
1405
       containing the first bit to be rounded away. */
1406
0
    half_eps = 1 << (int)((lsb - exp - 1) % 4);
1407
0
    key_digit = (lsb - exp - 1) / 4;
1408
0
    for (i = ndigits-1; i > key_digit; i--)
1409
0
        x = 16.0*x + HEX_DIGIT(i);
1410
0
    digit = HEX_DIGIT(key_digit);
1411
0
    x = 16.0*x + (double)(digit & (16-2*half_eps));
1412
1413
    /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1414
       bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1415
0
    if ((digit & half_eps) != 0) {
1416
0
        round_up = 0;
1417
0
        if ((digit & (3*half_eps-1)) != 0 || (half_eps == 8 &&
1418
0
                key_digit+1 < ndigits && (HEX_DIGIT(key_digit+1) & 1) != 0))
1419
0
            round_up = 1;
1420
0
        else
1421
0
            for (i = key_digit-1; i >= 0; i--)
1422
0
                if (HEX_DIGIT(i) != 0) {
1423
0
                    round_up = 1;
1424
0
                    break;
1425
0
                }
1426
0
        if (round_up) {
1427
0
            x += 2*half_eps;
1428
0
            if (top_exp == DBL_MAX_EXP &&
1429
0
                x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1430
                /* overflow corner case: pre-rounded value <
1431
                   2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1432
0
                goto overflow_error;
1433
0
        }
1434
0
    }
1435
0
    x = ldexp(x, (int)(exp+4*key_digit));
1436
1437
0
  finished:
1438
    /* optional trailing whitespace leading to the end of the string */
1439
0
    while (Py_ISSPACE(*s))
1440
0
        s++;
1441
0
    if (s != s_end)
1442
0
        goto parse_error;
1443
0
    result = PyFloat_FromDouble(negate ? -x : x);
1444
0
    if (type != &PyFloat_Type && result != NULL) {
1445
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
1446
0
    }
1447
0
    return result;
1448
1449
0
  overflow_error:
1450
0
    PyErr_SetString(PyExc_OverflowError,
1451
0
                    "hexadecimal value too large to represent as a float");
1452
0
    return NULL;
1453
1454
0
  parse_error:
1455
0
    PyErr_SetString(PyExc_ValueError,
1456
0
                    "invalid hexadecimal floating-point string");
1457
0
    return NULL;
1458
1459
0
  insane_length_error:
1460
0
    PyErr_SetString(PyExc_ValueError,
1461
0
                    "hexadecimal string too long to convert");
1462
0
    return NULL;
1463
0
}
1464
1465
/*[clinic input]
1466
@permit_long_summary
1467
float.as_integer_ratio
1468
1469
Return a pair of integers, whose ratio is exactly equal to the original float.
1470
1471
The ratio is in lowest terms and has a positive denominator.  Raise
1472
OverflowError on infinities and a ValueError on NaNs.
1473
1474
>>> (10.0).as_integer_ratio()
1475
(10, 1)
1476
>>> (0.0).as_integer_ratio()
1477
(0, 1)
1478
>>> (-.25).as_integer_ratio()
1479
(-1, 4)
1480
[clinic start generated code]*/
1481
1482
static PyObject *
1483
float_as_integer_ratio_impl(PyObject *self)
1484
/*[clinic end generated code: output=65f25f0d8d30a712 input=75ae9be7cecd82a3]*/
1485
0
{
1486
0
    double self_double;
1487
0
    double float_part;
1488
0
    int exponent;
1489
0
    int i;
1490
1491
0
    PyObject *py_exponent = NULL;
1492
0
    PyObject *numerator = NULL;
1493
0
    PyObject *denominator = NULL;
1494
0
    PyObject *result_pair = NULL;
1495
0
    PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
1496
1497
0
    CONVERT_TO_DOUBLE(self, self_double);
1498
1499
0
    if (isinf(self_double)) {
1500
0
        PyErr_SetString(PyExc_OverflowError,
1501
0
                        "cannot convert Infinity to integer ratio");
1502
0
        return NULL;
1503
0
    }
1504
0
    if (isnan(self_double)) {
1505
0
        PyErr_SetString(PyExc_ValueError,
1506
0
                        "cannot convert NaN to integer ratio");
1507
0
        return NULL;
1508
0
    }
1509
1510
0
    float_part = frexp(self_double, &exponent);        /* self_double == float_part * 2**exponent exactly */
1511
1512
0
    for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1513
0
        float_part *= 2.0;
1514
0
        exponent--;
1515
0
    }
1516
    /* self == float_part * 2**exponent exactly and float_part is integral.
1517
       If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1518
       to be truncated by PyLong_FromDouble(). */
1519
1520
0
    numerator = PyLong_FromDouble(float_part);
1521
0
    if (numerator == NULL)
1522
0
        goto error;
1523
0
    denominator = PyLong_FromLong(1);
1524
0
    if (denominator == NULL)
1525
0
        goto error;
1526
0
    py_exponent = PyLong_FromLong(Py_ABS(exponent));
1527
0
    if (py_exponent == NULL)
1528
0
        goto error;
1529
1530
    /* fold in 2**exponent */
1531
0
    if (exponent > 0) {
1532
0
        Py_SETREF(numerator,
1533
0
                  long_methods->nb_lshift(numerator, py_exponent));
1534
0
        if (numerator == NULL)
1535
0
            goto error;
1536
0
    }
1537
0
    else {
1538
0
        Py_SETREF(denominator,
1539
0
                  long_methods->nb_lshift(denominator, py_exponent));
1540
0
        if (denominator == NULL)
1541
0
            goto error;
1542
0
    }
1543
0
    Py_DECREF(py_exponent);
1544
1545
0
    return _PyTuple_FromPairSteal(numerator, denominator);
1546
1547
0
error:
1548
0
    Py_XDECREF(py_exponent);
1549
0
    Py_XDECREF(denominator);
1550
0
    Py_XDECREF(numerator);
1551
0
    return result_pair;
1552
0
}
1553
1554
static PyObject *
1555
float_subtype_new(PyTypeObject *type, PyObject *x);
1556
1557
/*[clinic input]
1558
@classmethod
1559
float.__new__ as float_new
1560
    x: object(c_default="NULL") = 0
1561
    /
1562
1563
Convert a string or number to a floating-point number, if possible.
1564
[clinic start generated code]*/
1565
1566
static PyObject *
1567
float_new_impl(PyTypeObject *type, PyObject *x)
1568
/*[clinic end generated code: output=ccf1e8dc460ba6ba input=55909f888aa0c8a6]*/
1569
504k
{
1570
504k
    if (type != &PyFloat_Type) {
1571
0
        if (x == NULL) {
1572
0
            x = _PyLong_GetZero();
1573
0
        }
1574
0
        return float_subtype_new(type, x); /* Wimp out */
1575
0
    }
1576
1577
504k
    if (x == NULL) {
1578
0
        return PyFloat_FromDouble(0.0);
1579
0
    }
1580
    /* If it's a string, but not a string subclass, use
1581
       PyFloat_FromString. */
1582
504k
    if (PyUnicode_CheckExact(x))
1583
504k
        return PyFloat_FromString(x);
1584
8
    return PyNumber_Float(x);
1585
504k
}
1586
1587
/* Wimpy, slow approach to tp_new calls for subtypes of float:
1588
   first create a regular float from whatever arguments we got,
1589
   then allocate a subtype instance and initialize its ob_fval
1590
   from the regular float.  The regular float is then thrown away.
1591
*/
1592
static PyObject *
1593
float_subtype_new(PyTypeObject *type, PyObject *x)
1594
0
{
1595
0
    PyObject *tmp, *newobj;
1596
1597
0
    assert(PyType_IsSubtype(type, &PyFloat_Type));
1598
0
    tmp = float_new_impl(&PyFloat_Type, x);
1599
0
    if (tmp == NULL)
1600
0
        return NULL;
1601
0
    assert(PyFloat_Check(tmp));
1602
0
    newobj = type->tp_alloc(type, 0);
1603
0
    if (newobj == NULL) {
1604
0
        Py_DECREF(tmp);
1605
0
        return NULL;
1606
0
    }
1607
0
    ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1608
0
    Py_DECREF(tmp);
1609
0
    return newobj;
1610
0
}
1611
1612
static PyObject *
1613
float_vectorcall(PyObject *type, PyObject *const *args,
1614
                 size_t nargsf, PyObject *kwnames)
1615
504k
{
1616
504k
    if (!_PyArg_NoKwnames("float", kwnames)) {
1617
0
        return NULL;
1618
0
    }
1619
1620
504k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1621
504k
    if (!_PyArg_CheckPositional("float", nargs, 0, 1)) {
1622
0
        return NULL;
1623
0
    }
1624
1625
504k
    PyObject *x = nargs >= 1 ? args[0] : NULL;
1626
504k
    return float_new_impl(_PyType_CAST(type), x);
1627
504k
}
1628
1629
1630
/*[clinic input]
1631
@classmethod
1632
float.from_number
1633
1634
    number: object
1635
    /
1636
1637
Convert real number to a floating-point number.
1638
[clinic start generated code]*/
1639
1640
static PyObject *
1641
float_from_number_impl(PyTypeObject *type, PyObject *number)
1642
/*[clinic end generated code: output=dda7e4466ab7068d input=1f8424d9bc11866a]*/
1643
0
{
1644
0
    if (PyFloat_CheckExact(number) && type == &PyFloat_Type) {
1645
0
        Py_INCREF(number);
1646
0
        return number;
1647
0
    }
1648
0
    double x = PyFloat_AsDouble(number);
1649
0
    if (x == -1.0 && PyErr_Occurred()) {
1650
0
        return NULL;
1651
0
    }
1652
0
    PyObject *result = PyFloat_FromDouble(x);
1653
0
    if (type != &PyFloat_Type && result != NULL) {
1654
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
1655
0
    }
1656
0
    return result;
1657
0
}
1658
1659
1660
/*[clinic input]
1661
float.__getnewargs__
1662
[clinic start generated code]*/
1663
1664
static PyObject *
1665
float___getnewargs___impl(PyObject *self)
1666
/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
1667
0
{
1668
0
    return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
1669
0
}
1670
1671
1672
/*[clinic input]
1673
@permit_long_docstring_body
1674
@classmethod
1675
float.__getformat__
1676
1677
    typestr: str
1678
        Must be 'double' or 'float'.
1679
    /
1680
1681
You probably don't want to use this function.
1682
1683
It exists mainly to be used in Python's test suite.
1684
1685
This function returns whichever of 'IEEE, big-endian' or 'IEEE,
1686
little-endian' best describes the format of floating-point numbers used by the
1687
C type named by typestr.
1688
[clinic start generated code]*/
1689
1690
static PyObject *
1691
float___getformat___impl(PyTypeObject *type, const char *typestr)
1692
/*[clinic end generated code: output=2bfb987228cc9628 input=0ae1ba35d192f704]*/
1693
0
{
1694
0
    if (strcmp(typestr, "double") != 0 && strcmp(typestr, "float") != 0) {
1695
0
        PyErr_SetString(PyExc_ValueError,
1696
0
                        "__getformat__() argument 1 must be "
1697
0
                        "'double' or 'float'");
1698
0
        return NULL;
1699
0
    }
1700
0
    return PyUnicode_FromString(_PY_FLOAT_LITTLE_ENDIAN ?
1701
0
                                "IEEE, little-endian" : "IEEE, big-endian");
1702
0
}
1703
1704
static PyObject *
1705
float_getreal(PyObject *v, void *Py_UNUSED(closure))
1706
0
{
1707
0
    return float_float(v);
1708
0
}
1709
1710
static PyObject *
1711
float_getimag(PyObject *Py_UNUSED(v), void *Py_UNUSED(closure))
1712
0
{
1713
0
    return PyFloat_FromDouble(0.0);
1714
0
}
1715
1716
/*[clinic input]
1717
float.__format__
1718
1719
  format_spec: unicode
1720
  /
1721
1722
Formats the float according to format_spec.
1723
[clinic start generated code]*/
1724
1725
static PyObject *
1726
float___format___impl(PyObject *self, PyObject *format_spec)
1727
/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
1728
0
{
1729
0
    _PyUnicodeWriter writer;
1730
0
    int ret;
1731
1732
0
    _PyUnicodeWriter_Init(&writer);
1733
0
    ret = _PyFloat_FormatAdvancedWriter(
1734
0
        &writer,
1735
0
        self,
1736
0
        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1737
0
    if (ret == -1) {
1738
0
        _PyUnicodeWriter_Dealloc(&writer);
1739
0
        return NULL;
1740
0
    }
1741
0
    return _PyUnicodeWriter_Finish(&writer);
1742
0
}
1743
1744
static PyMethodDef float_methods[] = {
1745
    FLOAT_FROM_NUMBER_METHODDEF
1746
    FLOAT_CONJUGATE_METHODDEF
1747
    FLOAT___TRUNC___METHODDEF
1748
    FLOAT___FLOOR___METHODDEF
1749
    FLOAT___CEIL___METHODDEF
1750
    FLOAT___ROUND___METHODDEF
1751
    FLOAT_AS_INTEGER_RATIO_METHODDEF
1752
    FLOAT_FROMHEX_METHODDEF
1753
    FLOAT_HEX_METHODDEF
1754
    FLOAT_IS_INTEGER_METHODDEF
1755
    FLOAT___GETNEWARGS___METHODDEF
1756
    FLOAT___GETFORMAT___METHODDEF
1757
    FLOAT___FORMAT___METHODDEF
1758
    {NULL,              NULL}           /* sentinel */
1759
};
1760
1761
static PyGetSetDef float_getset[] = {
1762
    {"real",
1763
     float_getreal, NULL,
1764
     "the real part of a complex number",
1765
     NULL},
1766
    {"imag",
1767
     float_getimag, NULL,
1768
     "the imaginary part of a complex number",
1769
     NULL},
1770
    {NULL}  /* Sentinel */
1771
};
1772
1773
1774
static PyNumberMethods float_as_number = {
1775
    float_add,          /* nb_add */
1776
    float_sub,          /* nb_subtract */
1777
    float_mul,          /* nb_multiply */
1778
    float_rem,          /* nb_remainder */
1779
    float_divmod,       /* nb_divmod */
1780
    float_pow,          /* nb_power */
1781
    float_neg,          /* nb_negative */
1782
    float_float,        /* nb_positive */
1783
    float_abs,          /* nb_absolute */
1784
    float_bool,         /* nb_bool */
1785
    0,                  /* nb_invert */
1786
    0,                  /* nb_lshift */
1787
    0,                  /* nb_rshift */
1788
    0,                  /* nb_and */
1789
    0,                  /* nb_xor */
1790
    0,                  /* nb_or */
1791
    float___trunc___impl, /* nb_int */
1792
    0,                  /* nb_reserved */
1793
    float_float,        /* nb_float */
1794
    0,                  /* nb_inplace_add */
1795
    0,                  /* nb_inplace_subtract */
1796
    0,                  /* nb_inplace_multiply */
1797
    0,                  /* nb_inplace_remainder */
1798
    0,                  /* nb_inplace_power */
1799
    0,                  /* nb_inplace_lshift */
1800
    0,                  /* nb_inplace_rshift */
1801
    0,                  /* nb_inplace_and */
1802
    0,                  /* nb_inplace_xor */
1803
    0,                  /* nb_inplace_or */
1804
    float_floor_div,    /* nb_floor_divide */
1805
    float_div,          /* nb_true_divide */
1806
    0,                  /* nb_inplace_floor_divide */
1807
    0,                  /* nb_inplace_true_divide */
1808
};
1809
1810
PyTypeObject PyFloat_Type = {
1811
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1812
    "float",
1813
    sizeof(PyFloatObject),
1814
    0,
1815
    float_dealloc,                              /* tp_dealloc */
1816
    0,                                          /* tp_vectorcall_offset */
1817
    0,                                          /* tp_getattr */
1818
    0,                                          /* tp_setattr */
1819
    0,                                          /* tp_as_async */
1820
    float_repr,                                 /* tp_repr */
1821
    &float_as_number,                           /* tp_as_number */
1822
    0,                                          /* tp_as_sequence */
1823
    0,                                          /* tp_as_mapping */
1824
    float_hash,                                 /* tp_hash */
1825
    0,                                          /* tp_call */
1826
    0,                                          /* tp_str */
1827
    PyObject_GenericGetAttr,                    /* tp_getattro */
1828
    0,                                          /* tp_setattro */
1829
    0,                                          /* tp_as_buffer */
1830
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1831
        _Py_TPFLAGS_MATCH_SELF,               /* tp_flags */
1832
    float_new__doc__,                           /* tp_doc */
1833
    0,                                          /* tp_traverse */
1834
    0,                                          /* tp_clear */
1835
    float_richcompare,                          /* tp_richcompare */
1836
    0,                                          /* tp_weaklistoffset */
1837
    0,                                          /* tp_iter */
1838
    0,                                          /* tp_iternext */
1839
    float_methods,                              /* tp_methods */
1840
    0,                                          /* tp_members */
1841
    float_getset,                               /* tp_getset */
1842
    0,                                          /* tp_base */
1843
    0,                                          /* tp_dict */
1844
    0,                                          /* tp_descr_get */
1845
    0,                                          /* tp_descr_set */
1846
    0,                                          /* tp_dictoffset */
1847
    0,                                          /* tp_init */
1848
    0,                                          /* tp_alloc */
1849
    float_new,                                  /* tp_new */
1850
    .tp_vectorcall = float_vectorcall,
1851
    .tp_version_tag = _Py_TYPE_VERSION_FLOAT,
1852
};
1853
1854
PyStatus
1855
_PyFloat_InitTypes(PyInterpreterState *interp)
1856
36
{
1857
    /* Init float info */
1858
36
    if (_PyStructSequence_InitBuiltin(interp, &FloatInfoType,
1859
36
                                      &floatinfo_desc) < 0)
1860
0
    {
1861
0
        return _PyStatus_ERR("can't init float info type");
1862
0
    }
1863
1864
36
    return _PyStatus_OK();
1865
36
}
1866
1867
void
1868
_PyFloat_FiniType(PyInterpreterState *interp)
1869
0
{
1870
0
    _PyStructSequence_FiniBuiltin(interp, &FloatInfoType);
1871
0
}
1872
1873
/* Print summary info about the state of the optimized allocator */
1874
void
1875
_PyFloat_DebugMallocStats(FILE *out)
1876
0
{
1877
0
    _PyDebugAllocatorStats(out,
1878
0
                           "free PyFloatObject",
1879
0
                           _Py_FREELIST_SIZE(floats),
1880
0
                           sizeof(PyFloatObject));
1881
0
}
1882
1883
1884
/*----------------------------------------------------------------------------
1885
 * PyFloat_{Pack,Unpack}{2,4,8}.  See floatobject.h.
1886
 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
1887
 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
1888
 * We use:
1889
 *       bits = (unsigned short)f;    Note the truncation
1890
 *       if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
1891
 *           bits++;
1892
 *       }
1893
 */
1894
1895
int
1896
PyFloat_Pack2(double x, char *data, int le)
1897
0
{
1898
0
    unsigned char *p = (unsigned char *)data;
1899
0
    unsigned char sign;
1900
0
    int e;
1901
0
    double f;
1902
0
    unsigned short bits;
1903
0
    int incr = 1;
1904
1905
0
    if (x == 0.0) {
1906
0
        sign = (copysign(1.0, x) == -1.0);
1907
0
        e = 0;
1908
0
        bits = 0;
1909
0
    }
1910
0
    else if (isinf(x)) {
1911
0
        sign = (x < 0.0);
1912
0
        e = 0x1f;
1913
0
        bits = 0;
1914
0
    }
1915
0
    else if (isnan(x)) {
1916
0
        sign = (copysign(1.0, x) == -1.0);
1917
0
        e = 0x1f;
1918
1919
0
        uint64_t v;
1920
0
        memcpy(&v, &x, sizeof(v));
1921
0
        v &= 0xffc0000000000ULL;
1922
0
        bits = (unsigned short)(v >> 42); /* NaN's type & payload */
1923
        /* set qNaN if no payload */
1924
0
        if (!bits) {
1925
0
            bits |= (1<<9);
1926
0
        }
1927
0
    }
1928
0
    else {
1929
0
        sign = (x < 0.0);
1930
0
        if (sign) {
1931
0
            x = -x;
1932
0
        }
1933
1934
0
        f = frexp(x, &e);
1935
0
        if (f < 0.5 || f >= 1.0) {
1936
0
            PyErr_SetString(PyExc_SystemError,
1937
0
                            "frexp() result out of range");
1938
0
            return -1;
1939
0
        }
1940
1941
        /* Normalize f to be in the range [1.0, 2.0) */
1942
0
        f *= 2.0;
1943
0
        e--;
1944
1945
0
        if (e >= 16) {
1946
0
            goto Overflow;
1947
0
        }
1948
0
        else if (e < -25) {
1949
            /* |x| < 2**-25. Underflow to zero. */
1950
0
            f = 0.0;
1951
0
            e = 0;
1952
0
        }
1953
0
        else if (e < -14) {
1954
            /* |x| < 2**-14. Gradual underflow */
1955
0
            f = ldexp(f, 14 + e);
1956
0
            e = 0;
1957
0
        }
1958
0
        else /* if (!(e == 0 && f == 0.0)) */ {
1959
0
            e += 15;
1960
0
            f -= 1.0; /* Get rid of leading 1 */
1961
0
        }
1962
1963
0
        f *= 1024.0; /* 2**10 */
1964
        /* Round to even */
1965
0
        bits = (unsigned short)f; /* Note the truncation */
1966
0
        assert(bits < 1024);
1967
0
        assert(e < 31);
1968
0
        if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
1969
0
            ++bits;
1970
0
            if (bits == 1024) {
1971
                /* The carry propagated out of a string of 10 1 bits. */
1972
0
                bits = 0;
1973
0
                ++e;
1974
0
                if (e == 31)
1975
0
                    goto Overflow;
1976
0
            }
1977
0
        }
1978
0
    }
1979
1980
0
    bits |= (e << 10) | (sign << 15);
1981
1982
    /* Write out result. */
1983
0
    if (le) {
1984
0
        p += 1;
1985
0
        incr = -1;
1986
0
    }
1987
1988
    /* First byte */
1989
0
    *p = (unsigned char)((bits >> 8) & 0xFF);
1990
0
    p += incr;
1991
1992
    /* Second byte */
1993
0
    *p = (unsigned char)(bits & 0xFF);
1994
1995
0
    return 0;
1996
1997
0
  Overflow:
1998
0
    PyErr_SetString(PyExc_OverflowError,
1999
0
                    "float too large to pack with e format");
2000
0
    return -1;
2001
0
}
2002
2003
int
2004
PyFloat_Pack4(double x, char *data, int le)
2005
0
{
2006
0
    unsigned char *p = (unsigned char *)data;
2007
0
    float y = (float)x;
2008
0
    int i, incr = 1;
2009
2010
0
    if (isinf(y) && !isinf(x)) {
2011
0
        PyErr_SetString(PyExc_OverflowError,
2012
0
                        "float too large to pack with f format");
2013
0
        return -1;
2014
0
    }
2015
2016
    /* correct y if x was a sNaN, transformed to qNaN by conversion */
2017
0
    if (isnan(x)) {
2018
0
        uint64_t v;
2019
2020
0
        memcpy(&v, &x, 8);
2021
0
#ifndef __riscv
2022
0
        if ((v & (1ULL << 51)) == 0) {
2023
0
            uint32_t u32;
2024
0
            memcpy(&u32, &y, 4);
2025
            /* if have payload, make sNaN */
2026
0
            if (u32 & 0x3fffff) {
2027
0
                u32 &= ~(1 << 22);
2028
0
            }
2029
0
            memcpy(&y, &u32, 4);
2030
0
        }
2031
#else
2032
        uint32_t u32;
2033
2034
        memcpy(&u32, &y, 4);
2035
        /* Workaround RISC-V: "If a NaN value is converted to a
2036
         * different floating-point type, the result is the
2037
         * canonical NaN of the new type".  The canonical NaN here
2038
         * is a positive qNaN with zero payload. */
2039
        if (v & (1ULL << 63)) {
2040
            u32 |= (1 << 31); /* set sign */
2041
        }
2042
        /* add payload */
2043
        u32 -= (u32 & 0x3fffff);
2044
        u32 += (uint32_t)((v & 0x7ffffffffffffULL) >> 29);
2045
        /* if have payload, make sNaN */
2046
        if ((v & (1ULL << 51)) == 0 && (u32 & 0x3fffff)) {
2047
            u32 &= ~(1 << 22);
2048
        }
2049
2050
        memcpy(&y, &u32, 4);
2051
#endif
2052
0
    }
2053
2054
0
    unsigned char s[sizeof(float)];
2055
0
    memcpy(s, &y, sizeof(float));
2056
2057
0
    if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) {
2058
0
        p += 3;
2059
0
        incr = -1;
2060
0
    }
2061
2062
0
    for (i = 0; i < 4; i++) {
2063
0
        *p = s[i];
2064
0
        p += incr;
2065
0
    }
2066
0
    return 0;
2067
0
}
2068
2069
int
2070
PyFloat_Pack8(double x, char *data, int le)
2071
496
{
2072
496
    unsigned char *p = (unsigned char *)data;
2073
496
    unsigned char as_bytes[8];
2074
496
    memcpy(as_bytes, &x, 8);
2075
496
    const unsigned char *s = as_bytes;
2076
496
    int i, incr = 1;
2077
2078
496
    if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) {
2079
481
        p += 7;
2080
481
        incr = -1;
2081
481
    }
2082
2083
4.46k
    for (i = 0; i < 8; i++) {
2084
3.96k
        *p = *s++;
2085
3.96k
        p += incr;
2086
3.96k
    }
2087
496
    return 0;
2088
496
}
2089
2090
double
2091
PyFloat_Unpack2(const char *data, int le)
2092
0
{
2093
0
    unsigned char *p = (unsigned char *)data;
2094
0
    unsigned char sign;
2095
0
    int e;
2096
0
    unsigned int f;
2097
0
    double x;
2098
0
    int incr = 1;
2099
2100
0
    if (le) {
2101
0
        p += 1;
2102
0
        incr = -1;
2103
0
    }
2104
2105
    /* First byte */
2106
0
    sign = (*p >> 7) & 1;
2107
0
    e = (*p & 0x7C) >> 2;
2108
0
    f = (*p & 0x03) << 8;
2109
0
    p += incr;
2110
2111
    /* Second byte */
2112
0
    f |= *p;
2113
2114
0
    if (e == 0x1f) {
2115
0
        if (f == 0) {
2116
            /* Infinity */
2117
0
            return sign ? -INFINITY : INFINITY;
2118
0
        }
2119
0
        else {
2120
            /* NaN */
2121
0
            uint64_t v = sign ? 0xfff0000000000000ULL : 0x7ff0000000000000ULL;
2122
2123
0
            v += (uint64_t)f << 42; /* add NaN's type & payload */
2124
0
            memcpy(&x, &v, sizeof(v));
2125
0
            return x;
2126
0
        }
2127
0
    }
2128
2129
0
    x = (double)f / 1024.0;
2130
2131
0
    if (e == 0) {
2132
0
        e = -14;
2133
0
    }
2134
0
    else {
2135
0
        x += 1.0;
2136
0
        e -= 15;
2137
0
    }
2138
0
    x = ldexp(x, e);
2139
2140
0
    if (sign)
2141
0
        x = -x;
2142
2143
0
    return x;
2144
0
}
2145
2146
double
2147
PyFloat_Unpack4(const char *data, int le)
2148
18
{
2149
18
    unsigned char *p = (unsigned char *)data;
2150
18
    float x;
2151
2152
18
    if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) {
2153
18
        char buf[4];
2154
18
        char *d = &buf[3];
2155
18
        int i;
2156
2157
90
        for (i = 0; i < 4; i++) {
2158
72
            *d-- = *p++;
2159
72
        }
2160
18
        memcpy(&x, buf, 4);
2161
18
    }
2162
0
    else {
2163
0
        memcpy(&x, p, 4);
2164
0
    }
2165
2166
    /* return sNaN double if x was sNaN float */
2167
18
    if (isnan(x)) {
2168
0
        uint32_t v;
2169
0
        memcpy(&v, &x, 4);
2170
2171
0
#ifndef __riscv
2172
0
        if ((v & (1 << 22)) == 0) {
2173
0
            double y = x; /* will make qNaN double */
2174
0
            uint64_t u64;
2175
0
            memcpy(&u64, &y, 8);
2176
0
            u64 &= ~(1ULL << 51); /* make sNaN */
2177
0
            memcpy(&y, &u64, 8);
2178
0
            return y;
2179
0
        }
2180
#else
2181
        double y = x;
2182
        uint64_t u64;
2183
2184
        memcpy(&u64, &y, 8);
2185
        if ((v & (1 << 22)) == 0) {
2186
            u64 &= ~(1ULL << 51);
2187
        }
2188
        /* Workaround RISC-V, see PyFloat_Pack4() */
2189
        if (v & (1 << 31)) {
2190
            u64 |= (1ULL << 63); /* set sign */
2191
        }
2192
        /* add payload */
2193
        u64 -= (u64 & 0x7ffffffffffffULL);
2194
        u64 += ((v & 0x3fffffULL) << 29);
2195
2196
        memcpy(&y, &u64, 8);
2197
        return y;
2198
#endif
2199
0
    }
2200
2201
18
    return x;
2202
18
}
2203
2204
double
2205
PyFloat_Unpack8(const char *data, int le)
2206
709
{
2207
709
    unsigned char *p = (unsigned char *)data;
2208
709
    double x;
2209
2210
709
    if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) {
2211
72
        char buf[8];
2212
72
        char *d = &buf[7];
2213
72
        int i;
2214
2215
648
        for (i = 0; i < 8; i++) {
2216
576
            *d-- = *p++;
2217
576
        }
2218
72
        memcpy(&x, buf, 8);
2219
72
    }
2220
637
    else {
2221
637
        memcpy(&x, p, 8);
2222
637
    }
2223
2224
709
    return x;
2225
709
}