blob: f78f7df88a918704cc7e8c928688f9ad9080124a [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Mark Dickinson7abf8d42009-04-18 20:17:52 +000018/* ascii character tests (as opposed to locale tests) */
19#define ISSPACE(c) ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
20 (c) == '\r' || (c) == '\t' || (c) == '\v')
21#define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
22
Christian Heimesbbe741d2008-03-28 10:53:29 +000023#ifdef HAVE_IEEEFP_H
24#include <ieeefp.h>
25#endif
26
Guido van Rossum6923e131990-11-02 17:50:43 +000027
Christian Heimes969fe572008-01-25 11:23:10 +000028#ifdef _OSF_SOURCE
29/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
30extern int finite(double);
31#endif
32
Guido van Rossum93ad0df1997-05-13 21:00:42 +000033/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000034#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000035#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000036#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000037
Guido van Rossum3fce8831999-03-12 19:43:17 +000038struct _floatblock {
39 struct _floatblock *next;
40 PyFloatObject objects[N_FLOATOBJECTS];
41};
42
43typedef struct _floatblock PyFloatBlock;
44
45static PyFloatBlock *block_list = NULL;
46static PyFloatObject *free_list = NULL;
47
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000049fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050{
51 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000052 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
53 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000055 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000056 ((PyFloatBlock *)p)->next = block_list;
57 block_list = (PyFloatBlock *)p;
58 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000059 q = p + N_FLOATOBJECTS;
60 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000061 Py_TYPE(q) = (struct _typeobject *)(q-1);
62 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000063 return p + N_FLOATOBJECTS - 1;
64}
65
Christian Heimes93852662007-12-01 12:22:32 +000066double
67PyFloat_GetMax(void)
68{
69 return DBL_MAX;
70}
71
72double
73PyFloat_GetMin(void)
74{
75 return DBL_MIN;
76}
77
Christian Heimesd32ed6f2008-01-14 18:49:24 +000078static PyTypeObject FloatInfoType;
79
80PyDoc_STRVAR(floatinfo__doc__,
81"sys.floatinfo\n\
82\n\
83A structseq holding information about the float type. It contains low level\n\
84information about the precision and internal representation. Please study\n\
85your system's :file:`float.h` for more information.");
86
87static PyStructSequence_Field floatinfo_fields[] = {
88 {"max", "DBL_MAX -- maximum representable finite float"},
89 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
90 "is representable"},
91 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
92 "is representable"},
93 {"min", "DBL_MIN -- Minimum positive normalizer float"},
94 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
95 "is a normalized float"},
96 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
97 "a normalized"},
98 {"dig", "DBL_DIG -- digits"},
99 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
100 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
101 "representable float"},
102 {"radix", "FLT_RADIX -- radix of exponent"},
103 {"rounds", "FLT_ROUNDS -- addition rounds"},
104 {0}
105};
106
107static PyStructSequence_Desc floatinfo_desc = {
108 "sys.floatinfo", /* name */
109 floatinfo__doc__, /* doc */
110 floatinfo_fields, /* fields */
111 11
112};
113
Christian Heimes93852662007-12-01 12:22:32 +0000114PyObject *
115PyFloat_GetInfo(void)
116{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000117 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000118 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120 floatinfo = PyStructSequence_New(&FloatInfoType);
121 if (floatinfo == NULL) {
122 return NULL;
123 }
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125#define SetIntFlag(flag) \
126 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
127#define SetDblFlag(flag) \
128 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000129
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000130 SetDblFlag(DBL_MAX);
131 SetIntFlag(DBL_MAX_EXP);
132 SetIntFlag(DBL_MAX_10_EXP);
133 SetDblFlag(DBL_MIN);
134 SetIntFlag(DBL_MIN_EXP);
135 SetIntFlag(DBL_MIN_10_EXP);
136 SetIntFlag(DBL_DIG);
137 SetIntFlag(DBL_MANT_DIG);
138 SetDblFlag(DBL_EPSILON);
139 SetIntFlag(FLT_RADIX);
140 SetIntFlag(FLT_ROUNDS);
141#undef SetIntFlag
142#undef SetDblFlag
143
144 if (PyErr_Occurred()) {
145 Py_CLEAR(floatinfo);
146 return NULL;
147 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000148 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000149}
150
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 register PyFloatObject *op;
155 if (free_list == NULL) {
156 if ((free_list = fill_free_list()) == NULL)
157 return NULL;
158 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000159 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000160 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000161 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000162 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000163 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000168PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000169{
Christian Heimes99170a52007-12-19 02:07:34 +0000170 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000172 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000174 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000175 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000176
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000177 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000178 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
179 if (s_buffer == NULL)
180 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000181 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000182 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000183 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000184 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000185 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000186 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000188 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000189 else if (PyObject_AsCharBuffer(v, &s, &len)) {
190 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000191 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000193 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000194
Guido van Rossum4c08d552000-03-10 22:55:18 +0000195 last = s + len;
Mark Dickinson7abf8d42009-04-18 20:17:52 +0000196 while (*s && ISSPACE(Py_CHARMASK(*s)))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000197 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000198 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000199 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000200 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000201 }
Christian Heimes99170a52007-12-19 02:07:34 +0000202 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000203 /* We don't care about overflow or underflow. If the platform supports
204 * them, infinities and signed zeroes (on underflow) are fine.
Eric Smith0923d1d2009-04-16 20:16:10 +0000205 * However, strtod can return 0 for denormalized numbers. Note that
Tim Petersef14d732000-09-23 03:39:17 +0000206 * whether strtod sets errno on underflow is not defined, so we can't
207 * key off errno.
208 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000209 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000210 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000211 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000212 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000214 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215 if (end > last)
216 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000217 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000218 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000219 char *p = (char*)sp;
220 int sign = 1;
221
222 if (*p == '-') {
223 sign = -1;
224 p++;
225 }
226 if (*p == '+') {
227 p++;
228 }
229 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000230 if (s_buffer != NULL)
231 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000232 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000233 }
Georg Brandl2ee470f2008-07-16 12:55:28 +0000234 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000235 if (s_buffer != NULL)
236 PyMem_FREE(s_buffer);
Georg Brandl2ee470f2008-07-16 12:55:28 +0000237 Py_RETURN_INF(sign);
238 }
Christian Heimes99170a52007-12-19 02:07:34 +0000239#ifdef Py_NAN
240 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000241 if (s_buffer != NULL)
242 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000243 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000244 }
245#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000246 PyOS_snprintf(buffer, sizeof(buffer),
247 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000248 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000249 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000250 }
251 /* Since end != s, the platform made *some* kind of sense out
252 of the input. Trust it. */
Mark Dickinson7abf8d42009-04-18 20:17:52 +0000253 while (*end && ISSPACE(Py_CHARMASK(*end)))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000254 end++;
255 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000256 PyOS_snprintf(buffer, sizeof(buffer),
257 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000258 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000259 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000261 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000262 PyErr_SetString(PyExc_ValueError,
263 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000264 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000265 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000266 result = PyFloat_FromDouble(x);
267 error:
268 if (s_buffer)
269 PyMem_FREE(s_buffer);
270 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000271}
272
Guido van Rossum234f9421993-06-17 12:35:49 +0000273static void
Fred Drakefd99de62000-07-09 05:02:18 +0000274float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000275{
Guido van Rossum9475a232001-10-05 20:51:39 +0000276 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000277 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000278 free_list = op;
279 }
280 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000281 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000282}
283
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284double
Fred Drakefd99de62000-07-09 05:02:18 +0000285PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287 PyNumberMethods *nb;
288 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000289 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000290
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000291 if (op && PyFloat_Check(op))
292 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000294 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 return -1;
297 }
Tim Petersd2364e82001-11-01 20:09:42 +0000298
Christian Heimes90aa7642007-12-19 02:45:37 +0000299 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000300 PyErr_SetString(PyExc_TypeError, "a float is required");
301 return -1;
302 }
303
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 if (fo == NULL)
306 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 if (!PyFloat_Check(fo)) {
308 PyErr_SetString(PyExc_TypeError,
309 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310 return -1;
311 }
Tim Petersd2364e82001-11-01 20:09:42 +0000312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313 val = PyFloat_AS_DOUBLE(fo);
314 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000315
Guido van Rossumb6775db1994-08-01 11:34:53 +0000316 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317}
318
Neil Schemenauer32117e52001-01-04 01:44:34 +0000319/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000320 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000321 set to NULL, and the function invoking this macro returns NULL. If
322 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
323 stored in obj, and returned from the function invoking this macro.
324*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000325#define CONVERT_TO_DOUBLE(obj, dbl) \
326 if (PyFloat_Check(obj)) \
327 dbl = PyFloat_AS_DOUBLE(obj); \
328 else if (convert_to_double(&(obj), &(dbl)) < 0) \
329 return obj;
330
Eric Smith0923d1d2009-04-16 20:16:10 +0000331/* Methods */
332
Neil Schemenauer32117e52001-01-04 01:44:34 +0000333static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000334convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000335{
336 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000337
Guido van Rossumddefaf32007-01-14 03:31:43 +0000338 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000339 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000340 if (*dbl == -1.0 && PyErr_Occurred()) {
341 *v = NULL;
342 return -1;
343 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000344 }
345 else {
346 Py_INCREF(Py_NotImplemented);
347 *v = Py_NotImplemented;
348 return -1;
349 }
350 return 0;
351}
352
Eric Smith0923d1d2009-04-16 20:16:10 +0000353static PyObject *
354float_str_or_repr(PyFloatObject *v, char format_code)
355{
356 PyObject *result;
357 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
358 format_code, 0, Py_DTSF_ADD_DOT_0,
359 NULL);
360 if (!buf)
361 return PyErr_NoMemory();
362 result = PyUnicode_FromString(buf);
363 PyMem_Free(buf);
364 return result;
365}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000366
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000368float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
Eric Smith0923d1d2009-04-16 20:16:10 +0000370 return float_str_or_repr(v, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000371}
372
373static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000374float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000375{
Eric Smith0923d1d2009-04-16 20:16:10 +0000376 return float_str_or_repr(v, 's');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377}
378
Tim Peters307fa782004-09-23 08:06:40 +0000379/* Comparison is pretty much a nightmare. When comparing float to float,
380 * we do it as straightforwardly (and long-windedly) as conceivable, so
381 * that, e.g., Python x == y delivers the same result as the platform
382 * C x == y when x and/or y is a NaN.
383 * When mixing float with an integer type, there's no good *uniform* approach.
384 * Converting the double to an integer obviously doesn't work, since we
385 * may lose info from fractional bits. Converting the integer to a double
386 * also has two failure modes: (1) a long int may trigger overflow (too
387 * large to fit in the dynamic range of a C double); (2) even a C long may have
388 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
389 * 63 bits of precision, but a C double probably has only 53), and then
390 * we can falsely claim equality when low-order integer bits are lost by
391 * coercion to double. So this part is painful too.
392 */
393
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000394static PyObject*
395float_richcompare(PyObject *v, PyObject *w, int op)
396{
397 double i, j;
398 int r = 0;
399
Tim Peters307fa782004-09-23 08:06:40 +0000400 assert(PyFloat_Check(v));
401 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000402
Tim Peters307fa782004-09-23 08:06:40 +0000403 /* Switch on the type of w. Set i and j to doubles to be compared,
404 * and op to the richcomp to use.
405 */
406 if (PyFloat_Check(w))
407 j = PyFloat_AS_DOUBLE(w);
408
Thomas Wouters477c8d52006-05-27 19:21:47 +0000409 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000410 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000411 /* If i is an infinity, its magnitude exceeds any
412 * finite integer, so it doesn't matter which int we
413 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000414 */
415 j = 0.0;
416 else
417 goto Unimplemented;
418 }
419
Tim Peters307fa782004-09-23 08:06:40 +0000420 else if (PyLong_Check(w)) {
421 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
422 int wsign = _PyLong_Sign(w);
423 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000424 int exponent;
425
426 if (vsign != wsign) {
427 /* Magnitudes are irrelevant -- the signs alone
428 * determine the outcome.
429 */
430 i = (double)vsign;
431 j = (double)wsign;
432 goto Compare;
433 }
434 /* The signs are the same. */
435 /* Convert w to a double if it fits. In particular, 0 fits. */
436 nbits = _PyLong_NumBits(w);
437 if (nbits == (size_t)-1 && PyErr_Occurred()) {
438 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000439 * to hold the # of bits. Replace with little doubles
440 * that give the same outcome -- w is so large that
441 * its magnitude must exceed the magnitude of any
442 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000443 */
444 PyErr_Clear();
445 i = (double)vsign;
446 assert(wsign != 0);
447 j = wsign * 2.0;
448 goto Compare;
449 }
450 if (nbits <= 48) {
451 j = PyLong_AsDouble(w);
452 /* It's impossible that <= 48 bits overflowed. */
453 assert(j != -1.0 || ! PyErr_Occurred());
454 goto Compare;
455 }
456 assert(wsign != 0); /* else nbits was 0 */
457 assert(vsign != 0); /* if vsign were 0, then since wsign is
458 * not 0, we would have taken the
459 * vsign != wsign branch at the start */
460 /* We want to work with non-negative numbers. */
461 if (vsign < 0) {
462 /* "Multiply both sides" by -1; this also swaps the
463 * comparator.
464 */
465 i = -i;
466 op = _Py_SwappedOp[op];
467 }
468 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000469 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000470 /* exponent is the # of bits in v before the radix point;
471 * we know that nbits (the # of bits in w) > 48 at this point
472 */
473 if (exponent < 0 || (size_t)exponent < nbits) {
474 i = 1.0;
475 j = 2.0;
476 goto Compare;
477 }
478 if ((size_t)exponent > nbits) {
479 i = 2.0;
480 j = 1.0;
481 goto Compare;
482 }
483 /* v and w have the same number of bits before the radix
484 * point. Construct two longs that have the same comparison
485 * outcome.
486 */
487 {
488 double fracpart;
489 double intpart;
490 PyObject *result = NULL;
491 PyObject *one = NULL;
492 PyObject *vv = NULL;
493 PyObject *ww = w;
494
495 if (wsign < 0) {
496 ww = PyNumber_Negative(w);
497 if (ww == NULL)
498 goto Error;
499 }
500 else
501 Py_INCREF(ww);
502
503 fracpart = modf(i, &intpart);
504 vv = PyLong_FromDouble(intpart);
505 if (vv == NULL)
506 goto Error;
507
508 if (fracpart != 0.0) {
509 /* Shift left, and or a 1 bit into vv
510 * to represent the lost fraction.
511 */
512 PyObject *temp;
513
Christian Heimes217cfd12007-12-02 14:31:20 +0000514 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000515 if (one == NULL)
516 goto Error;
517
518 temp = PyNumber_Lshift(ww, one);
519 if (temp == NULL)
520 goto Error;
521 Py_DECREF(ww);
522 ww = temp;
523
524 temp = PyNumber_Lshift(vv, one);
525 if (temp == NULL)
526 goto Error;
527 Py_DECREF(vv);
528 vv = temp;
529
530 temp = PyNumber_Or(vv, one);
531 if (temp == NULL)
532 goto Error;
533 Py_DECREF(vv);
534 vv = temp;
535 }
536
537 r = PyObject_RichCompareBool(vv, ww, op);
538 if (r < 0)
539 goto Error;
540 result = PyBool_FromLong(r);
541 Error:
542 Py_XDECREF(vv);
543 Py_XDECREF(ww);
544 Py_XDECREF(one);
545 return result;
546 }
547 } /* else if (PyLong_Check(w)) */
548
549 else /* w isn't float, int, or long */
550 goto Unimplemented;
551
552 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000553 PyFPE_START_PROTECT("richcompare", return NULL)
554 switch (op) {
555 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000556 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000557 break;
558 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000559 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000560 break;
561 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000562 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000563 break;
564 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000565 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000566 break;
567 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000568 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000569 break;
570 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000571 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000572 break;
573 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000574 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000575 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000576
577 Unimplemented:
578 Py_INCREF(Py_NotImplemented);
579 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000580}
581
Guido van Rossum9bfef441993-03-29 10:43:31 +0000582static long
Fred Drakefd99de62000-07-09 05:02:18 +0000583float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000584{
Tim Peters39dce292000-08-15 03:34:48 +0000585 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000586}
587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000589float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000591 double a,b;
592 CONVERT_TO_DOUBLE(v, a);
593 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000594 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000595 a = a + b;
596 PyFPE_END_PROTECT(a)
597 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598}
599
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000601float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000603 double a,b;
604 CONVERT_TO_DOUBLE(v, a);
605 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000606 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000607 a = a - b;
608 PyFPE_END_PROTECT(a)
609 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610}
611
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000613float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000614{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000615 double a,b;
616 CONVERT_TO_DOUBLE(v, a);
617 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000618 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000619 a = a * b;
620 PyFPE_END_PROTECT(a)
621 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000622}
623
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000625float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000626{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000627 double a,b;
628 CONVERT_TO_DOUBLE(v, a);
629 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000630#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000631 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000632 PyErr_SetString(PyExc_ZeroDivisionError,
633 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000634 return NULL;
635 }
Christian Heimes53876d92008-04-19 00:31:39 +0000636#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000637 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000638 a = a / b;
639 PyFPE_END_PROTECT(a)
640 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641}
642
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000644float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000646 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000647 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000648 CONVERT_TO_DOUBLE(v, vx);
649 CONVERT_TO_DOUBLE(w, wx);
650#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000652 PyErr_SetString(PyExc_ZeroDivisionError,
653 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000654 return NULL;
655 }
Christian Heimes53876d92008-04-19 00:31:39 +0000656#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000657 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000658 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000659 /* note: checking mod*wx < 0 is incorrect -- underflows to
660 0 if wx < sqrt(smallest nonzero double) */
661 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000662 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000663 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000664 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000666}
667
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000668static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000669float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000670{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000671 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000672 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000673 CONVERT_TO_DOUBLE(v, vx);
674 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000675 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000677 return NULL;
678 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000679 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000680 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000681 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000682 exact multiple of wx. But this is fp arithmetic, and fp
683 vx - mod is an approximation; the result is that div may
684 not be an exact integral value after the division, although
685 it will always be very close to one.
686 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000687 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000688 if (mod) {
689 /* ensure the remainder has the same sign as the denominator */
690 if ((wx < 0) != (mod < 0)) {
691 mod += wx;
692 div -= 1.0;
693 }
694 }
695 else {
696 /* the remainder is zero, and in the presence of signed zeroes
697 fmod returns different results across platforms; ensure
698 it has the same sign as the denominator; we'd like to do
699 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000700 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000701 if (wx < 0.0)
702 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000703 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000704 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000705 if (div) {
706 floordiv = floor(div);
707 if (div - floordiv > 0.5)
708 floordiv += 1.0;
709 }
710 else {
711 /* div is zero - get the same sign as the true quotient */
712 div *= div; /* hide "div = +0" from optimizers */
713 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
714 }
715 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000716 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000717}
718
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000719static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000720float_floor_div(PyObject *v, PyObject *w)
721{
722 PyObject *t, *r;
723
724 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000725 if (t == NULL || t == Py_NotImplemented)
726 return t;
727 assert(PyTuple_CheckExact(t));
728 r = PyTuple_GET_ITEM(t, 0);
729 Py_INCREF(r);
730 Py_DECREF(t);
731 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000732}
733
734static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000735float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736{
737 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000738
739 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000740 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000741 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000742 return NULL;
743 }
744
Neil Schemenauer32117e52001-01-04 01:44:34 +0000745 CONVERT_TO_DOUBLE(v, iv);
746 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000747
748 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000749 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000750 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000751 }
Tim Peters96685bf2001-08-23 22:31:37 +0000752 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000753 if (iw < 0.0) {
754 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000755 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000756 return NULL;
757 }
758 return PyFloat_FromDouble(0.0);
759 }
Christian Heimes53876d92008-04-19 00:31:39 +0000760 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
761 return PyFloat_FromDouble(1.0);
762 }
Tim Peterse87568d2003-05-24 20:18:24 +0000763 if (iv < 0.0) {
764 /* Whether this is an error is a mess, and bumps into libm
765 * bugs so we have to figure it out ourselves.
766 */
767 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000768 /* Negative numbers raised to fractional powers
769 * become complex.
770 */
771 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000772 }
773 /* iw is an exact integer, albeit perhaps a very large one.
774 * -1 raised to an exact integer should never be exceptional.
775 * Alas, some libms (chiefly glibc as of early 2003) return
776 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
777 * happen to be representable in a *C* integer. That's a
778 * bug; we let that slide in math.pow() (which currently
779 * reflects all platform accidents), but not for Python's **.
780 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000781 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000782 /* Return 1 if iw is even, -1 if iw is odd; there's
783 * no guarantee that any C integral type is big
784 * enough to hold iw, so we have to check this
785 * indirectly.
786 */
787 ix = floor(iw * 0.5) * 2.0;
788 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
789 }
790 /* Else iv != -1.0, and overflow or underflow are possible.
791 * Unless we're to write pow() ourselves, we have to trust
792 * the platform to do this correctly.
793 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000794 }
Tim Peters96685bf2001-08-23 22:31:37 +0000795 errno = 0;
796 PyFPE_START_PROTECT("pow", return NULL)
797 ix = pow(iv, iw);
798 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000799 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000800 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000801 /* We don't expect any errno value other than ERANGE, but
802 * the range of libm bugs appears unbounded.
803 */
804 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
805 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000807 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809}
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000812float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815}
816
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000817static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000818float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000819{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000820 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821}
822
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000823static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000824float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000825{
826 return v->ob_fval != 0.0;
827}
828
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000829static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000830float_is_integer(PyObject *v)
831{
832 double x = PyFloat_AsDouble(v);
833 PyObject *o;
834
835 if (x == -1.0 && PyErr_Occurred())
836 return NULL;
837 if (!Py_IS_FINITE(x))
838 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000839 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000840 PyFPE_START_PROTECT("is_integer", return NULL)
841 o = (floor(x) == x) ? Py_True : Py_False;
842 PyFPE_END_PROTECT(x)
843 if (errno != 0) {
844 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
845 PyExc_ValueError);
846 return NULL;
847 }
848 Py_INCREF(o);
849 return o;
850}
851
852#if 0
853static PyObject *
854float_is_inf(PyObject *v)
855{
856 double x = PyFloat_AsDouble(v);
857 if (x == -1.0 && PyErr_Occurred())
858 return NULL;
859 return PyBool_FromLong((long)Py_IS_INFINITY(x));
860}
861
862static PyObject *
863float_is_nan(PyObject *v)
864{
865 double x = PyFloat_AsDouble(v);
866 if (x == -1.0 && PyErr_Occurred())
867 return NULL;
868 return PyBool_FromLong((long)Py_IS_NAN(x));
869}
870
871static PyObject *
872float_is_finite(PyObject *v)
873{
874 double x = PyFloat_AsDouble(v);
875 if (x == -1.0 && PyErr_Occurred())
876 return NULL;
877 return PyBool_FromLong((long)Py_IS_FINITE(x));
878}
879#endif
880
881static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000882float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000883{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000884 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000885 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000886
887 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000888 /* Try to get out cheap if this fits in a Python int. The attempt
889 * to cast to long must be protected, as C doesn't define what
890 * happens if the double is too big to fit in a long. Some rare
891 * systems raise an exception then (RISCOS was mentioned as one,
892 * and someone using a non-default option on Sun also bumped into
893 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
894 * still be vulnerable: if a long has more bits of precision than
895 * a double, casting MIN/MAX to double may yield an approximation,
896 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
897 * yield true from the C expression wholepart<=LONG_MAX, despite
898 * that wholepart is actually greater than LONG_MAX.
899 */
900 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
901 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000902 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000903 }
904 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000905}
906
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000907/* double_round: rounds a finite double to the closest multiple of
908 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
909 ndigits <= 323). Returns a Python float, or sets a Python error and
910 returns NULL on failure (OverflowError and memory errors are possible). */
911
912#ifndef PY_NO_SHORT_FLOAT_REPR
913/* version of double_round that uses the correctly-rounded string<->double
914 conversions from Python/dtoa.c */
915
916static PyObject *
917double_round(double x, int ndigits) {
918
919 double rounded;
920 Py_ssize_t buflen, mybuflen=100;
921 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
922 int decpt, sign;
923 PyObject *result = NULL;
924
925 /* round to a decimal string */
926 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
927 if (buf == NULL) {
928 PyErr_NoMemory();
929 return NULL;
930 }
931
932 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
933 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
934 buflen = buf_end - buf;
935 if (buflen + 8 > mybuflen) {
936 mybuflen = buflen+8;
937 mybuf = (char *)PyMem_Malloc(mybuflen);
938 if (mybuf == NULL) {
939 PyErr_NoMemory();
940 goto exit;
941 }
942 }
943 /* copy buf to mybuf, adding exponent, sign and leading 0 */
944 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
945 buf, decpt - (int)buflen);
946
947 /* and convert the resulting string back to a double */
948 errno = 0;
949 rounded = _Py_dg_strtod(mybuf, NULL);
950 if (errno == ERANGE && fabs(rounded) >= 1.)
951 PyErr_SetString(PyExc_OverflowError,
952 "rounded value too large to represent");
953 else
954 result = PyFloat_FromDouble(rounded);
955
956 /* done computing value; now clean up */
957 if (mybuf != shortbuf)
958 PyMem_Free(mybuf);
959 exit:
960 _Py_dg_freedtoa(buf);
961 return result;
962}
963
964#else /* PY_NO_SHORT_FLOAT_REPR */
965
966/* fallback version, to be used when correctly rounded binary<->decimal
967 conversions aren't available */
968
969static PyObject *
970double_round(double x, int ndigits) {
971 double pow1, pow2, y, z;
972 if (ndigits >= 0) {
973 if (ndigits > 22) {
974 /* pow1 and pow2 are each safe from overflow, but
975 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
976 pow1 = pow(10.0, (double)(ndigits-22));
977 pow2 = 1e22;
978 }
979 else {
980 pow1 = pow(10.0, (double)ndigits);
981 pow2 = 1.0;
982 }
983 y = (x*pow1)*pow2;
984 /* if y overflows, then rounded value is exactly x */
985 if (!Py_IS_FINITE(y))
986 return PyFloat_FromDouble(x);
987 }
988 else {
989 pow1 = pow(10.0, (double)-ndigits);
990 pow2 = 1.0; /* unused; silences a gcc compiler warning */
991 y = x / pow1;
992 }
993
994 z = round(y);
995 if (fabs(y-z) == 0.5)
996 /* halfway between two integers; use round-half-even */
997 z = 2.0*round(y/2.0);
998
999 if (ndigits >= 0)
1000 z = (z / pow2) / pow1;
1001 else
1002 z *= pow1;
1003
1004 /* if computation resulted in overflow, raise OverflowError */
1005 if (!Py_IS_FINITE(z)) {
1006 PyErr_SetString(PyExc_OverflowError,
1007 "overflow occurred during round");
1008 return NULL;
1009 }
1010
1011 return PyFloat_FromDouble(z);
1012}
1013
1014#endif /* PY_NO_SHORT_FLOAT_REPR */
1015
1016/* round a Python float v to the closest multiple of 10**-ndigits */
1017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001018static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001019float_round(PyObject *v, PyObject *args)
1020{
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001021 double x, rounded;
1022 PyObject *o_ndigits = NULL;
1023 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001024
1025 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1027 return NULL;
1028 if (o_ndigits == NULL) {
1029 /* single-argument round: round to nearest integer */
1030 rounded = round(x);
1031 if (fabs(x-rounded) == 0.5)
1032 /* halfway case: round to even */
1033 rounded = 2.0*round(x/2.0);
1034 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001035 }
1036
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001037 /* interpret second argument as a Py_ssize_t; clips on overflow */
1038 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1039 if (ndigits == -1 && PyErr_Occurred())
1040 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001041
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001042 /* nans and infinities round to themselves */
1043 if (!Py_IS_FINITE(x))
1044 return PyFloat_FromDouble(x);
1045
1046 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1047 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1048 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
1049#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1050#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
1051 if (ndigits > NDIGITS_MAX)
1052 /* return x */
1053 return PyFloat_FromDouble(x);
1054 else if (ndigits < NDIGITS_MIN)
1055 /* return 0.0, but with sign of x */
1056 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001057 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001058 /* finite x, and ndigits is not unreasonably large */
1059 return double_round(x, (int)ndigits);
1060#undef NDIGITS_MAX
1061#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001062}
1063
1064static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001065float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001066{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001067 if (PyFloat_CheckExact(v))
1068 Py_INCREF(v);
1069 else
1070 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001071 return v;
1072}
1073
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001074/* turn ASCII hex characters into integer values and vice versa */
1075
1076static char
1077char_from_hex(int x)
1078{
1079 assert(0 <= x && x < 16);
1080 return "0123456789abcdef"[x];
1081}
1082
1083static int
1084hex_from_char(char c) {
1085 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001086 switch(c) {
1087 case '0':
1088 x = 0;
1089 break;
1090 case '1':
1091 x = 1;
1092 break;
1093 case '2':
1094 x = 2;
1095 break;
1096 case '3':
1097 x = 3;
1098 break;
1099 case '4':
1100 x = 4;
1101 break;
1102 case '5':
1103 x = 5;
1104 break;
1105 case '6':
1106 x = 6;
1107 break;
1108 case '7':
1109 x = 7;
1110 break;
1111 case '8':
1112 x = 8;
1113 break;
1114 case '9':
1115 x = 9;
1116 break;
1117 case 'a':
1118 case 'A':
1119 x = 10;
1120 break;
1121 case 'b':
1122 case 'B':
1123 x = 11;
1124 break;
1125 case 'c':
1126 case 'C':
1127 x = 12;
1128 break;
1129 case 'd':
1130 case 'D':
1131 x = 13;
1132 break;
1133 case 'e':
1134 case 'E':
1135 x = 14;
1136 break;
1137 case 'f':
1138 case 'F':
1139 x = 15;
1140 break;
1141 default:
1142 x = -1;
1143 break;
1144 }
1145 return x;
1146}
1147
1148/* convert a float to a hexadecimal string */
1149
1150/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1151 of the form 4k+1. */
1152#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1153
1154static PyObject *
1155float_hex(PyObject *v)
1156{
1157 double x, m;
1158 int e, shift, i, si, esign;
1159 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1160 trailing NUL byte. */
1161 char s[(TOHEX_NBITS-1)/4+3];
1162
1163 CONVERT_TO_DOUBLE(v, x);
1164
1165 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1166 return float_str((PyFloatObject *)v);
1167
1168 if (x == 0.0) {
1169 if(copysign(1.0, x) == -1.0)
1170 return PyUnicode_FromString("-0x0.0p+0");
1171 else
1172 return PyUnicode_FromString("0x0.0p+0");
1173 }
1174
1175 m = frexp(fabs(x), &e);
1176 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1177 m = ldexp(m, shift);
1178 e -= shift;
1179
1180 si = 0;
1181 s[si] = char_from_hex((int)m);
1182 si++;
1183 m -= (int)m;
1184 s[si] = '.';
1185 si++;
1186 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1187 m *= 16.0;
1188 s[si] = char_from_hex((int)m);
1189 si++;
1190 m -= (int)m;
1191 }
1192 s[si] = '\0';
1193
1194 if (e < 0) {
1195 esign = (int)'-';
1196 e = -e;
1197 }
1198 else
1199 esign = (int)'+';
1200
1201 if (x < 0.0)
1202 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1203 else
1204 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1205}
1206
1207PyDoc_STRVAR(float_hex_doc,
1208"float.hex() -> string\n\
1209\n\
1210Return a hexadecimal representation of a floating-point number.\n\
1211>>> (-0.1).hex()\n\
1212'-0x1.999999999999ap-4'\n\
1213>>> 3.14159.hex()\n\
1214'0x1.921f9f01b866ep+1'");
1215
1216/* Convert a hexadecimal string to a float. */
1217
1218static PyObject *
1219float_fromhex(PyObject *cls, PyObject *arg)
1220{
1221 PyObject *result_as_float, *result;
1222 double x;
1223 long exp, top_exp, lsb, key_digit;
1224 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1225 int half_eps, digit, round_up, sign=1;
1226 Py_ssize_t length, ndigits, fdigits, i;
1227
1228 /*
1229 * For the sake of simplicity and correctness, we impose an artificial
1230 * limit on ndigits, the total number of hex digits in the coefficient
1231 * The limit is chosen to ensure that, writing exp for the exponent,
1232 *
1233 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1234 * guaranteed to overflow (provided it's nonzero)
1235 *
1236 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1237 * guaranteed to underflow to 0.
1238 *
1239 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1240 * overflow in the calculation of exp and top_exp below.
1241 *
1242 * More specifically, ndigits is assumed to satisfy the following
1243 * inequalities:
1244 *
1245 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1246 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1247 *
1248 * If either of these inequalities is not satisfied, a ValueError is
1249 * raised. Otherwise, write x for the value of the hex string, and
1250 * assume x is nonzero. Then
1251 *
1252 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1253 *
1254 * Now if exp > LONG_MAX/2 then:
1255 *
1256 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1257 * = DBL_MAX_EXP
1258 *
1259 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1260 * double, so overflows. If exp < LONG_MIN/2, then
1261 *
1262 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1263 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1264 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1265 *
1266 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1267 * when converted to a C double.
1268 *
1269 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1270 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1271 */
1272
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001273 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274 if (s == NULL)
1275 return NULL;
1276 s_end = s + length;
1277
1278 /********************
1279 * Parse the string *
1280 ********************/
1281
1282 /* leading whitespace and optional sign */
Mark Dickinson7abf8d42009-04-18 20:17:52 +00001283 while (ISSPACE(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001284 s++;
1285 if (*s == '-') {
1286 s++;
1287 sign = -1;
1288 }
1289 else if (*s == '+')
1290 s++;
1291
1292 /* infinities and nans */
Andrew MacIntyre45612572008-09-22 14:49:01 +00001293 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001294 x = Py_NAN;
1295 goto finished;
1296 }
Andrew MacIntyre45612572008-09-22 14:49:01 +00001297 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1298 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001299 x = sign*Py_HUGE_VAL;
1300 goto finished;
1301 }
1302
1303 /* [0x] */
1304 s_store = s;
1305 if (*s == '0') {
1306 s++;
Mark Dickinson7abf8d42009-04-18 20:17:52 +00001307 if (*s == 'x' || *s == 'X')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308 if (tolower(*s) == (int)'x')
1309 s++;
1310 else
1311 s = s_store;
1312 }
1313
1314 /* coefficient: <integer> [. <fraction>] */
1315 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001316 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001317 s++;
1318 s_store = s;
1319 if (*s == '.') {
1320 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001321 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001322 s++;
1323 coeff_end = s-1;
1324 }
1325 else
1326 coeff_end = s;
1327
1328 /* ndigits = total # of hex digits; fdigits = # after point */
1329 ndigits = coeff_end - coeff_start;
1330 fdigits = coeff_end - s_store;
1331 if (ndigits == 0)
1332 goto parse_error;
1333 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1334 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1335 goto insane_length_error;
1336
1337 /* [p <exponent>] */
1338 if (tolower(*s) == (int)'p') {
1339 s++;
1340 exp_start = s;
1341 if (*s == '-' || *s == '+')
1342 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001343 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001344 goto parse_error;
1345 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001346 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347 s++;
1348 exp = strtol(exp_start, NULL, 10);
1349 }
1350 else
1351 exp = 0;
1352
1353 /* optional trailing whitespace leading to the end of the string */
Mark Dickinson7abf8d42009-04-18 20:17:52 +00001354 while (ISSPACE(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001355 s++;
1356 if (s != s_end)
1357 goto parse_error;
1358
1359/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1360#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1361 coeff_end-(j) : \
1362 coeff_end-1-(j)))
1363
1364 /*******************************************
1365 * Compute rounded value of the hex string *
1366 *******************************************/
1367
1368 /* Discard leading zeros, and catch extreme overflow and underflow */
1369 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1370 ndigits--;
1371 if (ndigits == 0 || exp < LONG_MIN/2) {
1372 x = sign * 0.0;
1373 goto finished;
1374 }
1375 if (exp > LONG_MAX/2)
1376 goto overflow_error;
1377
1378 /* Adjust exponent for fractional part. */
1379 exp = exp - 4*((long)fdigits);
1380
1381 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1382 top_exp = exp + 4*((long)ndigits - 1);
1383 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1384 top_exp++;
1385
1386 /* catch almost all nonextreme cases of overflow and underflow here */
1387 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1388 x = sign * 0.0;
1389 goto finished;
1390 }
1391 if (top_exp > DBL_MAX_EXP)
1392 goto overflow_error;
1393
1394 /* lsb = exponent of least significant bit of the *rounded* value.
1395 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1396 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1397
1398 x = 0.0;
1399 if (exp >= lsb) {
1400 /* no rounding required */
1401 for (i = ndigits-1; i >= 0; i--)
1402 x = 16.0*x + HEX_DIGIT(i);
1403 x = sign * ldexp(x, (int)(exp));
1404 goto finished;
1405 }
1406 /* rounding required. key_digit is the index of the hex digit
1407 containing the first bit to be rounded away. */
1408 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1409 key_digit = (lsb - exp - 1) / 4;
1410 for (i = ndigits-1; i > key_digit; i--)
1411 x = 16.0*x + HEX_DIGIT(i);
1412 digit = HEX_DIGIT(key_digit);
1413 x = 16.0*x + (double)(digit & (16-2*half_eps));
1414
1415 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1416 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1417 if ((digit & half_eps) != 0) {
1418 round_up = 0;
1419 if ((digit & (3*half_eps-1)) != 0 ||
1420 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1421 round_up = 1;
1422 else
1423 for (i = key_digit-1; i >= 0; i--)
1424 if (HEX_DIGIT(i) != 0) {
1425 round_up = 1;
1426 break;
1427 }
1428 if (round_up == 1) {
1429 x += 2*half_eps;
1430 if (top_exp == DBL_MAX_EXP &&
1431 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1432 /* overflow corner case: pre-rounded value <
1433 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1434 goto overflow_error;
1435 }
1436 }
1437 x = sign * ldexp(x, (int)(exp+4*key_digit));
1438
1439 finished:
1440 result_as_float = Py_BuildValue("(d)", x);
1441 if (result_as_float == NULL)
1442 return NULL;
1443 result = PyObject_CallObject(cls, result_as_float);
1444 Py_DECREF(result_as_float);
1445 return result;
1446
1447 overflow_error:
1448 PyErr_SetString(PyExc_OverflowError,
1449 "hexadecimal value too large to represent as a float");
1450 return NULL;
1451
1452 parse_error:
1453 PyErr_SetString(PyExc_ValueError,
1454 "invalid hexadecimal floating-point string");
1455 return NULL;
1456
1457 insane_length_error:
1458 PyErr_SetString(PyExc_ValueError,
1459 "hexadecimal string too long to convert");
1460 return NULL;
1461}
1462
1463PyDoc_STRVAR(float_fromhex_doc,
1464"float.fromhex(string) -> float\n\
1465\n\
1466Create a floating-point number from a hexadecimal string.\n\
1467>>> float.fromhex('0x1.ffffp10')\n\
14682047.984375\n\
1469>>> float.fromhex('-0x1p-1074')\n\
1470-4.9406564584124654e-324");
1471
1472
Christian Heimes26855632008-01-27 23:50:43 +00001473static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001474float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001475{
1476 double self;
1477 double float_part;
1478 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001479 int i;
1480
Christian Heimes26855632008-01-27 23:50:43 +00001481 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001482 PyObject *py_exponent = NULL;
1483 PyObject *numerator = NULL;
1484 PyObject *denominator = NULL;
1485 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001486 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001487
1488#define INPLACE_UPDATE(obj, call) \
1489 prev = obj; \
1490 obj = call; \
1491 Py_DECREF(prev); \
1492
1493 CONVERT_TO_DOUBLE(v, self);
1494
1495 if (Py_IS_INFINITY(self)) {
1496 PyErr_SetString(PyExc_OverflowError,
1497 "Cannot pass infinity to float.as_integer_ratio.");
1498 return NULL;
1499 }
1500#ifdef Py_NAN
1501 if (Py_IS_NAN(self)) {
1502 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001503 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001504 return NULL;
1505 }
1506#endif
1507
Christian Heimes26855632008-01-27 23:50:43 +00001508 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001509 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001510 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001511
1512 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1513 float_part *= 2.0;
1514 exponent--;
1515 }
1516 /* self == float_part * 2**exponent exactly and float_part is integral.
1517 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1518 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001519
Christian Heimes292d3512008-02-03 16:51:08 +00001520 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001521 if (numerator == NULL) goto error;
1522
Christian Heimes292d3512008-02-03 16:51:08 +00001523 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001524 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001525 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001526 if (py_exponent == NULL) goto error;
1527 INPLACE_UPDATE(py_exponent,
1528 long_methods->nb_lshift(denominator, py_exponent));
1529 if (py_exponent == NULL) goto error;
1530 if (exponent > 0) {
1531 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001532 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001533 if (numerator == NULL) goto error;
1534 }
1535 else {
1536 Py_DECREF(denominator);
1537 denominator = py_exponent;
1538 py_exponent = NULL;
1539 }
1540
1541 result_pair = PyTuple_Pack(2, numerator, denominator);
1542
1543#undef INPLACE_UPDATE
1544error:
1545 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001546 Py_XDECREF(denominator);
1547 Py_XDECREF(numerator);
1548 return result_pair;
1549}
1550
1551PyDoc_STRVAR(float_as_integer_ratio_doc,
1552"float.as_integer_ratio() -> (int, int)\n"
1553"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001554"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1555"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001556"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001557"\n"
1558">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001559"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001560">>> (0.0).as_integer_ratio()\n"
1561"(0, 1)\n"
1562">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001563"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001564
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001565
Jeremy Hylton938ace62002-07-17 16:30:39 +00001566static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001567float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1568
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569static PyObject *
1570float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1571{
1572 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001573 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574
Guido van Rossumbef14172001-08-29 15:47:46 +00001575 if (type != &PyFloat_Type)
1576 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1578 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001579 /* If it's a string, but not a string subclass, use
1580 PyFloat_FromString. */
1581 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001582 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 return PyNumber_Float(x);
1584}
1585
Guido van Rossumbef14172001-08-29 15:47:46 +00001586/* Wimpy, slow approach to tp_new calls for subtypes of float:
1587 first create a regular float from whatever arguments we got,
1588 then allocate a subtype instance and initialize its ob_fval
1589 from the regular float. The regular float is then thrown away.
1590*/
1591static PyObject *
1592float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1593{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001594 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001595
1596 assert(PyType_IsSubtype(type, &PyFloat_Type));
1597 tmp = float_new(&PyFloat_Type, args, kwds);
1598 if (tmp == NULL)
1599 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001600 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001601 newobj = type->tp_alloc(type, 0);
1602 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001603 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001604 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001605 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001606 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001607 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001608 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001609}
1610
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001611static PyObject *
1612float_getnewargs(PyFloatObject *v)
1613{
1614 return Py_BuildValue("(d)", v->ob_fval);
1615}
1616
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617/* this is for the benefit of the pack/unpack routines below */
1618
1619typedef enum {
1620 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1621} float_format_type;
1622
1623static float_format_type double_format, float_format;
1624static float_format_type detected_double_format, detected_float_format;
1625
1626static PyObject *
1627float_getformat(PyTypeObject *v, PyObject* arg)
1628{
1629 char* s;
1630 float_format_type r;
1631
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001632 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001633 PyErr_Format(PyExc_TypeError,
1634 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001635 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001636 return NULL;
1637 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001638 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001639 if (s == NULL)
1640 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001641 if (strcmp(s, "double") == 0) {
1642 r = double_format;
1643 }
1644 else if (strcmp(s, "float") == 0) {
1645 r = float_format;
1646 }
1647 else {
1648 PyErr_SetString(PyExc_ValueError,
1649 "__getformat__() argument 1 must be "
1650 "'double' or 'float'");
1651 return NULL;
1652 }
1653
1654 switch (r) {
1655 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001656 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001657 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001658 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001659 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001660 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001661 default:
1662 Py_FatalError("insane float_format or double_format");
1663 return NULL;
1664 }
1665}
1666
1667PyDoc_STRVAR(float_getformat_doc,
1668"float.__getformat__(typestr) -> string\n"
1669"\n"
1670"You probably don't want to use this function. It exists mainly to be\n"
1671"used in Python's test suite.\n"
1672"\n"
1673"typestr must be 'double' or 'float'. This function returns whichever of\n"
1674"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1675"format of floating point numbers used by the C type named by typestr.");
1676
1677static PyObject *
1678float_setformat(PyTypeObject *v, PyObject* args)
1679{
1680 char* typestr;
1681 char* format;
1682 float_format_type f;
1683 float_format_type detected;
1684 float_format_type *p;
1685
1686 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1687 return NULL;
1688
1689 if (strcmp(typestr, "double") == 0) {
1690 p = &double_format;
1691 detected = detected_double_format;
1692 }
1693 else if (strcmp(typestr, "float") == 0) {
1694 p = &float_format;
1695 detected = detected_float_format;
1696 }
1697 else {
1698 PyErr_SetString(PyExc_ValueError,
1699 "__setformat__() argument 1 must "
1700 "be 'double' or 'float'");
1701 return NULL;
1702 }
1703
1704 if (strcmp(format, "unknown") == 0) {
1705 f = unknown_format;
1706 }
1707 else if (strcmp(format, "IEEE, little-endian") == 0) {
1708 f = ieee_little_endian_format;
1709 }
1710 else if (strcmp(format, "IEEE, big-endian") == 0) {
1711 f = ieee_big_endian_format;
1712 }
1713 else {
1714 PyErr_SetString(PyExc_ValueError,
1715 "__setformat__() argument 2 must be "
1716 "'unknown', 'IEEE, little-endian' or "
1717 "'IEEE, big-endian'");
1718 return NULL;
1719
1720 }
1721
1722 if (f != unknown_format && f != detected) {
1723 PyErr_Format(PyExc_ValueError,
1724 "can only set %s format to 'unknown' or the "
1725 "detected platform value", typestr);
1726 return NULL;
1727 }
1728
1729 *p = f;
1730 Py_RETURN_NONE;
1731}
1732
1733PyDoc_STRVAR(float_setformat_doc,
1734"float.__setformat__(typestr, fmt) -> None\n"
1735"\n"
1736"You probably don't want to use this function. It exists mainly to be\n"
1737"used in Python's test suite.\n"
1738"\n"
1739"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1740"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1741"one of the latter two if it appears to match the underlying C reality.\n"
1742"\n"
1743"Overrides the automatic determination of C-level floating point type.\n"
1744"This affects how floats are converted to and from binary strings.");
1745
Guido van Rossumb43daf72007-08-01 18:08:08 +00001746static PyObject *
1747float_getzero(PyObject *v, void *closure)
1748{
1749 return PyFloat_FromDouble(0.0);
1750}
1751
Eric Smith8c663262007-08-25 02:26:07 +00001752static PyObject *
1753float__format__(PyObject *self, PyObject *args)
1754{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001755 PyObject *format_spec;
1756
1757 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1758 return NULL;
1759 return _PyFloat_FormatAdvanced(self,
1760 PyUnicode_AS_UNICODE(format_spec),
1761 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001762}
1763
1764PyDoc_STRVAR(float__format__doc,
1765"float.__format__(format_spec) -> string\n"
1766"\n"
1767"Formats the float according to format_spec.");
1768
1769
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001770static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001771 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001772 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001773 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1774 "Returns the Integral closest to x between 0 and x."},
1775 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1776 "Returns the Integral closest to x, rounding half toward even.\n"
1777 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001778 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1779 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001780 {"fromhex", (PyCFunction)float_fromhex,
1781 METH_O|METH_CLASS, float_fromhex_doc},
1782 {"hex", (PyCFunction)float_hex,
1783 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001784 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1785 "Returns True if the float is an integer."},
1786#if 0
1787 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1788 "Returns True if the float is positive or negative infinite."},
1789 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1790 "Returns True if the float is finite, neither infinite nor NaN."},
1791 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1792 "Returns True if the float is not a number (NaN)."},
1793#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001794 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001795 {"__getformat__", (PyCFunction)float_getformat,
1796 METH_O|METH_CLASS, float_getformat_doc},
1797 {"__setformat__", (PyCFunction)float_setformat,
1798 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001799 {"__format__", (PyCFunction)float__format__,
1800 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001801 {NULL, NULL} /* sentinel */
1802};
1803
Guido van Rossumb43daf72007-08-01 18:08:08 +00001804static PyGetSetDef float_getset[] = {
1805 {"real",
1806 (getter)float_float, (setter)NULL,
1807 "the real part of a complex number",
1808 NULL},
1809 {"imag",
1810 (getter)float_getzero, (setter)NULL,
1811 "the imaginary part of a complex number",
1812 NULL},
1813 {NULL} /* Sentinel */
1814};
1815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001816PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817"float(x) -> floating point number\n\
1818\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001819Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820
1821
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001822static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001823 float_add, /*nb_add*/
1824 float_sub, /*nb_subtract*/
1825 float_mul, /*nb_multiply*/
1826 float_rem, /*nb_remainder*/
1827 float_divmod, /*nb_divmod*/
1828 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001829 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001830 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001831 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001832 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001833 0, /*nb_invert*/
1834 0, /*nb_lshift*/
1835 0, /*nb_rshift*/
1836 0, /*nb_and*/
1837 0, /*nb_xor*/
1838 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001839 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001840 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001841 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001842 0, /* nb_inplace_add */
1843 0, /* nb_inplace_subtract */
1844 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001845 0, /* nb_inplace_remainder */
1846 0, /* nb_inplace_power */
1847 0, /* nb_inplace_lshift */
1848 0, /* nb_inplace_rshift */
1849 0, /* nb_inplace_and */
1850 0, /* nb_inplace_xor */
1851 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001852 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001853 float_div, /* nb_true_divide */
1854 0, /* nb_inplace_floor_divide */
1855 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856};
1857
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001858PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001859 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001860 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001861 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001862 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001863 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001864 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 0, /* tp_getattr */
1866 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001867 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 (reprfunc)float_repr, /* tp_repr */
1869 &float_as_number, /* tp_as_number */
1870 0, /* tp_as_sequence */
1871 0, /* tp_as_mapping */
1872 (hashfunc)float_hash, /* tp_hash */
1873 0, /* tp_call */
1874 (reprfunc)float_str, /* tp_str */
1875 PyObject_GenericGetAttr, /* tp_getattro */
1876 0, /* tp_setattro */
1877 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001878 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 float_doc, /* tp_doc */
1880 0, /* tp_traverse */
1881 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001882 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001883 0, /* tp_weaklistoffset */
1884 0, /* tp_iter */
1885 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001886 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001888 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 0, /* tp_base */
1890 0, /* tp_dict */
1891 0, /* tp_descr_get */
1892 0, /* tp_descr_set */
1893 0, /* tp_dictoffset */
1894 0, /* tp_init */
1895 0, /* tp_alloc */
1896 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001897};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001898
1899void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001900_PyFloat_Init(void)
1901{
1902 /* We attempt to determine if this machine is using IEEE
1903 floating point formats by peering at the bits of some
1904 carefully chosen values. If it looks like we are on an
1905 IEEE platform, the float packing/unpacking routines can
1906 just copy bits, if not they resort to arithmetic & shifts
1907 and masks. The shifts & masks approach works on all finite
1908 values, but what happens to infinities, NaNs and signed
1909 zeroes on packing is an accident, and attempting to unpack
1910 a NaN or an infinity will raise an exception.
1911
1912 Note that if we're on some whacked-out platform which uses
1913 IEEE formats but isn't strictly little-endian or big-
1914 endian, we will fall back to the portable shifts & masks
1915 method. */
1916
1917#if SIZEOF_DOUBLE == 8
1918 {
1919 double x = 9006104071832581.0;
1920 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1921 detected_double_format = ieee_big_endian_format;
1922 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1923 detected_double_format = ieee_little_endian_format;
1924 else
1925 detected_double_format = unknown_format;
1926 }
1927#else
1928 detected_double_format = unknown_format;
1929#endif
1930
1931#if SIZEOF_FLOAT == 4
1932 {
1933 float y = 16711938.0;
1934 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1935 detected_float_format = ieee_big_endian_format;
1936 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1937 detected_float_format = ieee_little_endian_format;
1938 else
1939 detected_float_format = unknown_format;
1940 }
1941#else
1942 detected_float_format = unknown_format;
1943#endif
1944
1945 double_format = detected_double_format;
1946 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001947
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001948 /* Init float info */
1949 if (FloatInfoType.tp_name == 0)
1950 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001951}
1952
Georg Brandl2ee470f2008-07-16 12:55:28 +00001953int
1954PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001955{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001956 PyFloatObject *p;
1957 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001958 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001959 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001960 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001961
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001962 list = block_list;
1963 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001964 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001965 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001966 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001967 for (i = 0, p = &list->objects[0];
1968 i < N_FLOATOBJECTS;
1969 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001970 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001971 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001972 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001973 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001974 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001975 list->next = block_list;
1976 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001977 for (i = 0, p = &list->objects[0];
1978 i < N_FLOATOBJECTS;
1979 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001980 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001981 Py_REFCNT(p) == 0) {
1982 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001983 free_list;
1984 free_list = p;
1985 }
1986 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001987 }
1988 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001989 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001990 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001991 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001992 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001993 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001994 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001995}
1996
1997void
1998PyFloat_Fini(void)
1999{
2000 PyFloatObject *p;
2001 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00002002 int i;
2003 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00002004
Georg Brandl2ee470f2008-07-16 12:55:28 +00002005 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00002006
Guido van Rossum3fce8831999-03-12 19:43:17 +00002007 if (!Py_VerboseFlag)
2008 return;
2009 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00002010 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002011 fprintf(stderr, "\n");
2012 }
2013 else {
2014 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00002015 ": %d unfreed float%s\n",
2016 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002017 }
2018 if (Py_VerboseFlag > 1) {
2019 list = block_list;
2020 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002021 for (i = 0, p = &list->objects[0];
2022 i < N_FLOATOBJECTS;
2023 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002024 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00002025 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00002026 char *buf = PyOS_double_to_string(
2027 PyFloat_AS_DOUBLE(p), 'r',
2028 0, 0, NULL);
2029 if (buf) {
2030 /* XXX(twouters) cast
2031 refcount to long
2032 until %zd is
2033 universally
2034 available
2035 */
2036 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002037 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00002038 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00002039 PyMem_Free(buf);
2040 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002041 }
2042 }
2043 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002044 }
2045 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002046}
Tim Peters9905b942003-03-20 20:53:32 +00002047
2048/*----------------------------------------------------------------------------
2049 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002050 */
2051int
2052_PyFloat_Pack4(double x, unsigned char *p, int le)
2053{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002054 if (float_format == unknown_format) {
2055 unsigned char sign;
2056 int e;
2057 double f;
2058 unsigned int fbits;
2059 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002060
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002061 if (le) {
2062 p += 3;
2063 incr = -1;
2064 }
Tim Peters9905b942003-03-20 20:53:32 +00002065
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002066 if (x < 0) {
2067 sign = 1;
2068 x = -x;
2069 }
2070 else
2071 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002072
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002073 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002074
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002075 /* Normalize f to be in the range [1.0, 2.0) */
2076 if (0.5 <= f && f < 1.0) {
2077 f *= 2.0;
2078 e--;
2079 }
2080 else if (f == 0.0)
2081 e = 0;
2082 else {
2083 PyErr_SetString(PyExc_SystemError,
2084 "frexp() result out of range");
2085 return -1;
2086 }
2087
2088 if (e >= 128)
2089 goto Overflow;
2090 else if (e < -126) {
2091 /* Gradual underflow */
2092 f = ldexp(f, 126 + e);
2093 e = 0;
2094 }
2095 else if (!(e == 0 && f == 0.0)) {
2096 e += 127;
2097 f -= 1.0; /* Get rid of leading 1 */
2098 }
2099
2100 f *= 8388608.0; /* 2**23 */
2101 fbits = (unsigned int)(f + 0.5); /* Round */
2102 assert(fbits <= 8388608);
2103 if (fbits >> 23) {
2104 /* The carry propagated out of a string of 23 1 bits. */
2105 fbits = 0;
2106 ++e;
2107 if (e >= 255)
2108 goto Overflow;
2109 }
2110
2111 /* First byte */
2112 *p = (sign << 7) | (e >> 1);
2113 p += incr;
2114
2115 /* Second byte */
2116 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2117 p += incr;
2118
2119 /* Third byte */
2120 *p = (fbits >> 8) & 0xFF;
2121 p += incr;
2122
2123 /* Fourth byte */
2124 *p = fbits & 0xFF;
2125
2126 /* Done */
2127 return 0;
2128
Tim Peters9905b942003-03-20 20:53:32 +00002129 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002130 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002131 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002132 const char *s = (char*)&y;
2133 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002134
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002135 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2136 goto Overflow;
2137
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138 if ((float_format == ieee_little_endian_format && !le)
2139 || (float_format == ieee_big_endian_format && le)) {
2140 p += 3;
2141 incr = -1;
2142 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002143
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002144 for (i = 0; i < 4; i++) {
2145 *p = *s++;
2146 p += incr;
2147 }
2148 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002149 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002150 Overflow:
2151 PyErr_SetString(PyExc_OverflowError,
2152 "float too large to pack with f format");
2153 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002154}
2155
2156int
2157_PyFloat_Pack8(double x, unsigned char *p, int le)
2158{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159 if (double_format == unknown_format) {
2160 unsigned char sign;
2161 int e;
2162 double f;
2163 unsigned int fhi, flo;
2164 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002165
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002166 if (le) {
2167 p += 7;
2168 incr = -1;
2169 }
Tim Peters9905b942003-03-20 20:53:32 +00002170
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171 if (x < 0) {
2172 sign = 1;
2173 x = -x;
2174 }
2175 else
2176 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002177
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002178 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002179
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002180 /* Normalize f to be in the range [1.0, 2.0) */
2181 if (0.5 <= f && f < 1.0) {
2182 f *= 2.0;
2183 e--;
2184 }
2185 else if (f == 0.0)
2186 e = 0;
2187 else {
2188 PyErr_SetString(PyExc_SystemError,
2189 "frexp() result out of range");
2190 return -1;
2191 }
2192
2193 if (e >= 1024)
2194 goto Overflow;
2195 else if (e < -1022) {
2196 /* Gradual underflow */
2197 f = ldexp(f, 1022 + e);
2198 e = 0;
2199 }
2200 else if (!(e == 0 && f == 0.0)) {
2201 e += 1023;
2202 f -= 1.0; /* Get rid of leading 1 */
2203 }
2204
2205 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2206 f *= 268435456.0; /* 2**28 */
2207 fhi = (unsigned int)f; /* Truncate */
2208 assert(fhi < 268435456);
2209
2210 f -= (double)fhi;
2211 f *= 16777216.0; /* 2**24 */
2212 flo = (unsigned int)(f + 0.5); /* Round */
2213 assert(flo <= 16777216);
2214 if (flo >> 24) {
2215 /* The carry propagated out of a string of 24 1 bits. */
2216 flo = 0;
2217 ++fhi;
2218 if (fhi >> 28) {
2219 /* And it also progagated out of the next 28 bits. */
2220 fhi = 0;
2221 ++e;
2222 if (e >= 2047)
2223 goto Overflow;
2224 }
2225 }
2226
2227 /* First byte */
2228 *p = (sign << 7) | (e >> 4);
2229 p += incr;
2230
2231 /* Second byte */
2232 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2233 p += incr;
2234
2235 /* Third byte */
2236 *p = (fhi >> 16) & 0xFF;
2237 p += incr;
2238
2239 /* Fourth byte */
2240 *p = (fhi >> 8) & 0xFF;
2241 p += incr;
2242
2243 /* Fifth byte */
2244 *p = fhi & 0xFF;
2245 p += incr;
2246
2247 /* Sixth byte */
2248 *p = (flo >> 16) & 0xFF;
2249 p += incr;
2250
2251 /* Seventh byte */
2252 *p = (flo >> 8) & 0xFF;
2253 p += incr;
2254
2255 /* Eighth byte */
2256 *p = flo & 0xFF;
2257 p += incr;
2258
2259 /* Done */
2260 return 0;
2261
2262 Overflow:
2263 PyErr_SetString(PyExc_OverflowError,
2264 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002265 return -1;
2266 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002267 else {
2268 const char *s = (char*)&x;
2269 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002270
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002271 if ((double_format == ieee_little_endian_format && !le)
2272 || (double_format == ieee_big_endian_format && le)) {
2273 p += 7;
2274 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002275 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002276
2277 for (i = 0; i < 8; i++) {
2278 *p = *s++;
2279 p += incr;
2280 }
2281 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002282 }
Tim Peters9905b942003-03-20 20:53:32 +00002283}
2284
2285double
2286_PyFloat_Unpack4(const unsigned char *p, int le)
2287{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002288 if (float_format == unknown_format) {
2289 unsigned char sign;
2290 int e;
2291 unsigned int f;
2292 double x;
2293 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002294
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002295 if (le) {
2296 p += 3;
2297 incr = -1;
2298 }
2299
2300 /* First byte */
2301 sign = (*p >> 7) & 1;
2302 e = (*p & 0x7F) << 1;
2303 p += incr;
2304
2305 /* Second byte */
2306 e |= (*p >> 7) & 1;
2307 f = (*p & 0x7F) << 16;
2308 p += incr;
2309
2310 if (e == 255) {
2311 PyErr_SetString(
2312 PyExc_ValueError,
2313 "can't unpack IEEE 754 special value "
2314 "on non-IEEE platform");
2315 return -1;
2316 }
2317
2318 /* Third byte */
2319 f |= *p << 8;
2320 p += incr;
2321
2322 /* Fourth byte */
2323 f |= *p;
2324
2325 x = (double)f / 8388608.0;
2326
2327 /* XXX This sadly ignores Inf/NaN issues */
2328 if (e == 0)
2329 e = -126;
2330 else {
2331 x += 1.0;
2332 e -= 127;
2333 }
2334 x = ldexp(x, e);
2335
2336 if (sign)
2337 x = -x;
2338
2339 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002340 }
Tim Peters9905b942003-03-20 20:53:32 +00002341 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002342 float x;
2343
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344 if ((float_format == ieee_little_endian_format && !le)
2345 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002346 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002347 char *d = &buf[3];
2348 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002349
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002350 for (i = 0; i < 4; i++) {
2351 *d-- = *p++;
2352 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002353 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354 }
2355 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002356 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002357 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002358
2359 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360 }
Tim Peters9905b942003-03-20 20:53:32 +00002361}
2362
2363double
2364_PyFloat_Unpack8(const unsigned char *p, int le)
2365{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002366 if (double_format == unknown_format) {
2367 unsigned char sign;
2368 int e;
2369 unsigned int fhi, flo;
2370 double x;
2371 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002372
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002373 if (le) {
2374 p += 7;
2375 incr = -1;
2376 }
2377
2378 /* First byte */
2379 sign = (*p >> 7) & 1;
2380 e = (*p & 0x7F) << 4;
2381
2382 p += incr;
2383
2384 /* Second byte */
2385 e |= (*p >> 4) & 0xF;
2386 fhi = (*p & 0xF) << 24;
2387 p += incr;
2388
2389 if (e == 2047) {
2390 PyErr_SetString(
2391 PyExc_ValueError,
2392 "can't unpack IEEE 754 special value "
2393 "on non-IEEE platform");
2394 return -1.0;
2395 }
2396
2397 /* Third byte */
2398 fhi |= *p << 16;
2399 p += incr;
2400
2401 /* Fourth byte */
2402 fhi |= *p << 8;
2403 p += incr;
2404
2405 /* Fifth byte */
2406 fhi |= *p;
2407 p += incr;
2408
2409 /* Sixth byte */
2410 flo = *p << 16;
2411 p += incr;
2412
2413 /* Seventh byte */
2414 flo |= *p << 8;
2415 p += incr;
2416
2417 /* Eighth byte */
2418 flo |= *p;
2419
2420 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2421 x /= 268435456.0; /* 2**28 */
2422
2423 if (e == 0)
2424 e = -1022;
2425 else {
2426 x += 1.0;
2427 e -= 1023;
2428 }
2429 x = ldexp(x, e);
2430
2431 if (sign)
2432 x = -x;
2433
2434 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002435 }
Tim Peters9905b942003-03-20 20:53:32 +00002436 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002437 double x;
2438
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002439 if ((double_format == ieee_little_endian_format && !le)
2440 || (double_format == ieee_big_endian_format && le)) {
2441 char buf[8];
2442 char *d = &buf[7];
2443 int i;
2444
2445 for (i = 0; i < 8; i++) {
2446 *d-- = *p++;
2447 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002448 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002449 }
2450 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002451 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002452 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002453
2454 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002455 }
Tim Peters9905b942003-03-20 20:53:32 +00002456}