Coverage Report

Created: 2026-10-17 06:15

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