ยปCore Development>Code coverage>Objects/floatobject.c

Python code coverage for Objects/floatobject.c

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