Coverage Report

Created: 2025-07-11 06:59

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