Coverage Report

Created: 2025-07-04 06:49

/src/cpython/Objects/floatobject.c
Line
Count
Source (jump to first uncovered line)
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
16
{
84
16
    PyObject* floatinfo;
85
16
    int pos = 0;
86
87
16
    floatinfo = PyStructSequence_New(&FloatInfoType);
88
16
    if (floatinfo == NULL) {
89
0
        return NULL;
90
0
    }
91
92
16
#define SetFlag(CALL) \
93
176
    do {                                                    \
94
176
        PyObject *flag = (CALL);                            \
95
176
        if (flag == NULL) {                                 \
96
0
            Py_CLEAR(floatinfo);                            \
97
0
            return NULL;                                    \
98
0
        }                                                   \
99
176
        PyStructSequence_SET_ITEM(floatinfo, pos++, flag);  \
100
176
    } while (0)
101
102
128
#define SetIntFlag(FLAG) SetFlag(PyLong_FromLong((FLAG)))
103
48
#define SetDblFlag(FLAG) SetFlag(PyFloat_FromDouble((FLAG)))
104
105
16
    SetDblFlag(DBL_MAX);
106
16
    SetIntFlag(DBL_MAX_EXP);
107
16
    SetIntFlag(DBL_MAX_10_EXP);
108
16
    SetDblFlag(DBL_MIN);
109
16
    SetIntFlag(DBL_MIN_EXP);
110
16
    SetIntFlag(DBL_MIN_10_EXP);
111
16
    SetIntFlag(DBL_DIG);
112
16
    SetIntFlag(DBL_MANT_DIG);
113
16
    SetDblFlag(DBL_EPSILON);
114
16
    SetIntFlag(FLT_RADIX);
115
16
    SetIntFlag(FLT_ROUNDS);
116
16
#undef SetIntFlag
117
16
#undef SetDblFlag
118
16
#undef SetFlag
119
120
16
    return floatinfo;
121
16
}
122
123
PyObject *
124
PyFloat_FromDouble(double fval)
125
6.88M
{
126
6.88M
    PyFloatObject *op = _Py_FREELIST_POP(PyFloatObject, floats);
127
6.88M
    if (op == NULL) {
128
550k
        op = PyObject_Malloc(sizeof(PyFloatObject));
129
550k
        if (!op) {
130
0
            return PyErr_NoMemory();
131
0
        }
132
550k
        _PyObject_Init((PyObject*)op, &PyFloat_Type);
133
550k
    }
134
6.88M
    op->ob_fval = fval;
135
6.88M
    return (PyObject *) op;
136
6.88M
}
137
138
_PyStackRef _PyFloat_FromDouble_ConsumeInputs(_PyStackRef left, _PyStackRef right, double value)
139
0
{
140
0
    PyStackRef_CLOSE_SPECIALIZED(left, _PyFloat_ExactDealloc);
141
0
    PyStackRef_CLOSE_SPECIALIZED(right, _PyFloat_ExactDealloc);
142
0
    return PyStackRef_FromPyObjectSteal(PyFloat_FromDouble(value));
143
0
}
144
145
static PyObject *
146
float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
147
575k
{
148
575k
    double x;
149
575k
    const char *end;
150
575k
    const char *last = s + len;
151
    /* strip leading whitespace */
152
575k
    while (s < last && Py_ISSPACE(*s)) {
153
0
        s++;
154
0
    }
155
575k
    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
575k
    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
575k
    x = PyOS_string_to_double(s, (char **)&end, NULL);
171
575k
    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
575k
    else if (x == -1.0 && PyErr_Occurred()) {
178
0
        return NULL;
179
0
    }
180
575k
    else {
181
575k
        return PyFloat_FromDouble(x);
182
575k
    }
183
575k
}
184
185
PyObject *
186
PyFloat_FromString(PyObject *v)
187
575k
{
188
575k
    const char *s;
189
575k
    PyObject *s_buffer = NULL;
190
575k
    Py_ssize_t len;
191
575k
    Py_buffer view = {NULL, NULL};
192
575k
    PyObject *result = NULL;
193
194
575k
    if (PyUnicode_Check(v)) {
195
8
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
196
8
        if (s_buffer == NULL)
197
0
            return NULL;
198
8
        assert(PyUnicode_IS_ASCII(s_buffer));
199
        /* Simply get a pointer to existing ASCII characters. */
200
8
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
201
8
        assert(s != NULL);
202
8
    }
203
575k
    else if (PyBytes_Check(v)) {
204
575k
        s = PyBytes_AS_STRING(v);
205
575k
        len = PyBytes_GET_SIZE(v);
206
575k
    }
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
575k
    result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
229
575k
                                                   float_from_string_inner);
230
575k
    PyBuffer_Release(&view);
231
575k
    Py_XDECREF(s_buffer);
232
575k
    return result;
233
575k
}
234
235
void
236
_PyFloat_ExactDealloc(PyObject *obj)
237
6.88M
{
238
6.88M
    assert(PyFloat_CheckExact(obj));
239
6.88M
    _Py_FREELIST_FREE(floats, obj, PyObject_Free);
240
6.88M
}
241
242
static void
243
float_dealloc(PyObject *op)
244
3.89M
{
245
3.89M
    assert(PyFloat_Check(op));
246
3.89M
    if (PyFloat_CheckExact(op))
247
3.89M
        _PyFloat_ExactDealloc(op);
248
0
    else
249
0
        Py_TYPE(op)->tp_free(op);
250
3.89M
}
251
252
double
253
PyFloat_AsDouble(PyObject *op)
254
12.4M
{
255
12.4M
    PyNumberMethods *nb;
256
12.4M
    PyObject *res;
257
12.4M
    double val;
258
259
12.4M
    if (op == NULL) {
260
0
        PyErr_BadArgument();
261
0
        return -1;
262
0
    }
263
264
12.4M
    if (PyFloat_Check(op)) {
265
12.4M
        return PyFloat_AS_DOUBLE(op);
266
12.4M
    }
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
                         "%.50s.__float__ returned non-float (type %.50s)",
292
0
                         Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name);
293
0
            Py_DECREF(res);
294
0
            return -1;
295
0
        }
