Coverage Report

Created: 2025-10-12 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
22
{
84
22
    PyObject* floatinfo;
85
22
    int pos = 0;
86
87
22
    floatinfo = PyStructSequence_New(&FloatInfoType);
88
22
    if (floatinfo == NULL) {
89
0
        return NULL;
90
0
    }
91
92
22
#define SetFlag(CALL) \
93
242
    do {                                                    \
94
242
        PyObject *flag = (CALL);                            \
95
242
        if (flag == NULL) {                                 \
96
0
            Py_CLEAR(floatinfo);                            \
97
0
            return NULL;                                    \
98
0
        }                                                   \
99
242
        PyStructSequence_SET_ITEM(floatinfo, pos++, flag);  \
100
242
    } while (0)
101
102
176
#define SetIntFlag(FLAG) SetFlag(PyLong_FromLong((FLAG)))
103
66
#define SetDblFlag(FLAG) SetFlag(PyFloat_FromDouble((FLAG)))
104
105
22
    SetDblFlag(DBL_MAX);
106
22
    SetIntFlag(DBL_MAX_EXP);
107
22
    SetIntFlag(DBL_MAX_10_EXP);
108
22
    SetDblFlag(DBL_MIN);
109
22
    SetIntFlag(DBL_MIN_EXP);
110
22
    SetIntFlag(DBL_MIN_10_EXP);
111
22
    SetIntFlag(DBL_DIG);
112
22
    SetIntFlag(DBL_MANT_DIG);
113
22
    SetDblFlag(DBL_EPSILON);
114
22
    SetIntFlag(FLT_RADIX);
115
22
    SetIntFlag(FLT_ROUNDS);
116
22
#undef SetIntFlag
117
22
#undef SetDblFlag
118
22
#undef SetFlag
119
120
22
    return floatinfo;
121
22
}
122
123
PyObject *
124
PyFloat_FromDouble(double fval)
125
391k
{
126
391k
    PyFloatObject *op = _Py_FREELIST_POP(PyFloatObject, floats);
127
391k
    if (op == NULL) {
128
177k
        op = PyObject_Malloc(sizeof(PyFloatObject));
129
177k
        if (!op) {
130
0
            return PyErr_NoMemory();
131
0
        }
132
177k
        _PyObject_Init((PyObject*)op, &PyFloat_Type);
133
177k
    }
134
391k
    op->ob_fval = fval;
135
391k
    return (PyObject *) op;
136
391k
}
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
77.9k
{
148
77.9k
    double x;
149
77.9k
    const char *end;
150
77.9k
    const char *last = s + len;
151
    /* strip leading whitespace */
152
78.9k
    while (s < last && Py_ISSPACE(*s)) {
153
980
        s++;
154
980
    }
155
77.9k
    if (s == last) {
156
32
        PyErr_Format(PyExc_ValueError,
157
32
                     "could not convert string to float: "
158
32
                     "%R", obj);
159
32
        return NULL;
160
32
    }
161
162
    /* strip trailing whitespace */
163
78.3k
    while (s < last - 1 && Py_ISSPACE(last[-1])) {
164
473
        last--;
165
473
    }
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
77.9k
    x = PyOS_string_to_double(s, (char **)&end, NULL);
171
77.9k
    if (end != last) {
172
1.78k
        PyErr_Format(PyExc_ValueError,
173
1.78k
                     "could not convert string to float: "
174
1.78k
                     "%R", obj);
175
1.78k
        return NULL;
176
1.78k
    }
177
76.1k
    else if (x == -1.0 && PyErr_Occurred()) {
178
0
        return NULL;
179
0
    }
180
76.1k
    else {
181
76.1k
        return PyFloat_FromDouble(x);
182
76.1k
    }
183
77.9k
}
184
185
PyObject *
186
PyFloat_FromString(PyObject *v)
187
78.0k
{
188
78.0k
    const char *s;
189
78.0k
    PyObject *s_buffer = NULL;
190
78.0k
    Py_ssize_t len;
191
78.0k
    Py_buffer view = {NULL, NULL};
192
78.0k
    PyObject *result = NULL;
193
194
78.0k
    if (PyUnicode_Check(v)) {
195
4
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
196
4
        if (s_buffer == NULL)
197
0
            return NULL;
198
4
        assert(PyUnicode_IS_ASCII(s_buffer));
199
        /* Simply get a pointer to existing ASCII characters. */
200
4
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
201
4
        assert(s != NULL);
202
4
    }
203
78.0k
    else if (PyBytes_Check(v)) {
204
78.0k
        s = PyBytes_AS_STRING(v);
205
78.0k
        len = PyBytes_GET_SIZE(v);
206
78.0k
    }
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
78.0k
    result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
229
78.0k
                                                   float_from_string_inner);
230
78.0k
    PyBuffer_Release(&view);
231
78.0k
    Py_XDECREF(s_buffer);
232
78.0k
    return result;
