Coverage Report

Created: 2026-02-26 06:53

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