296
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
297
0
                "%.50s.__float__ returned non-float (type %.50s).  "
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
                Py_TYPE(op)->tp_name, Py_TYPE(res)->tp_name)) {
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
22
    if (PyFloat_Check(obj))                                 \
319
22
        dbl = PyFloat_AS_DOUBLE(obj);                       \
320
22
    else if (_Py_convert_int_to_double(&(obj), &(dbl)) < 0) \
321
8
        return obj;
322
323
/* Methods */
324
325
int
326
_Py_convert_int_to_double(PyObject **v, double *dbl)
327
8
{
328
8
    PyObject *obj = *v;
329
330
8
    if (PyLong_Check(obj)) {
331
8
        *dbl = PyLong_AsDouble(obj);
332
8
        if (*dbl == -1.0 && PyErr_Occurred()) {
333
0
            *v = NULL;
334
0
            return -1;
335
0
        }
336
8
    }
337
0
    else {
338
0
        *v = Py_NewRef(Py_NotImplemented);
339
0
        return -1;
340
0
    }
341
8
    return 0;
342
8
}
343
344
static PyObject *
345
float_repr(PyObject *op)
346
52.7k
{
347
52.7k
    PyFloatObject *v = _PyFloat_CAST(op);
348
52.7k
    PyObject *result;
349
52.7k
    char *buf;
350
351
52.7k
    buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
352
52.7k
                                'r', 0,
353
52.7k
                                Py_DTSF_ADD_DOT_0,
354
52.7k
                                NULL);
355
52.7k
    if (!buf)
356
0
        return PyErr_NoMemory();
357
52.7k
    result = _PyUnicode_FromASCII(buf, strlen(buf));
358
52.7k
    PyMem_Free(buf);
359
52.7k
    return result;
360
52.7k
}
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
304
{
380
304
    double i, j;
381
304
    int r = 0;
382
383
304
    assert(PyFloat_Check(v));
384
304
    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
304
    if (PyFloat_Check(w))
390
201
        j = PyFloat_AS_DOUBLE(w);
391
392
103
    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
103
    else if (PyLong_Check(w)) {
404
103
        int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
405
103
        int wsign;
406
103
        int exponent;
407
408
103
        (void)PyLong_GetSign(w, &wsign);
409
103
        if (vsign != wsign) {
410
            /* Magnitudes are irrelevant -- the signs alone
411
             * determine the outcome.
412
             */
413
103
            i = (double)vsign;
414
103
            j = (double)wsign;
415
103
            goto Compare;
416
103
        }
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
304
 Compare:
529
304
    switch (op) {
530
94
    case Py_EQ:
531
94
        r = i == j;
532
94
        break;
533
207
    case Py_NE:
534
207
        r = i != j;
535
207
        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
304
    }
549
304
    return PyBool_FromLong(r);
550
551
0
 Unimplemented:
552
0
    Py_RETURN_NOTIMPLEMENTED;
553
304
}
554
555
static Py_hash_t
556
float_hash(PyObject *op)
557
365
{
558
365
    PyFloatObject *v = _PyFloat_CAST(op);
559
365
    return _Py_HashDouble(op, v->ob_fval);
560
365
}
561
562
static PyObject *
563
float_add(PyObject *v, PyObject *w)
564
2
{
565
2
    double a,b;
566
2
    CONVERT_TO_DOUBLE(v, a);
567
2
    CONVERT_TO_DOUBLE(w, b);
568
2
    a = a + b;
569
2
    return PyFloat_FromDouble(a);
570
2
}
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
3
{
585
3
    double a,b;
586
3
    CONVERT_TO_DOUBLE(v, a);
587
3
    CONVERT_TO_DOUBLE(w, b);
588
3
    a = a * b;
589
3
    return PyFloat_FromDouble(a);
590
3
}
591
592
static PyObject *
593
float_div(PyObject *v, PyObject *w)
594
4
{
595
4
    double a,b;
596
4
    CONVERT_TO_DOUBLE(v, a);
597
4
    CONVERT_TO_DOUBLE(w, b);
598
4
    if (b == 0.0) {
599
0
        PyErr_SetString(PyExc_ZeroDivisionError,
600
0
                        "division by zero");
601
0
        return NULL;
602
0
    }
603
4
    a = a / b;
604
4
    return PyFloat_FromDouble(a);
605
4
}
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
2
{
710
2
    double iv, iw, ix;
711
2
    int negate_result = 0;
712
713
2
    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
2
    CONVERT_TO_DOUBLE(v, iv);
720
2
    CONVERT_TO_DOUBLE(w, iw);
721
722
    /* Sort out special cases here instead of relying on pow() */
723
2
    if (iw == 0) {              /* v**0 is 1, even 0**0 */
724
0
        return PyFloat_FromDouble(1.0);
725
0
    }
726
2
    if (isnan(iv)) {        /* nan**w = nan, unless w == 0 */
727
0
        return PyFloat_FromDouble(iv);
728
0
    }
729
2
    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
2
    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
2
    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
2
    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
2
    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
2
    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
2
    errno = 0;
810
2
    ix = pow(iv, iw);
811
2
    _Py_ADJUST_ERANGE1(ix);
812
2
    if (negate_result)
813
0
        ix = -ix;
814
815
2
    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
2
    return PyFloat_FromDouble(ix);
824
2
}
825
826
#undef DOUBLE_IS_ODD_INTEGER
827
828
static PyObject *
829
float_neg(PyObject *op)
830
3.37k
{
831
3.37k
    PyFloatObject *v = _PyFloat_CAST(op);
832
3.37k
    return PyFloat_FromDouble(-v->ob_fval);
833
3.37k
}
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
13.4k
{
886
13.4k
    return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
887
13.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
float.as_integer_ratio
1488
1489
Return a pair of integers, whose ratio is exactly equal to the original float.
1490
1491
The ratio is in lowest terms and has a positive denominator.  Raise
1492
OverflowError on infinities and a ValueError on NaNs.
1493
1494
>>> (10.0).as_integer_ratio()
1495
(10, 1)
1496
>>> (0.0).as_integer_ratio()
1497
(0, 1)
1498
>>> (-.25).as_integer_ratio()
1499
(-1, 4)
1500
[clinic start generated code]*/
1501
1502
static PyObject *
1503
float_as_integer_ratio_impl(PyObject *self)
1504
/*[clinic end generated code: output=65f25f0d8d30a712 input=d5ba7765655d75bd]*/
1505
0
{
1506
0
    double self_double;
1507
0
    double float_part;
1508
0
    int exponent;
1509
0
    int i;
1510
1511
0
    PyObject *py_exponent = NULL;
1512
0
    PyObject *numerator = NULL;
1513
0
    PyObject *denominator = NULL;
1514
0
    PyObject *result_pair = NULL;
1515
0
    PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
1516
1517
0
    CONVERT_TO_DOUBLE(self, self_double);
1518
1519
0
    if (isinf(self_double)) {
1520
0
        PyErr_SetString(PyExc_OverflowError,
1521
0
                        "cannot convert Infinity to integer ratio");
1522
0
        return NULL;
1523
0
    }
1524
0
    if (isnan(self_double)) {
1525
0
        PyErr_SetString(PyExc_ValueError,
1526
0
                        "cannot convert NaN to integer ratio");
1527
0
        return NULL;
1528
0
    }
1529
1530
0
    float_part = frexp(self_double, &exponent);        /* self_double == float_part * 2**exponent exactly */
1531
1532
0
    for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1533
0
        float_part *= 2.0;
1534
0
        exponent--;
1535
0
    }
1536
    /* self == float_part * 2**exponent exactly and float_part is integral.
1537
       If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1538
       to be truncated by PyLong_FromDouble(). */
1539
1540
0
    numerator = PyLong_FromDouble(float_part);
1541
0
    if (numerator == NULL)
1542
0
        goto error;
1543
0
    denominator = PyLong_FromLong(1);
1544
0
    if (denominator == NULL)
1545
0
        goto error;
1546
0
    py_exponent = PyLong_FromLong(Py_ABS(exponent));
1547
0
    if (py_exponent == NULL)
1548
0
        goto error;
1549
1550
    /* fold in 2**exponent */
1551
0
    if (exponent > 0) {
1552
0
        Py_SETREF(numerator,
1553
0
                  long_methods->nb_lshift(numerator, py_exponent));
1554
0
        if (numerator == NULL)
1555
0
            goto error;
1556
0
    }
1557
0
    else {
1558
0
        Py_SETREF(denominator,
1559
0
                  long_methods->nb_lshift(denominator, py_exponent));
1560
0
        if (denominator == NULL)
1561
0
            goto error;
1562
0
    }
1563
1564
0
    result_pair = PyTuple_Pack(2, numerator, denominator);
1565
1566
0
error:
1567
0
    Py_XDECREF(py_exponent);
1568
0
    Py_XDECREF(denominator);
1569
0
    Py_XDECREF(numerator);
1570
0
    return result_pair;
1571
0
}
1572
1573
static PyObject *
1574
float_subtype_new(PyTypeObject *type, PyObject *x);
1575
1576
/*[clinic input]
1577
@classmethod
1578
float.__new__ as float_new
1579
    x: object(c_default="NULL") = 0
1580
    /
1581
1582
Convert a string or number to a floating-point number, if possible.
1583
[clinic start generated code]*/
1584
1585
static PyObject *
1586
float_new_impl(PyTypeObject *type, PyObject *x)
1587
/*[clinic end generated code: output=ccf1e8dc460ba6ba input=55909f888aa0c8a6]*/
1588
8
{
1589
8
    if (type != &PyFloat_Type) {
1590
0
        if (x == NULL) {
1591
0
            x = _PyLong_GetZero();
1592
0
        }
1593
0
        return float_subtype_new(type, x); /* Wimp out */
1594
0
    }
1595
1596
8
    if (x == NULL) {
1597
0
        return PyFloat_FromDouble(0.0);
1598
0
    }
1599
    /* If it's a string, but not a string subclass, use
1600
       PyFloat_FromString. */
1601
8
    if (PyUnicode_CheckExact(x))
1602
8
        return PyFloat_FromString(x);
1603
0
    return PyNumber_Float(x);
1604
8
}
1605
1606
/* Wimpy, slow approach to tp_new calls for subtypes of float:
1607
   first create a regular float from whatever arguments we got,
1608
   then allocate a subtype instance and initialize its ob_fval
1609
   from the regular float.  The regular float is then thrown away.
1610
*/
1611
static PyObject *
1612
float_subtype_new(PyTypeObject *type, PyObject *x)
1613
0
{
1614
0
    PyObject *tmp, *newobj;
1615
1616
0
    assert(PyType_IsSubtype(type, &PyFloat_Type));
1617
0
    tmp = float_new_impl(&PyFloat_Type, x);
1618
0
    if (tmp == NULL)
1619
0
        return NULL;
1620
0
    assert(PyFloat_Check(tmp));
1621
0
    newobj = type->tp_alloc(type, 0);
1622
0
    if (newobj == NULL) {
1623
0
        Py_DECREF(tmp);
1624
0
        return NULL;
1625
0
    }
1626
0
    ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1627
0
    Py_DECREF(tmp);
1628
0
    return newobj;
1629
0
}
1630
1631
static PyObject *
1632
float_vectorcall(PyObject *type, PyObject *const *args,
1633
                 size_t nargsf, PyObject *kwnames)
1634
8
{
1635
8
    if (!_PyArg_NoKwnames("float", kwnames)) {
1636
0
        return NULL;
1637
0
    }
1638
1639
8
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1640
8
    if (!_PyArg_CheckPositional("float", nargs, 0, 1)) {
1641
0
        return NULL;
1642
0
    }
1643
1644
8
    PyObject *x = nargs >= 1 ? args[0] : NULL;
1645
8
    return float_new_impl(_PyType_CAST(type), x);
1646
8
}
1647
1648
1649
/*[clinic input]
1650
@classmethod
1651
float.from_number
1652
1653
    number: object
1654
    /
1655
1656
Convert real number to a floating-point number.
1657
[clinic start generated code]*/
1658
1659
static PyObject *
1660
float_from_number_impl(PyTypeObject *type, PyObject *number)
1661
/*[clinic end generated code: output=dda7e4466ab7068d input=1f8424d9bc11866a]*/
1662
0
{
1663
0
    if (PyFloat_CheckExact(number) && type == &PyFloat_Type) {
1664
0
        Py_INCREF(number);
1665
0
        return number;
1666
0
    }
1667
0
    double x = PyFloat_AsDouble(number);
1668
0
    if (x == -1.0 && PyErr_Occurred()) {
1669
0
        return NULL;
1670
0
    }
1671
0
    PyObject *result = PyFloat_FromDouble(x);
1672
0
    if (type != &PyFloat_Type && result != NULL) {
1673
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
1674
0
    }
1675
0
    return result;
1676
0
}
1677
1678
1679
/*[clinic input]
1680
float.__getnewargs__
1681
[clinic start generated code]*/
1682
1683
static PyObject *
1684
float___getnewargs___impl(PyObject *self)
1685
/*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/
1686
0
{
1687
0
    return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval);
1688
0
}
1689
1690
/* this is for the benefit of the pack/unpack routines below */
1691
typedef enum _py_float_format_type float_format_type;
1692
82
#define unknown_format _py_float_format_unknown
1693
164
#define ieee_big_endian_format _py_float_format_ieee_big_endian
1694
196
#define ieee_little_endian_format _py_float_format_ieee_little_endian
1695
1696
16
#define float_format (_PyRuntime.float_state.float_format)
1697
262
#define double_format (_PyRuntime.float_state.double_format)
1698
1699
1700
/*[clinic input]
1701
@classmethod
1702
float.__getformat__
1703
1704
    typestr: str
1705
        Must be 'double' or 'float'.
1706
    /
1707
1708
You probably don't want to use this function.
1709
1710
It exists mainly to be used in Python's test suite.
1711
1712
This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
1713
little-endian' best describes the format of floating-point numbers used by the
1714
C type named by typestr.
1715
[clinic start generated code]*/
1716
1717
static PyObject *
1718
float___getformat___impl(PyTypeObject *type, const char *typestr)
1719
/*[clinic end generated code: output=2bfb987228cc9628 input=90d5e246409a246e]*/
1720
0
{
1721
0
    float_format_type r;
1722
1723
0
    if (strcmp(typestr, "double") == 0) {
1724
0
        r = double_format;
1725
0
    }
1726
0
    else if (strcmp(typestr, "float") == 0) {
1727
0
        r = float_format;
1728
0
    }
1729
0
    else {
1730
0
        PyErr_SetString(PyExc_ValueError,
1731
0
                        "__getformat__() argument 1 must be "
1732
0
                        "'double' or 'float'");
1733
0
        return NULL;
1734
0
    }
1735
1736
0
    switch (r) {
1737
0
    case unknown_format:
1738
0
        return PyUnicode_FromString("unknown");
1739
0
    case ieee_little_endian_format:
1740
0
        return PyUnicode_FromString("IEEE, little-endian");
1741
0
    case ieee_big_endian_format:
1742
0
        return PyUnicode_FromString("IEEE, big-endian");
1743
0
    default:
1744
0
        PyErr_SetString(PyExc_RuntimeError,
1745
0
                        "insane float_format or double_format");
1746
0
        return NULL;
1747
0
    }
1748
0
}
1749
1750
1751
static PyObject *
1752
float_getreal(PyObject *v, void *Py_UNUSED(closure))
1753
0
{
1754
0
    return float_float(v);
1755
0
}
1756
1757
static PyObject *
1758
float_getimag(PyObject *Py_UNUSED(v), void *Py_UNUSED(closure))
1759
0
{
1760
0
    return PyFloat_FromDouble(0.0);
1761
0
}
1762
1763
/*[clinic input]
1764
float.__format__
1765
1766
  format_spec: unicode
1767
  /
1768
1769
Formats the float according to format_spec.
1770
[clinic start generated code]*/
1771
1772
static PyObject *
1773
float___format___impl(PyObject *self, PyObject *format_spec)
1774
/*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/
1775
0
{
1776
0
    _PyUnicodeWriter writer;
1777
0
    int ret;
1778
1779
0
    _PyUnicodeWriter_Init(&writer);
1780
0
    ret = _PyFloat_FormatAdvancedWriter(
1781
0
        &writer,
1782
0
        self,
1783
0
        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1784
0
    if (ret == -1) {
1785
0
        _PyUnicodeWriter_Dealloc(&writer);
1786
0
        return NULL;
1787
0
    }
1788
0
    return _PyUnicodeWriter_Finish(&writer);
1789
0
}
1790
1791
static PyMethodDef float_methods[] = {
1792
    FLOAT_FROM_NUMBER_METHODDEF
1793
    FLOAT_CONJUGATE_METHODDEF
1794
    FLOAT___TRUNC___METHODDEF
1795
    FLOAT___FLOOR___METHODDEF
1796
    FLOAT___CEIL___METHODDEF
1797
    FLOAT___ROUND___METHODDEF
1798
    FLOAT_AS_INTEGER_RATIO_METHODDEF
1799
    FLOAT_FROMHEX_METHODDEF
1800
    FLOAT_HEX_METHODDEF
1801
    FLOAT_IS_INTEGER_METHODDEF
1802
    FLOAT___GETNEWARGS___METHODDEF
1803
    FLOAT___GETFORMAT___METHODDEF
1804
    FLOAT___FORMAT___METHODDEF
1805
    {NULL,              NULL}           /* sentinel */
1806
};
1807
1808
static PyGetSetDef float_getset[] = {
1809
    {"real",
1810
     float_getreal, NULL,
1811
     "the real part of a complex number",
1812
     NULL},
1813
    {"imag",
1814
     float_getimag, NULL,
1815
     "the imaginary part of a complex number",
1816
     NULL},
1817
    {NULL}  /* Sentinel */
1818
};
1819
1820
1821
static PyNumberMethods float_as_number = {
1822
    float_add,          /* nb_add */
1823
    float_sub,          /* nb_subtract */
1824
    float_mul,          /* nb_multiply */
1825
    float_rem,          /* nb_remainder */
1826
    float_divmod,       /* nb_divmod */
1827
    float_pow,          /* nb_power */
1828
    float_neg,          /* nb_negative */
1829
    float_float,        /* nb_positive */
1830
    float_abs,          /* nb_absolute */
1831
    float_bool,         /* nb_bool */
1832
    0,                  /* nb_invert */
1833
    0,                  /* nb_lshift */
1834
    0,                  /* nb_rshift */
1835
    0,                  /* nb_and */
1836
    0,                  /* nb_xor */
1837
    0,                  /* nb_or */
1838
    float___trunc___impl, /* nb_int */
1839
    0,                  /* nb_reserved */
1840
    float_float,        /* nb_float */
1841
    0,                  /* nb_inplace_add */
1842
    0,                  /* nb_inplace_subtract */
1843
    0,                  /* nb_inplace_multiply */
1844
    0,                  /* nb_inplace_remainder */
1845
    0,                  /* nb_inplace_power */
1846
    0,                  /* nb_inplace_lshift */
1847
    0,                  /* nb_inplace_rshift */
1848
    0,                  /* nb_inplace_and */
1849
    0,                  /* nb_inplace_xor */
1850
    0,                  /* nb_inplace_or */
1851
    float_floor_div,    /* nb_floor_divide */
1852
    float_div,          /* nb_true_divide */
1853
    0,                  /* nb_inplace_floor_divide */
1854
    0,                  /* nb_inplace_true_divide */
1855
};
1856
1857
PyTypeObject PyFloat_Type = {
1858
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1859
    "float",
1860
    sizeof(PyFloatObject),
1861
    0,
1862
    float_dealloc,                              /* tp_dealloc */
1863
    0,                                          /* tp_vectorcall_offset */
1864
    0,                                          /* tp_getattr */
1865
    0,                                          /* tp_setattr */
1866
    0,                                          /* tp_as_async */
1867
    float_repr,                                 /* tp_repr */
1868
    &float_as_number,                           /* tp_as_number */
1869
    0,                                          /* tp_as_sequence */
1870
    0,                                          /* tp_as_mapping */
1871
    float_hash,                                 /* tp_hash */
1872
    0,                                          /* tp_call */
1873
    0,                                          /* tp_str */
1874
    PyObject_GenericGetAttr,                    /* tp_getattro */
1875
    0,                                          /* tp_setattro */
1876
    0,                                          /* tp_as_buffer */
1877
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1878
        _Py_TPFLAGS_MATCH_SELF,               /* tp_flags */
1879
    float_new__doc__,                           /* tp_doc */
1880
    0,                                          /* tp_traverse */
1881
    0,                                          /* tp_clear */
1882
    float_richcompare,                          /* tp_richcompare */
1883
    0,                                          /* tp_weaklistoffset */
1884
    0,                                          /* tp_iter */
1885
    0,                                          /* tp_iternext */
1886
    float_methods,                              /* tp_methods */
1887
    0,                                          /* tp_members */
1888
    float_getset,                               /* tp_getset */
1889
    0,                                          /* tp_base */
1890
    0,                                          /* tp_dict */
1891
    0,                                          /* tp_descr_get */
1892
    0,                                          /* tp_descr_set */
1893
    0,                                          /* tp_dictoffset */
1894
    0,                                          /* tp_init */
1895
    0,                                          /* tp_alloc */
1896
    float_new,                                  /* tp_new */
1897
    .tp_vectorcall = float_vectorcall,
1898
    .tp_version_tag = _Py_TYPE_VERSION_FLOAT,
1899
};
1900
1901
static void
1902
_init_global_state(void)
1903
16
{
1904
16
    float_format_type detected_double_format, detected_float_format;
1905
1906
    /* We attempt to determine if this machine is using IEEE
1907
       floating-point formats by peering at the bits of some
1908
       carefully chosen values.  If it looks like we are on an
1909
       IEEE platform, the float packing/unpacking routines can
1910
       just copy bits, if not they resort to arithmetic & shifts
1911
       and masks.  The shifts & masks approach works on all finite
1912
       values, but what happens to infinities, NaNs and signed
1913
       zeroes on packing is an accident, and attempting to unpack
1914
       a NaN or an infinity will raise an exception.
1915
1916
       Note that if we're on some whacked-out platform which uses
1917
       IEEE formats but isn't strictly little-endian or big-
1918
       endian, we will fall back to the portable shifts & masks
1919
       method. */
1920
1921
16
#if SIZEOF_DOUBLE == 8
1922
16
    {
1923
16
        double x = 9006104071832581.0;
1924
16
        if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1925
0
            detected_double_format = ieee_big_endian_format;
1926
16
        else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1927
16
            detected_double_format = ieee_little_endian_format;
1928
0
        else
1929
0
            detected_double_format = unknown_format;
1930
16
    }
1931
#else
1932
    detected_double_format = unknown_format;
1933
#endif
1934
1935
16
#if SIZEOF_FLOAT == 4
1936
16
    {
1937
16
        float y = 16711938.0;
1938
16
        if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1939
0
            detected_float_format = ieee_big_endian_format;
1940
16
        else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1941
16
            detected_float_format = ieee_little_endian_format;
1942
0
        else
1943
0
            detected_float_format = unknown_format;
1944
16
    }
1945
#else
1946
    detected_float_format = unknown_format;
1947
#endif
1948
1949
16
    double_format = detected_double_format;
1950
16
    float_format = detected_float_format;
1951
16
}
1952
1953
void
1954
_PyFloat_InitState(PyInterpreterState *interp)
1955
16
{
1956
16
    if (!_Py_IsMainInterpreter(interp)) {
1957
0
        return;
1958
0
    }
1959
16
    _init_global_state();
1960
16
}
1961
1962
PyStatus
1963
_PyFloat_InitTypes(PyInterpreterState *interp)
1964
16
{
1965
    /* Init float info */
1966
16
    if (_PyStructSequence_InitBuiltin(interp, &FloatInfoType,
1967
16
                                      &floatinfo_desc) < 0)
1968
0
    {
1969
0
        return _PyStatus_ERR("can't init float info type");
1970
0
    }
1971
1972
16
    return _PyStatus_OK();
1973
16
}
1974
1975
void
1976
_PyFloat_FiniType(PyInterpreterState *interp)
1977
0
{
1978
0
    _PyStructSequence_FiniBuiltin(interp, &FloatInfoType);
1979
0
}
1980
1981
/* Print summary info about the state of the optimized allocator */
1982
void
1983
_PyFloat_DebugMallocStats(FILE *out)
1984
0
{
1985
0
    _PyDebugAllocatorStats(out,
1986
0
                           "free PyFloatObject",
1987
0
                           _Py_FREELIST_SIZE(floats),
1988
0
                           sizeof(PyFloatObject));
1989
0
}
1990
1991
1992
/*----------------------------------------------------------------------------
1993
 * PyFloat_{Pack,Unpack}{2,4,8}.  See floatobject.h.
1994
 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
1995
 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
1996
 * We use:
1997
 *       bits = (unsigned short)f;    Note the truncation
1998
 *       if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
1999
 *           bits++;
2000
 *       }
2001
 */
