Coverage Report

Created: 2026-05-30 06:18

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