233
78.0k
}
234
235
void
236
_PyFloat_ExactDealloc(PyObject *obj)
237
391k
{
238
391k
    assert(PyFloat_CheckExact(obj));
239
391k
    _Py_FREELIST_FREE(floats, obj, PyObject_Free);
240
391k
}
241
242
static void
243
float_dealloc(PyObject *op)
244
391k
{
245
391k
    assert(PyFloat_Check(op));
246
391k
    if (PyFloat_CheckExact(op))
247
391k
        _PyFloat_ExactDealloc(op);
248
0
    else
249
0
        Py_TYPE(op)->tp_free(op);
250
391k
}
251
252
double
253
PyFloat_AsDouble(PyObject *op)
254
120
{
255
120
    PyNumberMethods *nb;
256
120
    PyObject *res;
257
120
    double val;
258
259
120
    if (op == NULL) {
260
0
        PyErr_BadArgument();
261
0
        return -1;
262
0
    }
263
264
120
    if (PyFloat_Check(op)) {
265
120
        return PyFloat_AS_DOUBLE(op);
266
120
    }
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
139k
    if (PyFloat_Check(obj))                                 \
319
139k
        dbl = PyFloat_AS_DOUBLE(obj);                       \
320
139k
    else if (_Py_convert_int_to_double(&(obj), &(dbl)) < 0) \
321
68.0k
        return obj;
322
323
/* Methods */
324
325
int
326
_Py_convert_int_to_double(PyObject **v, double *dbl)
327
111k
{
328
111k
    PyObject *obj = *v;
329
330
111k
    if (PyLong_Check(obj)) {
331
102k
        *dbl = PyLong_AsDouble(obj);
332
102k
        if (*dbl == -1.0 && PyErr_Occurred()) {
333
557
            *v = NULL;
334
557
            return -1;
335
557
        }
336
102k
    }
337
9.59k
    else {
338
9.59k
        *v = Py_NewRef(Py_NotImplemented);
339
9.59k
        return -1;
340
9.59k
    }
341
101k
    return 0;
342
111k
}
343
344
static PyObject *
345
float_repr(PyObject *op)
346
33.7k
{
347
33.7k
    PyFloatObject *v = _PyFloat_CAST(op);
348
0
    PyObject *result;
349
33.7k
    char *buf;
350
351
33.7k
    buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
352
33.7k
                                'r', 0,
353
33.7k
                                Py_DTSF_ADD_DOT_0,
354
33.7k
                                NULL);
355
33.7k
    if (!buf)
356
0
        return PyErr_NoMemory();
357
33.7k
    result = _PyUnicode_FromASCII(buf, strlen(buf));
358
33.7k
    PyMem_Free(buf);
359
33.7k
    return result;
360
33.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
136k
{
380
136k
    double i, j;
381
136k
    int r = 0;
382
383
136k
    assert(PyFloat_Check(v));
384
136k
    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
136k
    if (PyFloat_Check(w))
390
132k
        j = PyFloat_AS_DOUBLE(w);
391
392
3.68k
    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
3.68k
    else if (PyLong_Check(w)) {
404
3.55k
        int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
405
3.55k
        int wsign;
406
3.55k
        int exponent;
407
408
3.55k
        (void)PyLong_GetSign(w, &wsign);
409
3.55k
        if (vsign != wsign) {
410
            /* Magnitudes are irrelevant -- the signs alone
411
             * determine the outcome.
412
             */
413
98
            i = (double)vsign;
414
98
            j = (double)wsign;
415
98
            goto Compare;
416
98
        }
417
        /* The signs are the same. */
418
        /* Convert w to a double if it fits.  In particular, 0 fits. */
419
3.45k
        int64_t nbits64 = _PyLong_NumBits(w);
420
3.45k
        assert(nbits64 >= 0);
421
3.45k
        assert(!PyErr_Occurred());
422
3.45k
        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
3.45k
        int nbits = (int)nbits64;
435
3.45k
        if (nbits <= 48) {
436
3.00k
            j = PyLong_AsDouble(w);
437
            /* It's impossible that <= 48 bits overflowed. */
438
3.00k
            assert(j != -1.0 || ! PyErr_Occurred());
439
3.00k
            goto Compare;
440
3.00k
        }
441
3.45k
        assert(wsign != 0); /* else nbits was 0 */
442
449
        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
449
        if (vsign < 0) {
447
            /* "Multiply both sides" by -1; this also swaps the
448
             * comparator.
449
             */
450
329
            i = -i;
451
329
            op = _Py_SwappedOp[op];
452
329
        }
453
449
        assert(i > 0.0);
454
449
        (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
449
        if (exponent < nbits) {
459
181
            i = 1.0;
460
181
            j = 2.0;
461
181
            goto Compare;
462
181
        }
463
268
        if (exponent > nbits) {
464
45
            i = 2.0;
465
45
            j = 1.0;
466
45
            goto Compare;
467
45
        }
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
223
        {
473
223
            double fracpart;
474
223
            double intpart;
475
223
            PyObject *result = NULL;
476
223
            PyObject *vv = NULL;
477
223
            PyObject *ww = w;
478
479
223
            if (wsign < 0) {
480
103
                ww = PyNumber_Negative(w);
481
103
                if (ww == NULL)
482
0
                    goto Error;
483
103
            }
484
120
            else
485
120
                Py_INCREF(ww);
486
487
223
            fracpart = modf(i, &intpart);
488
223
            vv = PyLong_FromDouble(intpart);
489
223
            if (vv == NULL)
490
0
                goto Error;
491
492
223
            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
223
            r = PyObject_RichCompareBool(vv, ww, op);
515
223
            if (r < 0)
516
0
                goto Error;
517
223
            result = PyBool_FromLong(r);
518
223
         Error:
519
223
            Py_XDECREF(vv);
520
223
            Py_XDECREF(ww);
521
223
            return result;
522
223
        }
523
223
    } /* else if (PyLong_Check(w)) */
524
525
133
    else        /* w isn't float or int */
526
133
        goto Unimplemented;
527
528
136k
 Compare:
529
136k
    switch (op) {
530
136k
    case Py_EQ:
531
136k
        r = i == j;
532
136k
        break;
533
225
    case Py_NE:
534
225
        r = i != j;
535
225
        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
0
    case Py_GT:
546
0
        r = i > j;
547
0
        break;
548
136k
    }
549
136k
    return PyBool_FromLong(r);
550
551
133
 Unimplemented:
552
133
    Py_RETURN_NOTIMPLEMENTED;
553
136k
}
554
555
static Py_hash_t
556
float_hash(PyObject *op)
557
237M
{
558
237M
    PyFloatObject *v = _PyFloat_CAST(op);
559
0
    return _Py_HashDouble(op, v->ob_fval);
560
237M
}
561
562
static PyObject *
563
float_add(PyObject *v, PyObject *w)
564
7.50k
{
565
7.50k
    double a,b;
566
7.50k
    CONVERT_TO_DOUBLE(v, a);
567
7.03k
    CONVERT_TO_DOUBLE(w, b);
568
6.53k
    a = a + b;
569
6.53k
    return PyFloat_FromDouble(a);
570
7.03k
}
571
572
static PyObject *
573
float_sub(PyObject *v, PyObject *w)
574
13.9k
{
575
13.9k
    double a,b;
576
13.9k
    CONVERT_TO_DOUBLE(v, a);
577
13.8k
    CONVERT_TO_DOUBLE(w, b);
578
13.6k
    a = a - b;
579
13.6k
    return PyFloat_FromDouble(a);
580
13.8k
}
581
582
static PyObject *
583
float_mul(PyObject *v, PyObject *w)
584
9.11k
{
585
9.11k
    double a,b;
586
9.11k
    CONVERT_TO_DOUBLE(v, a);
587
8.43k
    CONVERT_TO_DOUBLE(w, b);
588
8.10k
    a = a * b;
589
8.10k
    return PyFloat_FromDouble(a);
590
8.43k
}
591
592
static PyObject *
593
float_div(PyObject *v, PyObject *w)
594
13.7k
{
595
13.7k
    double a,b;
596
13.7k
    CONVERT_TO_DOUBLE(v, a);
597
13.6k
    CONVERT_TO_DOUBLE(w, b);
598
12.1k
    if (b == 0.0) {
599
889
        PyErr_SetString(PyExc_ZeroDivisionError,
600
889
                        "division by zero");
601
889
        return NULL;
602
889
    }
603
11.2k
    a = a / b;
604
11.2k
    return PyFloat_FromDouble(a);
605
12.1k
}
606
607
static PyObject *
608
float_rem(PyObject *v, PyObject *w)
609
7.25k
{
610
7.25k
    double vx, wx;
611
7.25k
    double mod;
612
7.25k
    CONVERT_TO_DOUBLE(v, vx);
613
6.21k
    CONVERT_TO_DOUBLE(w, wx);
614
6.08k
    if (wx == 0.0) {
615
608
        PyErr_SetString(PyExc_ZeroDivisionError,
616
608
                        "division by zero");
617
608
        return NULL;
618
608
    }
619
5.47k
    mod = fmod(vx, wx);
620
5.47k
    if (mod) {
621
        /* ensure the remainder has the same sign as the denominator */
622
3.66k
        if ((wx < 0) != (mod < 0)) {
623
1.01k
            mod += wx;
624
1.01k
        }
625
3.66k
    }
626
1.81k
    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
1.81k
        mod = copysign(0.0, wx);
631
1.81k
    }
632
5.47k
    return PyFloat_FromDouble(mod);
633
6.08k
}
634
635
static void
636
_float_div_mod(double vx, double wx, double *floordiv, double *mod)
637
4.13k
{
638
4.13k
    double div;
639
4.13k
    *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
4.13k
    div = (vx - *mod) / wx;
647
4.13k
    if (*mod) {
648
        /* ensure the remainder has the same sign as the denominator */
649
2.64k
        if ((wx < 0) != (*mod < 0)) {
650
1.05k
            *mod += wx;
651
1.05k
            div -= 1.0;
652
1.05k
        }
653
2.64k
    }
654
1.48k
    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
1.48k
        *mod = copysign(0.0, wx);
659
1.48k
    }
660
    /* snap quotient to nearest integral value */
661
4.13k
    if (div) {
662
2.23k
        *floordiv = floor(div);
663
2.23k
        if (div - *floordiv > 0.5) {
664
252
            *floordiv += 1.0;
665
252
        }
666
2.23k
    }
667
1.89k
    else {
668
        /* div is zero - get the same sign as the true quotient */
669
1.89k
        *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
670
1.89k
    }
671
4.13k
}
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
4.88k
{
691
4.88k
    double vx, wx;
692
4.88k
    double mod, floordiv;
693
4.88k
    CONVERT_TO_DOUBLE(v, vx);
694
4.53k
    CONVERT_TO_DOUBLE(w, wx);
695
4.48k
    if (wx == 0.0) {
696
355
        PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
697
355
        return NULL;
698
355
    }
699
4.13k
    _float_div_mod(vx, wx, &floordiv, &mod);
700
4.13k
    return PyFloat_FromDouble(floordiv);
701
4.48k
}
702
703
/* determine whether x is an odd integer or not;  assumes that
704
   x is not an infinity or nan. */
