Coverage Report

Created: 2022-07-08 09:39

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