2002
2003
int
2004
PyFloat_Pack2(double x, char *data, int le)
2005
0
{
2006
0
    unsigned char *p = (unsigned char *)data;
2007
0
    unsigned char sign;
2008
0
    int e;
2009
0
    double f;
2010
0
    unsigned short bits;
2011
0
    int incr = 1;
2012
2013
0
    if (x == 0.0) {
2014
0
        sign = (copysign(1.0, x) == -1.0);
2015
0
        e = 0;
2016
0
        bits = 0;
2017
0
    }
2018
0
    else if (isinf(x)) {
2019
0
        sign = (x < 0.0);
2020
0
        e = 0x1f;
2021
0
        bits = 0;
2022
0
    }
2023
0
    else if (isnan(x)) {
2024
0
        sign = (copysign(1.0, x) == -1.0);
2025
0
        e = 0x1f;
2026
2027
0
        uint64_t v;
2028
0
        memcpy(&v, &x, sizeof(v));
2029
0
        v &= 0xffc0000000000ULL;
2030
0
        bits = (unsigned short)(v >> 42); /* NaN's type & payload */
2031
0
    }
2032
0
    else {
2033
0
        sign = (x < 0.0);
2034
0
        if (sign) {
2035
0
            x = -x;
2036
0
        }
2037
2038
0
        f = frexp(x, &e);
2039
0
        if (f < 0.5 || f >= 1.0) {
2040
0
            PyErr_SetString(PyExc_SystemError,
2041
0
                            "frexp() result out of range");
2042
0
            return -1;
2043
0
        }
2044
2045
        /* Normalize f to be in the range [1.0, 2.0) */
2046
0
        f *= 2.0;
2047
0
        e--;
2048
2049
0
        if (e >= 16) {
2050
0
            goto Overflow;
2051
0
        }
2052
0
        else if (e < -25) {
2053
            /* |x| < 2**-25. Underflow to zero. */
2054
0
            f = 0.0;
2055
0
            e = 0;
2056
0
        }
2057
0
        else if (e < -14) {
2058
            /* |x| < 2**-14. Gradual underflow */
2059
0
            f = ldexp(f, 14 + e);
2060
0
            e = 0;
2061
0
        }
2062
0
        else /* if (!(e == 0 && f == 0.0)) */ {
2063
0
            e += 15;
2064
0
            f -= 1.0; /* Get rid of leading 1 */
2065
0
        }
2066
2067
0
        f *= 1024.0; /* 2**10 */
2068
        /* Round to even */
2069
0
        bits = (unsigned short)f; /* Note the truncation */
2070
0
        assert(bits < 1024);
2071
0
        assert(e < 31);
2072
0
        if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2073
0
            ++bits;
2074
0
            if (bits == 1024) {
2075
                /* The carry propagated out of a string of 10 1 bits. */
2076
0
                bits = 0;
2077
0
                ++e;
2078
0
                if (e == 31)
2079
0
                    goto Overflow;
2080
0
            }
2081
0
        }
2082
0
    }
