Coverage Report

Created: 2025-11-24 06:11

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