705
3.28k
#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
14.9k
{
710
14.9k
    double iv, iw, ix;
711
14.9k
    int negate_result = 0;
712
713
14.9k
    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
14.9k
    CONVERT_TO_DOUBLE(v, iv);
720
14.8k
    CONVERT_TO_DOUBLE(w, iw);
721
722
    /* Sort out special cases here instead of relying on pow() */
723
13.1k
    if (iw == 0) {              /* v**0 is 1, even 0**0 */
724
922
        return PyFloat_FromDouble(1.0);
725
922
    }
726
12.1k
    if (isnan(iv)) {        /* nan**w = nan, unless w == 0 */
727
1
        return PyFloat_FromDouble(iv);
728
1
    }
729
12.1k
    if (isnan(iw)) {        /* v**nan = nan, unless v == 1; 1**nan = 1 */
730
13
        return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
731
13
    }
732
12.1k
    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
947
        iv = fabs(iv);
740
947
        if (iv == 1.0)
741
73
            return PyFloat_FromDouble(1.0);
742
874
        else if ((iw > 0.0) == (iv > 1.0))
743
647
            return PyFloat_FromDouble(fabs(iw)); /* return inf */
744
227
        else
745
227
            return PyFloat_FromDouble(0.0);
746
947
    }
747
11.2k
    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
1.36k
        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
753
1.36k
        if (iw > 0.0)
754
1.03k
            return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
755
338
        else
756
338
            return PyFloat_FromDouble(iw_is_odd ?
757
193
                                      copysign(0.0, iv) : 0.0);
758
1.36k
    }
759
9.86k
    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
1.72k
        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
763
1.72k
        if (iw < 0.0) {
764
415
            PyErr_SetString(PyExc_ZeroDivisionError,
765
415
                            "zero to a negative power");
766
415
            return NULL;
767
415
        }
768
        /* use correct sign if iw is odd */
769
1.31k
        return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
770
1.72k
    }
771
772
8.14k
    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