2083
2084
0
    bits |= (e << 10) | (sign << 15);
2085
2086
    /* Write out result. */
2087
0
    if (le) {
2088
0
        p += 1;
2089
0
        incr = -1;
2090
0
    }
2091
2092
    /* First byte */
2093
0
    *p = (unsigned char)((bits >> 8) & 0xFF);
2094
0
    p += incr;
2095
2096
    /* Second byte */
2097
0
    *p = (unsigned char)(bits & 0xFF);
2098
2099
0
    return 0;
2100
2101
0
  Overflow:
2102
0
    PyErr_SetString(PyExc_OverflowError,
2103
0
                    "float too large to pack with e format");
2104
0
    return -1;
2105
0
}
2106
2107
int
2108
PyFloat_Pack4(double x, char *data, int le)
2109
0
{
2110
0
    unsigned char *p = (unsigned char *)data;
2111
0
    if (float_format == unknown_format) {
2112
0
        unsigned char sign;
2113
0
        int e;
2114
0
        double f;
2115
0
        unsigned int fbits;
2116
0
        int incr = 1;
2117
2118
0
        if (le) {
2119
0
            p += 3;
2120
0
            incr = -1;
2121
0
        }
2122
2123
0
        if (x < 0) {
2124
0
            sign = 1;
2125
0
            x = -x;
2126
0
        }
2127
0
        else
2128
0
            sign = 0;
2129
2130
0
        f = frexp(x, &e);
2131
2132
        /* Normalize f to be in the range [1.0, 2.0) */
2133
0
        if (0.5 <= f && f < 1.0) {
2134
0
            f *= 2.0;
2135
0
            e--;
2136
0
        }
2137
0
        else if (f == 0.0)
2138
0
            e = 0;
2139
0
        else {
2140
0
            PyErr_SetString(PyExc_SystemError,
2141
0
                            "frexp() result out of range");
2142
0
            return -1;
2143
0
        }
2144
2145
0
        if (e >= 128)
2146
0
            goto Overflow;
2147
0
        else if (e < -126) {
2148
            /* Gradual underflow */
2149
0
            f = ldexp(f, 126 + e);
2150
0
            e = 0;
2151
0
        }
2152
0
        else if (!(e == 0 && f == 0.0)) {
2153
0
            e += 127;
2154
0
            f -= 1.0; /* Get rid of leading 1 */
2155
0
        }
2156
2157
0
        f *= 8388608.0; /* 2**23 */
2158
0
        fbits = (unsigned int)(f + 0.5); /* Round */
2159
0
        assert(fbits <= 8388608);
2160
0
        if (fbits >> 23) {
2161
            /* The carry propagated out of a string of 23 1 bits. */
2162
0
            fbits = 0;
2163
0
            ++e;
2164
0
            if (e >= 255)
2165
0
                goto Overflow;
2166
0
        }
2167
2168
        /* First byte */
2169
0
        *p = (sign << 7) | (e >> 1);
2170
0
        p += incr;
2171
2172
        /* Second byte */
2173
0
        *p = (char) (((e & 1) << 7) | (fbits >> 16));
2174
0
        p += incr;
2175
2176
        /* Third byte */
2177
0
        *p = (fbits >> 8) & 0xFF;
2178
0
        p += incr;
2179
2180
        /* Fourth byte */
2181
0
        *p = fbits & 0xFF;
2182
2183
        /* Done */
2184
0
        return 0;
2185
2186
0
    }
2187
0
    else {
2188
0
        float y = (float)x;
2189
0
        int i, incr = 1;
2190
2191
0
        if (isinf(y) && !isinf(x))
2192
0
            goto Overflow;
2193
2194
        /* correct y if x was a sNaN, transformed to qNaN by conversion */
2195
0
        if (isnan(x)) {
2196
0
            uint64_t v;
2197
2198
0
            memcpy(&v, &x, 8);
2199
0
#ifndef __riscv
2200
0
            if ((v & (1ULL << 51)) == 0) {
2201
0
                uint32_t u32;
2202
0
                memcpy(&u32, &y, 4);
2203
0
                u32 &= ~(1 << 22); /* make sNaN */
2204
0
                memcpy(&y, &u32, 4);
2205
0
            }
2206
#else
2207
            uint32_t u32;
2208
2209
            memcpy(&u32, &y, 4);
2210
            if ((v & (1ULL << 51)) == 0) {
2211
                u32 &= ~(1 << 22);
2212
            }
2213
            /* Workaround RISC-V: "If a NaN value is converted to a
2214
             * different floating-point type, the result is the
2215
             * canonical NaN of the new type".  The canonical NaN here
2216
             * is a positive qNaN with zero payload. */
2217
            if (v & (1ULL << 63)) {
2218
                u32 |= (1 << 31); /* set sign */
2219
            }
2220
            /* add payload */
2221
            u32 -= (u32 & 0x3fffff);
2222
            u32 += (uint32_t)((v & 0x7ffffffffffffULL) >> 29);
2223
2224
            memcpy(&y, &u32, 4);
2225
#endif
2226
0
        }
2227
2228
0
        unsigned char s[sizeof(float)];
2229
0
        memcpy(s, &y, sizeof(float));
2230
2231
0
        if ((float_format == ieee_little_endian_format && !le)
2232
0
            || (float_format == ieee_big_endian_format && le)) {
2233
0
            p += 3;
2234
0
            incr = -1;
2235
0
        }
2236
2237
0
        for (i = 0; i < 4; i++) {
2238
0
            *p = s[i];
2239
0
            p += incr;
2240
0
        }
2241
0
        return 0;
2242
0
    }
2243
0
  Overflow:
2244
0
    PyErr_SetString(PyExc_OverflowError,
2245
0
                    "float too large to pack with f format");
2246
0
    return -1;
2247
0
}
2248
2249
int
2250
PyFloat_Pack8(double x, char *data, int le)
2251
41
{
2252
41
    unsigned char *p = (unsigned char *)data;
2253
41
    if (double_format == unknown_format) {
2254
0
        unsigned char sign;
2255
0
        int e;
2256
0
        double f;
2257
0
        unsigned int fhi, flo;
2258
0
        int incr = 1;
2259
2260
0
        if (le) {
2261
0
            p += 7;
2262
0
            incr = -1;
2263
0
        }
2264
2265
0
        if (x < 0) {
2266
0
            sign = 1;
2267
0
            x = -x;
2268
0
        }
2269
0
        else
2270
0
            sign = 0;
2271
2272
0
        f = frexp(x, &e);
2273
2274
        /* Normalize f to be in the range [1.0, 2.0) */
2275
0
        if (0.5 <= f && f < 1.0) {
2276
0
            f *= 2.0;
2277
0
            e--;
2278
0
        }
2279
0
        else if (f == 0.0)
2280
0
            e = 0;
2281
0
        else {
2282
0
            PyErr_SetString(PyExc_SystemError,
2283
0
                            "frexp() result out of range");
2284
0
            return -1;
2285
0
        }
2286
2287
0
        if (e >= 1024)
2288
0
            goto Overflow;
2289
0
        else if (e < -1022) {
2290
            /* Gradual underflow */
2291
0
            f = ldexp(f, 1022 + e);
2292
0
            e = 0;
2293
0
        }
2294
0
        else if (!(e == 0 && f == 0.0)) {
2295
0
            e += 1023;
2296
0
            f -= 1.0; /* Get rid of leading 1 */
2297
0
        }
2298
2299
        /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2300
0
        f *= 268435456.0; /* 2**28 */
2301
0
        fhi = (unsigned int)f; /* Truncate */
2302
0
        assert(fhi < 268435456);
2303
2304
0
        f -= (double)fhi;
2305
0
        f *= 16777216.0; /* 2**24 */
2306
0
        flo = (unsigned int)(f + 0.5); /* Round */
2307
0
        assert(flo <= 16777216);
2308
0
        if (flo >> 24) {
2309
            /* The carry propagated out of a string of 24 1 bits. */
2310
0
            flo = 0;
2311
0
            ++fhi;
2312
0
            if (fhi >> 28) {
2313
                /* And it also propagated out of the next 28 bits. */
2314
0
                fhi = 0;
2315
0
                ++e;
2316
0
                if (e >= 2047)
2317
0
                    goto Overflow;
2318
0
            }
2319
0
        }
2320
2321
        /* First byte */
2322
0
        *p = (sign << 7) | (e >> 4);
2323
0
        p += incr;
2324
2325
        /* Second byte */
2326
0
        *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2327
0
        p += incr;
2328
2329
        /* Third byte */
2330
0
        *p = (fhi >> 16) & 0xFF;
2331
0
        p += incr;
2332
2333
        /* Fourth byte */
2334
0
        *p = (fhi >> 8) & 0xFF;
2335
0
        p += incr;
2336
2337
        /* Fifth byte */
2338
0
        *p = fhi & 0xFF;
2339
0
        p += incr;
2340
2341
        /* Sixth byte */
2342
0
        *p = (flo >> 16) & 0xFF;
2343
0
        p += incr;
2344
2345
        /* Seventh byte */
2346
0
        *p = (flo >> 8) & 0xFF;
2347
0
        p += incr;
2348
2349
        /* Eighth byte */
2350
0
        *p = flo & 0xFF;
2351
        /* p += incr; */
2352
2353
        /* Done */
2354
0
        return 0;
2355
2356
0
      Overflow:
2357
0
        PyErr_SetString(PyExc_OverflowError,
2358
0
                        "float too large to pack with d format");
2359
0
        return -1;
2360
0
    }
2361
41
    else {
2362
41
        unsigned char as_bytes[8];
2363
41
        memcpy(as_bytes, &x, 8);
2364
41
        const unsigned char *s = as_bytes;
2365
41
        int i, incr = 1;
2366
2367
41
        if ((double_format == ieee_little_endian_format && !le)
2368
41
            || (double_format == ieee_big_endian_format && le)) {
2369
0
            p += 7;
2370
0
            incr = -1;
2371
0
        }
2372
2373
369
        for (i = 0; i < 8; i++) {
2374
328
            *p = *s++;
2375
328
            p += incr;
2376
328
        }
2377
41
        return 0;
2378
41
    }
2379
41
}
2380
2381
double
2382
PyFloat_Unpack2(const char *data, int le)
2383
0
{
2384
0
    unsigned char *p = (unsigned char *)data;
2385
0
    unsigned char sign;
2386
0
    int e;
2387
0
    unsigned int f;
2388
0
    double x;
2389
0
    int incr = 1;
2390
2391
0
    if (le) {
2392
0
        p += 1;
2393
0
        incr = -1;
2394
0
    }
2395
2396
    /* First byte */
2397
0
    sign = (*p >> 7) & 1;
2398
0
    e = (*p & 0x7C) >> 2;
2399
0
    f = (*p & 0x03) << 8;
2400
0
    p += incr;
2401
2402
    /* Second byte */
2403
0
    f |= *p;
2404
2405
0
    if (e == 0x1f) {
2406
0
        if (f == 0) {
2407
            /* Infinity */
2408
0
            return sign ? -Py_INFINITY : Py_INFINITY;
2409
0
        }
2410
0
        else {
2411
            /* NaN */
2412
0
            uint64_t v = sign ? 0xfff0000000000000ULL : 0x7ff0000000000000ULL;
2413
2414
0
            v += (uint64_t)f << 42; /* add NaN's type & payload */
2415
0
            memcpy(&x, &v, sizeof(v));
2416
0
            return x;
2417
0
        }
2418
0
    }
2419
2420
0
    x = (double)f / 1024.0;
2421
2422
0
    if (e == 0) {
2423
0
        e = -14;
2424
0
    }
2425
0
    else {
2426
0
        x += 1.0;
2427
0
        e -= 15;
2428
0
    }
2429
0
    x = ldexp(x, e);
2430
2431
0
    if (sign)
2432
0
        x = -x;
2433
2434
0
    return x;
2435
0
}
2436
2437
double
2438
PyFloat_Unpack4(const char *data, int le)
2439
0
{
2440
0
    unsigned char *p = (unsigned char *)data;
2441
0
    if (float_format == unknown_format) {
2442
0
        unsigned char sign;
2443
0
        int e;
2444
0
        unsigned int f;
2445
0
        double x;
2446
0
        int incr = 1;
2447
2448
0
        if (le) {
2449
0
            p += 3;
2450
0
            incr = -1;
2451
0
        }
2452
2453
        /* First byte */
2454
0
        sign = (*p >> 7) & 1;
2455
0
        e = (*p & 0x7F) << 1;
2456
0
        p += incr;
2457
2458
        /* Second byte */
2459
0
        e |= (*p >> 7) & 1;
2460
0
        f = (*p & 0x7F) << 16;
2461
0
        p += incr;
2462
2463
0
        if (e == 255) {
2464
0
            PyErr_SetString(
2465
0
                PyExc_ValueError,
2466
0
                "can't unpack IEEE 754 special value "
2467
0
                "on non-IEEE platform");
2468
0
            return -1;
2469
0
        }
2470
2471
        /* Third byte */
2472
0
        f |= *p << 8;
2473
0
        p += incr;
2474
2475
        /* Fourth byte */
2476
0
        f |= *p;
2477
2478
0
        x = (double)f / 8388608.0;
2479
2480
        /* XXX This sadly ignores Inf/NaN issues */
2481
0
        if (e == 0)
2482
0
            e = -126;
2483
0
        else {
2484
0
            x += 1.0;
2485
0
            e -= 127;
2486
0
        }
2487
0
        x = ldexp(x, e);
2488
2489
0
        if (sign)
2490
0
            x = -x;
2491
2492
0
        return x;
2493
0
    }
2494
0
    else {
2495
0
        float x;
2496
2497
0
        if ((float_format == ieee_little_endian_format && !le)
2498
0
            || (float_format == ieee_big_endian_format && le)) {
2499
0
            char buf[4];
2500
0
            char *d = &buf[3];
2501
0
            int i;
2502
2503
0
            for (i = 0; i < 4; i++) {
2504
0
                *d-- = *p++;
2505
0
            }
2506
0
            memcpy(&x, buf, 4);
2507
0
        }
2508
0
        else {
2509
0
            memcpy(&x, p, 4);
2510
0
        }
2511
2512
        /* return sNaN double if x was sNaN float */
2513
0
        if (isnan(x)) {
2514
0
            uint32_t v;
2515
0
            memcpy(&v, &x, 4);
2516
2517
0
#ifndef __riscv
2518
0
            if ((v & (1 << 22)) == 0) {
2519
0
                double y = x; /* will make qNaN double */
2520
0
                uint64_t u64;
2521
0
                memcpy(&u64, &y, 8);
2522
0
                u64 &= ~(1ULL << 51); /* make sNaN */
2523
0
                memcpy(&y, &u64, 8);
2524
0
                return y;
2525
0
            }
2526
#else
2527
            double y = x;
2528
            uint64_t u64;
2529
2530
            memcpy(&u64, &y, 8);
2531
            if ((v & (1 << 22)) == 0) {
2532
                u64 &= ~(1ULL << 51);
2533
            }
2534
            /* Workaround RISC-V, see PyFloat_Pack4() */
2535
            if (v & (1 << 31)) {
2536
                u64 |= (1ULL << 63); /* set sign */
2537
            }
2538
            /* add payload */
2539
            u64 -= (u64 & 0x7ffffffffffffULL);
2540
            u64 += ((v & 0x3fffffULL) << 29);
2541
2542
            memcpy(&y, &u64, 8);
2543
            return y;
2544
#endif
2545
0
        }
2546
2547
0
        return x;
2548
0
    }
2549
0
}
2550
2551
double
2552
PyFloat_Unpack8(const char *data, int le)
2553
41
{
2554
41
    unsigned char *p = (unsigned char *)data;
2555
41
    if (double_format == unknown_format) {
2556
0
        unsigned char sign;
2557
0
        int e;
2558
0
        unsigned int fhi, flo;
2559
0
        double x;
2560
0
        int incr = 1;
2561
2562
0
        if (le) {
2563
0
            p += 7;
2564
0
            incr = -1;
2565
0
        }
2566
2567
        /* First byte */
2568
0
        sign = (*p >> 7) & 1;
2569
0
        e = (*p & 0x7F) << 4;
2570
2571
0
        p += incr;
2572
2573
        /* Second byte */
2574
0
        e |= (*p >> 4) & 0xF;
2575
0
        fhi = (*p & 0xF) << 24;
2576
0
        p += incr;
2577
2578
0
        if (e == 2047) {
2579
0
            PyErr_SetString(
2580
0
                PyExc_ValueError,
2581
0
                "can't unpack IEEE 754 special value "
2582
0
                "on non-IEEE platform");
2583
0
            return -1.0;
2584
0
        }
2585
2586
        /* Third byte */
2587
0
        fhi |= *p << 16;
2588
0
        p += incr;
2589
2590
        /* Fourth byte */
2591
0
        fhi |= *p  << 8;
2592
0
        p += incr;
2593
2594
        /* Fifth byte */
2595
0
        fhi |= *p;
2596
0
        p += incr;
2597
2598
        /* Sixth byte */
2599
0
        flo = *p << 16;
2600
0
        p += incr;
2601
2602
        /* Seventh byte */
2603
0
        flo |= *p << 8;
2604
0
        p += incr;
2605
2606
        /* Eighth byte */
2607
0
        flo |= *p;
2608
2609
0
        x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2610
0
        x /= 268435456.0; /* 2**28 */
2611
2612
0
        if (e == 0)
2613
0
            e = -1022;
2614
0
        else {
2615
0
            x += 1.0;
2616
0
            e -= 1023;
2617
0
        }
2618
0
        x = ldexp(x, e);
2619
2620
0
        if (sign)
2621
0
            x = -x;
2622
2623
0
        return x;
2624
0
    }
2625
41
    else {
2626
41
        double x;
2627
2628
41
        if ((double_format == ieee_little_endian_format && !le)
2629
41
            || (double_format == ieee_big_endian_format && le)) {
2630
0
            char buf[8];
2631
0
            char *d = &buf[7];
2632
0
            int i;
2633
2634
0
            for (i = 0; i < 8; i++) {
2635
0
                *d-- = *p++;
2636
0
            }
2637
0
            memcpy(&x, buf, 8);
2638
0
        }
2639
41
        else {
2640
41
            memcpy(&x, p, 8);
2641
41
        }
2642
2643
41
        return x;
2644
41
    }
2645
41
}