255
        if (iw != floor(iw)) {
777
            /* Negative numbers raised to fractional powers
778
             * become complex.
779
             */
780
68
            return PyComplex_Type.tp_as_number->nb_power(v, w, z);
781
68
        }
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
187
        iv = -iv;
787
187
        negate_result = DOUBLE_IS_ODD_INTEGER(iw);
788
187
    }
789
790
8.07k
    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
1.57k
        return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
803
1.57k
    }
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
8.07k
    errno = 0;
810
6.49k
    ix = pow(iv, iw);
811
6.49k
    _Py_ADJUST_ERANGE1(ix);
812
6.49k
    if (negate_result)
813
49
        ix = -ix;
814
815
6.49k
    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
1.76k
        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
820
1.76k
                             PyExc_ValueError);
821
1.76k
        return NULL;
822
1.76k
    }
823
4.73k
    return PyFloat_FromDouble(ix);
824
6.49k
}
825
826
#undef DOUBLE_IS_ODD_INTEGER
827
828
static PyObject *
829
float_neg(PyObject *op)
830
7.37k
{
831
7.37k
    PyFloatObject *v = _PyFloat_CAST(op);
832
0
    return PyFloat_FromDouble(-v->ob_fval);
833
7.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
132
{
845
132
    PyFloatObject *v = _PyFloat_CAST(op);
846
0
    return v->ob_fval != 0.0;
847
132
}
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
345
{
886
345
    return PyLong_FromDouble(PyFloat_AS_DOUBLE(self));
887
345
}
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
2.80k
{
1092
2.80k
    if (PyFloat_CheckExact(v)) {
1093
2.80k
        return Py_NewRef(v);
1094
2.80k
    }
1095
0
    else {
1096
0
        return PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1097
0
    }
1098
2.80k
}
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
128
hex_from_char(unsigned char c) {
1154
128
    return _CHAR_TO_HEX[c];
1155
128
}
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
4
{
1249
4
    PyObject *result;
1250
4
    double x;
1251
4
    long exp, top_exp, lsb, key_digit;
1252
4
    const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1253
4
    int half_eps, digit, round_up, negate=0;
1254
4
    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
4
    s = PyUnicode_AsUTF8AndSize(string, &length);
1302
4
    if (s == NULL)
1303
0
        return NULL;
1304
4
    s_end = s + length;
1305
1306
    /********************
1307
     * Parse the string *
1308
     ********************/
1309
1310
    /* leading whitespace */
1311
4
    while (Py_ISSPACE(*s))
1312
0
        s++;
1313
1314
    /* infinities and nans */
1315
4
    x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
1316
4
    if (coeff_end != s) {
1317
0
        s = coeff_end;
1318
0
        goto finished;
1319
0
    }
1320
1321
    /* optional sign */
1322
4
    if (*s == '-') {
1323
0
        s++;
1324
0
        negate = 1;
1325
0
    }
1326
4
    else if (*s == '+')
1327
0
        s++;
1328
1329
    /* [0x] */
1330
4
    s_store = s;
1331
4
    if (*s == '0') {
1332
4
        s++;
1333
4
        if (*s == 'x' || *s == 'X')
1334
4
            s++;
1335
0
        else
1336
0
            s = s_store;
1337
4
    }
1338
1339
    /* coefficient: <integer> [. <fraction>] */
1340
4
    coeff_start = s;
1341
8
    while (hex_from_char(*s) >= 0)
1342
4
        s++;
1343
4
    s_store = s;
1344
4
    if (*s == '.') {
1345
4
        s++;
1346
56
        while (hex_from_char(*s) >= 0)
1347
52
            s++;
1348
4
        coeff_end = s-1;
1349
4
    }
1350
0
    else
1351
0
        coeff_end = s;
1352
1353
    /* ndigits = total # of hex digits; fdigits = # after point */
1354
4
    ndigits = coeff_end - coeff_start;
1355
4
    fdigits = coeff_end - s_store;
1356
4
    if (ndigits == 0)
1357
0
        goto parse_error;
1358
4
    if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1359
4
                         LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1360
0
        goto insane_length_error;
1361
1362
    /* [p <exponent>] */
1363
4
    if (*s == 'p' || *s == 'P') {
1364
4
        s++;
1365
4
        exp_start = s;
1366
4
        if (*s == '-' || *s == '+')
1367
4
            s++;
1368
4
        if (!('0' <= *s && *s <= '9'))
1369
0
            goto parse_error;
1370
4
        s++;
1371
4
        while ('0' <= *s && *s <= '9')
1372
0
            s++;
1373
4
        exp = strtol(exp_start, NULL, 10);
1374
4
    }
1375
0
    else
1376
0
        exp = 0;
1377
1378
/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1379
64
#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ?            \
1380
64
                     coeff_end-(j) :                                    \
1381
64
                     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
4
    while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1389
0
        ndigits--;
1390
4
    if (ndigits == 0 || exp < LONG_MIN/2) {
1391
0
        x = 0.0;
1392
0
        goto finished;
1393
0
    }
1394
4
    if (exp > LONG_MAX/2)
1395
0
        goto overflow_error;
1396
1397
    /* Adjust exponent for fractional part. */
1398
4
    exp = exp - 4*((long)fdigits);
1399
1400
    /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1401
4
    top_exp = exp + 4*((long)ndigits - 1);
1402
8
    for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1403
4
        top_exp++;
1404
1405
    /* catch almost all nonextreme cases of overflow and underflow here */
1406
4
    if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1407
0
        x = 0.0;
1408
0
        goto finished;
1409
0
    }
1410
4
    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
4
    lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1416
1417
4
    x = 0.0;
1418
4
    if (exp >= lsb) {
1419
        /* no rounding required */
1420
60
        for (i = ndigits-1; i >= 0; i--)
1421
56
            x = 16.0*x + HEX_DIGIT(i);
1422
4
        x = ldexp(x, (int)(exp));
1423
4
        goto finished;
1424
4
    }
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
4
  finished:
1459
    /* optional trailing whitespace leading to the end of the string */
1460
4
    while (Py_ISSPACE(*s))
1461
0
        s++;
1462
4
    if (s != s_end)
1463
0
        goto parse_error;
1464
4
    result = PyFloat_FromDouble(negate ? -x : x);
1465
4
    if (type != &PyFloat_Type && result != NULL) {
1466
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
1467
0
    }
1468
4
    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
4
}
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
4
{
1590
4
    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
4
    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
4
    if (PyUnicode_CheckExact(x))
1603
4
        return PyFloat_FromString(x);
1604
0
    return PyNumber_Float(x);
1605
4
}
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
4
{
1636
4
    if (!_PyArg_NoKwnames("float", kwnames)) {
1637
0
        return NULL;
1638
0
    }
1639
1640
4
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1641
4
    if (!_PyArg_CheckPositional("float", nargs, 0, 1)) {
1642
0
        return NULL;
1643
0
    }
1644
1645
4
    PyObject *x = nargs >= 1 ? args[0] : NULL;
1646
4
    return float_new_impl(_PyType_CAST(type), x);
1647
4
}
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
5.90k
#define unknown_format _py_float_format_unknown
1694
2.14k
#define ieee_big_endian_format _py_float_format_ieee_big_endian
1695
11.8k
#define ieee_little_endian_format _py_float_format_ieee_little_endian
1696
1697
7.94k
#define float_format (_PyRuntime.float_state.float_format)
1698
4.97k
#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
22
{
1906
22
    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
22
#if SIZEOF_DOUBLE == 8
1924
22
    {
1925
22
        double x = 9006104071832581.0;
1926
22
        if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1927
0
            detected_double_format = ieee_big_endian_format;
1928
22
        else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1929
22
            detected_double_format = ieee_little_endian_format;
1930
0
        else
1931
0
            detected_double_format = unknown_format;
1932
22
    }
1933
#else
1934
    detected_double_format = unknown_format;
1935
#endif
1936
1937
22
#if SIZEOF_FLOAT == 4
1938
22
    {
1939
22
        float y = 16711938.0;
1940
22
        if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1941
0
            detected_float_format = ieee_big_endian_format;
1942
22
        else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1943
22
            detected_float_format = ieee_little_endian_format;
1944
0
        else
1945
0
            detected_float_format = unknown_format;
1946
22
    }
1947
#else
1948
    detected_float_format = unknown_format;
1949
#endif
1950
1951
22
    double_format = detected_double_format;
1952
22
    float_format = detected_float_format;
1953
22
}
1954
1955
void
1956
_PyFloat_InitState(PyInterpreterState *interp)
1957
22
{
1958
22
    if (!_Py_IsMainInterpreter(interp)) {
1959
0
        return;
1960
0
    }
1961
22
    _init_global_state();
1962
22
}
1963
1964
PyStatus
1965
_PyFloat_InitTypes(PyInterpreterState *interp)
1966
22
{
1967
    /* Init float info */
1968
22
    if (_PyStructSequence_InitBuiltin(interp, &FloatInfoType,
1969
22
                                      &floatinfo_desc) < 0)
1970
0
    {
1971
0
        return _PyStatus_ERR("can't init float info type");
1972
0
    }
1973
1974
22
    return _PyStatus_OK();
1975
22
}
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
0
    }
2034
0
    else {
2035
0
        sign = (x < 0.0);
2036
0
        if (sign) {
2037
0
            x = -x;
2038
0
        }
2039
2040
0
        f = frexp(x, &e);
2041
0
        if (f < 0.5 || f >= 1.0) {
2042
0
            PyErr_SetString(PyExc_SystemError,
2043
0
                            "frexp() result out of range");
2044
0
            return -1;
2045
0
        }
2046
2047
        /* Normalize f to be in the range [1.0, 2.0) */
2048
0
        f *= 2.0;
2049
0
        e--;
2050
2051
0
        if (e >= 16) {
2052
0
            goto Overflow;
2053
0
        }
2054
0
        else if (e < -25) {
2055
            /* |x| < 2**-25. Underflow to zero. */
2056
0
            f = 0.0;
2057
0
            e = 0;
2058
0
        }
2059
0
        else if (e < -14) {
2060
            /* |x| < 2**-14. Gradual underflow */
2061
0
            f = ldexp(f, 14 + e);
2062
0
            e = 0;
2063
0
        }
2064
0
        else /* if (!(e == 0 && f == 0.0)) */ {
2065
0
            e += 15;
2066
0
            f -= 1.0; /* Get rid of leading 1 */
2067
0
        }
2068
2069
0
        f *= 1024.0; /* 2**10 */
2070
        /* Round to even */
2071
0
        bits = (unsigned short)f; /* Note the truncation */
2072
0
        assert(bits < 1024);
2073
0
        assert(e < 31);
2074
0
        if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2075
0
            ++bits;
2076
0
            if (bits == 1024) {
2077
                /* The carry propagated out of a string of 10 1 bits. */
2078
0
                bits = 0;
2079
0
                ++e;
2080
0
                if (e == 31)
2081
0
                    goto Overflow;
2082
0
            }
2083
0
        }
2084
0
    }
2085
2086
0
    bits |= (e << 10) | (sign << 15);
2087
2088
    /* Write out result. */
2089
0
    if (le) {
2090
0
        p += 1;
2091
0
        incr = -1;
2092
0
    }
2093
2094
    /* First byte */
2095
0
    *p = (unsigned char)((bits >> 8) & 0xFF);
2096
0
    p += incr;
2097
2098
    /* Second byte */
2099
0
    *p = (unsigned char)(bits & 0xFF);
2100
2101
0
    return 0;
2102
2103
0
  Overflow:
2104
0
    PyErr_SetString(PyExc_OverflowError,
2105
0
                    "float too large to pack with e format");
2106
0
    return -1;
2107
0
}
2108
2109
int
2110
PyFloat_Pack4(double x, char *data, int le)
2111
0
{
2112
0
    unsigned char *p = (unsigned char *)data;
2113
0
    if (float_format == unknown_format) {
2114
0
        unsigned char sign;
2115
0
        int e;
2116
0
        double f;
2117
0
        unsigned int fbits;
2118
0
        int incr = 1;
2119
2120
0
        if (le) {
2121
0
            p += 3;
2122
0
            incr = -1;
2123
0
        }
2124
2125
0
        if (x < 0) {
2126
0
            sign = 1;
2127
0
            x = -x;
2128
0
        }
2129
0
        else
2130
0
            sign = 0;
2131
2132
0
        f = frexp(x, &e);
2133
2134
        /* Normalize f to be in the range [1.0, 2.0) */
2135
0
        if (0.5 <= f && f < 1.0) {
2136
0
            f *= 2.0;
2137
0
            e--;
2138
0
        }
2139
0
        else if (f == 0.0)
2140
0
            e = 0;
2141
0
        else {
2142
0
            PyErr_SetString(PyExc_SystemError,
2143
0
                            "frexp() result out of range");
2144
0
            return -1;
2145
0
        }
2146
2147
0
        if (e >= 128)
2148
0
            goto Overflow;
2149
0
        else if (e < -126) {
2150
            /* Gradual underflow */
2151
0
            f = ldexp(f, 126 + e);
2152
0
            e = 0;
2153
0
        }
2154
0
        else if (!(e == 0 && f == 0.0)) {
2155
0
            e += 127;
2156
0
            f -= 1.0; /* Get rid of leading 1 */
2157
0
        }
2158
2159
0
        f *= 8388608.0; /* 2**23 */
2160
0
        fbits = (unsigned int)(f + 0.5); /* Round */
2161
0
        assert(fbits <= 8388608);
2162
0
        if (fbits >> 23) {
2163
            /* The carry propagated out of a string of 23 1 bits. */
2164
0
            fbits = 0;
2165
0
            ++e;
2166
0
            if (e >= 255)
2167
0
                goto Overflow;
2168
0
        }
2169
2170
        /* First byte */
2171
0
        *p = (sign << 7) | (e >> 1);
2172
0
        p += incr;
2173
2174
        /* Second byte */
2175
0
        *p = (char) (((e & 1) << 7) | (fbits >> 16));
2176
0
        p += incr;
2177
2178
        /* Third byte */
2179
0
        *p = (fbits >> 8) & 0xFF;
2180
0
        p += incr;
2181
2182
        /* Fourth byte */
2183
0
        *p = fbits & 0xFF;
2184
2185
        /* Done */
2186
0
        return 0;
2187
2188
0
    }
2189
0
    else {
2190
0
        float y = (float)x;
2191
0
        int i, incr = 1;
2192
2193
0
        if (isinf(y) && !isinf(x))
2194
0
            goto Overflow;
2195
2196
        /* correct y if x was a sNaN, transformed to qNaN by conversion */
2197
0
        if (isnan(x)) {
2198
0
            uint64_t v;
2199
2200
0
            memcpy(&v, &x, 8);
2201
0
#ifndef __riscv
2202
0
            if ((v & (1ULL << 51)) == 0) {
2203
0
                uint32_t u32;
2204
0
                memcpy(&u32, &y, 4);
2205
0
                u32 &= ~(1 << 22); /* make sNaN */
2206
0
                memcpy(&y, &u32, 4);
2207
0
            }
2208
#else
2209
            uint32_t u32;
2210
2211
            memcpy(&u32, &y, 4);
2212
            if ((v & (1ULL << 51)) == 0) {
2213
                u32 &= ~(1 << 22);
2214
            }
2215
            /* Workaround RISC-V: "If a NaN value is converted to a
2216
             * different floating-point type, the result is the
2217
             * canonical NaN of the new type".  The canonical NaN here
2218
             * is a positive qNaN with zero payload. */
2219
            if (v & (1ULL << 63)) {
2220
                u32 |= (1 << 31); /* set sign */
2221
            }
2222
            /* add payload */
2223
            u32 -= (u32 & 0x3fffff);
2224
            u32 += (uint32_t)((v & 0x7ffffffffffffULL) >> 29);
2225
2226
            memcpy(&y, &u32, 4);
2227
#endif
2228
0
        }
2229
2230
0
        unsigned char s[sizeof(float)];
2231
0
        memcpy(s, &y, sizeof(float));
2232
2233
0
        if ((float_format == ieee_little_endian_format && !le)
2234
0
            || (float_format == ieee_big_endian_format && le)) {
2235
0
            p += 3;
2236
0
            incr = -1;
2237
0
        }
2238
2239
0
        for (i = 0; i < 4; i++) {
2240
0
            *p = s[i];
2241
0
            p += incr;
2242
0
        }
2243
0
        return 0;
2244
0
    }
2245
0
  Overflow:
2246
0
    PyErr_SetString(PyExc_OverflowError,
2247
0
                    "float too large to pack with f format");
2248
0
    return -1;
2249
0
}
2250
2251
int
2252
PyFloat_Pack8(double x, char *data, int le)
2253
0
{
2254
0
    unsigned char *p = (unsigned char *)data;
2255
0
    if (double_format == unknown_format) {
2256
0
        unsigned char sign;
2257
0
        int e;
2258
0
        double f;
2259
0
        unsigned int fhi, flo;
2260
0
        int incr = 1;
2261
2262
0
        if (le) {
2263
0
            p += 7;
2264
0
            incr = -1;
2265
0
        }
2266
2267
0
        if (x < 0) {
2268
0
            sign = 1;
2269
0
            x = -x;
2270
0
        }
2271
0
        else
2272
0
            sign = 0;
2273
2274
0
        f = frexp(x, &e);
2275
2276
        /* Normalize f to be in the range [1.0, 2.0) */
2277
0
        if (0.5 <= f && f < 1.0) {
2278
0
            f *= 2.0;
2279
0
            e--;
2280
0
        }
2281
0
        else if (f == 0.0)
2282
0
            e = 0;
2283
0
        else {
2284
0
            PyErr_SetString(PyExc_SystemError,
2285
0
                            "frexp() result out of range");
2286
0
            return -1;
2287
0
        }
2288
2289
0
        if (e >= 1024)
2290
0
            goto Overflow;
2291
0
        else if (e < -1022) {
2292
            /* Gradual underflow */
2293
0
            f = ldexp(f, 1022 + e);
2294
0
            e = 0;
2295
0
        }
2296
0
        else if (!(e == 0 && f == 0.0)) {
2297
0
            e += 1023;
2298
0
            f -= 1.0; /* Get rid of leading 1 */
2299
0
        }
2300
2301
        /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2302
0
        f *= 268435456.0; /* 2**28 */
2303
0
        fhi = (unsigned int)f; /* Truncate */
2304
0
        assert(fhi < 268435456);
2305
2306
0
        f -= (double)fhi;
2307
0
        f *= 16777216.0; /* 2**24 */
2308
0
        flo = (unsigned int)(f + 0.5); /* Round */
2309
0
        assert(flo <= 16777216);
2310
0
        if (flo >> 24) {
2311
            /* The carry propagated out of a string of 24 1 bits. */
2312
0
            flo = 0;
2313
0
            ++fhi;
2314
0
            if (fhi >> 28) {
2315
                /* And it also propagated out of the next 28 bits. */
2316
0
                fhi = 0;
2317
0
                ++e;
2318
0
                if (e >= 2047)
2319
0
                    goto Overflow;
2320
0
            }
2321
0
        }
2322
2323
        /* First byte */
2324
0
        *p = (sign << 7) | (e >> 4);
2325
0
        p += incr;
2326
2327
        /* Second byte */
2328
0
        *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2329
0
        p += incr;
2330
2331
        /* Third byte */
2332
0
        *p = (fhi >> 16) & 0xFF;
2333
0
        p += incr;
2334
2335
        /* Fourth byte */
2336
0
        *p = (fhi >> 8) & 0xFF;
2337
0
        p += incr;
2338
2339
        /* Fifth byte */
2340
0
        *p = fhi & 0xFF;
2341
0
        p += incr;
2342
2343
        /* Sixth byte */
2344
0
        *p = (flo >> 16) & 0xFF;
2345
0
        p += incr;
2346
2347
        /* Seventh byte */
2348
0
        *p = (flo >> 8) & 0xFF;
2349
0
        p += incr;
2350
2351
        /* Eighth byte */
2352
0
        *p = flo & 0xFF;
2353
        /* p += incr; */
2354
2355
        /* Done */
2356
0
        return 0;
2357
2358
0
      Overflow:
2359
0
        PyErr_SetString(PyExc_OverflowError,
2360
0
                        "float too large to pack with d format");
2361
0
        return -1;
2362
0
    }
2363
0
    else {
2364
0
        unsigned char as_bytes[8];
2365
0
        memcpy(as_bytes, &x, 8);
2366
0
        const unsigned char *s = as_bytes;
2367
0
        int i, incr = 1;
2368
2369
0
        if ((double_format == ieee_little_endian_format && !le)
2370
0
            || (double_format == ieee_big_endian_format && le)) {
2371
0
            p += 7;
2372
0
            incr = -1;
2373
0
        }
2374
2375
0
        for (i = 0; i < 8; i++) {
2376
0
            *p = *s++;
2377
0
            p += incr;
2378
0
        }
2379
0
        return 0;
2380
0
    }
2381
0
}
2382
2383
double
2384
PyFloat_Unpack2(const char *data, int le)
2385
2.86k
{
2386
2.86k
    unsigned char *p = (unsigned char *)data;
2387
2.86k
    unsigned char sign;
2388
2.86k
    int e;
2389
2.86k
    unsigned int f;
2390
2.86k
    double x;
2391
2.86k
    int incr = 1;
2392
2393
2.86k
    if (le) {
2394
2.21k
        p += 1;
2395
2.21k
        incr = -1;
2396
2.21k
    }
2397
2398
    /* First byte */
2399
2.86k
    sign = (*p >> 7) & 1;
2400
2.86k
    e = (*p & 0x7C) >> 2;
2401
2.86k
    f = (*p & 0x03) << 8;
2402
2.86k
    p += incr;
2403
2404
    /* Second byte */
2405
2.86k
    f |= *p;
2406
2407
2.86k
    if (e == 0x1f) {
2408
1.10k
        if (f == 0) {
2409
            /* Infinity */
2410
263
            return sign ? -Py_INFINITY : Py_INFINITY;
2411
263
        }
2412
842
        else {
2413
            /* NaN */
2414
842
            uint64_t v = sign ? 0xfff0000000000000ULL : 0x7ff0000000000000ULL;
2415
2416
842
            v += (uint64_t)f << 42; /* add NaN's type & payload */
2417
842
            memcpy(&x, &v, sizeof(v));
2418
842
            return x;
2419
842
        }
2420
1.10k
    }
2421
2422
1.75k
    x = (double)f / 1024.0;
2423
2424
1.75k
    if (e == 0) {
2425
547
        e = -14;
2426
547
    }
2427
1.21k
    else {
2428
1.21k
        x += 1.0;
2429
1.21k
        e -= 15;
2430
1.21k
    }
2431
1.75k
    x = ldexp(x, e);
2432
2433
1.75k
    if (sign)
2434
843
        x = -x;
2435
2436
1.75k
    return x;
2437
2.86k
}
2438
2439
double
2440
PyFloat_Unpack4(const char *data, int le)
2441
3.67k
{
2442
3.67k
    unsigned char *p = (unsigned char *)data;
2443
3.67k
    if (float_format == unknown_format) {
2444
0
        unsigned char sign;
2445
0
        int e;
2446
0
        unsigned int f;
2447
0
        double x;
2448
0
        int incr = 1;
2449
2450
0
        if (le) {
2451
0
            p += 3;
2452
0
            incr = -1;
2453
0
        }
2454
2455
        /* First byte */
2456
0
        sign = (*p >> 7) & 1;
2457
0
        e = (*p & 0x7F) << 1;
2458
0
        p += incr;
2459
2460
        /* Second byte */
2461
0
        e |= (*p >> 7) & 1;
2462
0
        f = (*p & 0x7F) << 16;
2463
0
        p += incr;
2464
2465
0
        if (e == 255) {
2466
0
            PyErr_SetString(
2467
0
                PyExc_ValueError,
2468
0
                "can't unpack IEEE 754 special value "
2469
0
                "on non-IEEE platform");
2470
0
            return -1;
2471
0
        }
2472
2473
        /* Third byte */
2474
0
        f |= *p << 8;
2475
0
        p += incr;
2476
2477
        /* Fourth byte */
2478
0
        f |= *p;
2479
2480
0
        x = (double)f / 8388608.0;
2481
2482
        /* XXX This sadly ignores Inf/NaN issues */
2483
0
        if (e == 0)
2484
0
            e = -126;
2485
0
        else {
2486
0
            x += 1.0;
2487
0
            e -= 127;
2488
0
        }
2489
0
        x = ldexp(x, e);
2490
2491
0
        if (sign)
2492
0
            x = -x;
2493
2494
0
        return x;
2495
0
    }
2496
3.67k
    else {
2497
3.67k
        float x;
2498
2499
3.67k
        if ((float_format == ieee_little_endian_format && !le)
2500
3.10k
            || (float_format == ieee_big_endian_format && le)) {
2501
3.10k
            char buf[4];
2502
3.10k
            char *d = &buf[3];
2503
3.10k
            int i;
2504
2505
15.5k
            for (i = 0; i < 4; i++) {
2506
12.4k
                *d-- = *p++;
2507
12.4k
            }
2508
3.10k
            memcpy(&x, buf, 4);
2509
3.10k
        }
2510
574
        else {
2511
574
            memcpy(&x, p, 4);
2512
574
        }
2513
2514
        /* return sNaN double if x was sNaN float */
2515
3.67k
        if (isnan(x)) {
2516
527
            uint32_t v;
2517
527
            memcpy(&v, &x, 4);
2518
2519
527
#ifndef __riscv
2520
527
            if ((v & (1 << 22)) == 0) {
2521
84
                double y = x; /* will make qNaN double */
2522
84
                uint64_t u64;
2523
84
                memcpy(&u64, &y, 8);
2524
84
                u64 &= ~(1ULL << 51); /* make sNaN */
2525
84
                memcpy(&y, &u64, 8);
2526
84
                return y;
2527
84
            }
2528
#else
2529
            double y = x;
2530
            uint64_t u64;
2531
2532
            memcpy(&u64, &y, 8);
2533
            if ((v & (1 << 22)) == 0) {
2534
                u64 &= ~(1ULL << 51);
2535
            }
2536
            /* Workaround RISC-V, see PyFloat_Pack4() */
2537
            if (v & (1 << 31)) {
2538
                u64 |= (1ULL << 63); /* set sign */
2539
            }
2540
            /* add payload */
2541
            u64 -= (u64 & 0x7ffffffffffffULL);
2542
            u64 += ((v & 0x3fffffULL) << 29);
2543
2544
            memcpy(&y, &u64, 8);
2545
            return y;
2546
#endif
2547
527
        }
2548
2549
3.59k
        return x;
2550
3.67k
    }
2551
3.67k
}
2552
2553
double
2554
PyFloat_Unpack8(const char *data, int le)
2555
2.22k
{
2556
2.22k
    unsigned char *p = (unsigned char *)data;
2557
2.22k
    if (double_format == unknown_format) {
2558
0
        unsigned char sign;
2559
0
        int e;
2560
0
        unsigned int fhi, flo;
2561
0
        double x;
2562
0
        int incr = 1;
2563
2564
0
        if (le) {
2565
0
            p += 7;
2566
0
            incr = -1;
2567
0
        }
2568
2569
        /* First byte */
2570
0
        sign = (*p >> 7) & 1;
2571
0
        e = (*p & 0x7F) << 4;
2572
2573
0
        p += incr;
2574
2575
        /* Second byte */
2576
0
        e |= (*p >> 4) & 0xF;
2577
0
        fhi = (*p & 0xF) << 24;
2578
0
        p += incr;
2579
2580
0
        if (e == 2047) {
2581
0
            PyErr_SetString(
2582
0
                PyExc_ValueError,
2583
0
                "can't unpack IEEE 754 special value "
2584
0
                "on non-IEEE platform");
2585
0
            return -1.0;
2586
0
        }
2587
2588
        /* Third byte */
2589
0
        fhi |= *p << 16;
2590
0
        p += incr;
2591
2592
        /* Fourth byte */
2593
0
        fhi |= *p  << 8;
2594
0
        p += incr;
2595
2596
        /* Fifth byte */
2597
0
        fhi |= *p;
2598
0
        p += incr;
2599
2600
        /* Sixth byte */
2601
0
        flo = *p << 16;
2602
0
        p += incr;
2603
2604
        /* Seventh byte */
2605
0
        flo |= *p << 8;
2606
0
        p += incr;
2607
2608
        /* Eighth byte */
2609
0
        flo |= *p;
2610
2611
0
        x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2612
0
        x /= 268435456.0; /* 2**28 */
2613
2614
0
        if (e == 0)
2615
0
            e = -1022;
2616
0
        else {
2617
0
            x += 1.0;
2618
0
            e -= 1023;
2619
0
        }
2620
0
        x = ldexp(x, e);
2621
2622
0
        if (sign)
2623
0
            x = -x;
2624
2625
0
        return x;
2626
0
    }
2627
2.22k
    else {
2628
2.22k
        double x;
2629
2630
2.22k
        if ((double_format == ieee_little_endian_format && !le)
2631
1.73k
            || (double_format == ieee_big_endian_format && le)) {
2632
1.73k
            char buf[8];
2633
1.73k
            char *d = &buf[7];
2634
1.73k
            int i;
2635
2636
15.5k
            for (i = 0; i < 8; i++) {
2637
13.8k
                *d-- = *p++;
2638
13.8k
            }
2639
1.73k
            memcpy(&x, buf, 8);
2640
1.73k
        }
2641
497
        else {
2642
497
            memcpy(&x, p, 8);
2643
497
        }
2644
2645
2.22k
        return x;
2646
2.22k
    }
2647
2.22k
}