blob: 238022b3bc89ec5f025f2d8c566fda498cafc28f [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
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Christian Heimes969fe572008-01-25 11:23:10 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000026#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000027#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
30 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
32};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
42 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000043 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000047 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 q = p + N_FLOATOBJECTS;
51 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000052 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 return p + N_FLOATOBJECTS - 1;
55}
56
Christian Heimes93852662007-12-01 12:22:32 +000057double
58PyFloat_GetMax(void)
59{
60 return DBL_MAX;
61}
62
63double
64PyFloat_GetMin(void)
65{
66 return DBL_MIN;
67}
68
Christian Heimesd32ed6f2008-01-14 18:49:24 +000069static PyTypeObject FloatInfoType;
70
71PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000072"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
79 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
96};
97
98static PyStructSequence_Desc floatinfo_desc = {
Benjamin Peterson78565b22009-06-28 19:19:51 +000099 "sys.float_info", /* name */
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
103};
104
Christian Heimes93852662007-12-01 12:22:32 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000108 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000109 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000110
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000111 floatinfo = PyStructSequence_New(&FloatInfoType);
112 if (floatinfo == NULL) {
113 return NULL;
114 }
Christian Heimes93852662007-12-01 12:22:32 +0000115
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000116#define SetIntFlag(flag) \
117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
118#define SetDblFlag(flag) \
119 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000120
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000121 SetDblFlag(DBL_MAX);
122 SetIntFlag(DBL_MAX_EXP);
123 SetIntFlag(DBL_MAX_10_EXP);
124 SetDblFlag(DBL_MIN);
125 SetIntFlag(DBL_MIN_EXP);
126 SetIntFlag(DBL_MIN_10_EXP);
127 SetIntFlag(DBL_DIG);
128 SetIntFlag(DBL_MANT_DIG);
129 SetDblFlag(DBL_EPSILON);
130 SetIntFlag(FLT_RADIX);
131 SetIntFlag(FLT_ROUNDS);
132#undef SetIntFlag
133#undef SetDblFlag
134
135 if (PyErr_Occurred()) {
136 Py_CLEAR(floatinfo);
137 return NULL;
138 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000139 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000140}
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000145 register PyFloatObject *op;
146 if (free_list == NULL) {
147 if ((free_list = fill_free_list()) == NULL)
148 return NULL;
149 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000150 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000151 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000152 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000153 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000154 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000158PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000159PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160{
Mark Dickinson6d65df12009-04-26 15:30:47 +0000161 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000163 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000164 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000166 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000168 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000169 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
170 if (s_buffer == NULL)
171 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000172 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000173 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000174 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000175 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000176 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000178 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000180 else if (PyObject_AsCharBuffer(v, &s, &len)) {
181 PyErr_SetString(PyExc_TypeError,
Mark Dickinsone0d6f602009-10-26 21:12:50 +0000182 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000183 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000185 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000186
Mark Dickinsonaa77d262009-05-03 21:07:13 +0000187 while (Py_ISSPACE(*s))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 s++;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000189 /* We don't care about overflow or underflow. If the platform
190 * supports them, infinities and signed zeroes (on underflow) are
191 * fine. */
Mark Dickinson725bfd82009-05-03 20:33:40 +0000192 x = PyOS_string_to_double(s, (char **)&end, NULL);
193 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum2be161d2007-05-15 20:43:51 +0000194 goto error;
Mark Dickinsonaa77d262009-05-03 21:07:13 +0000195 while (Py_ISSPACE(*end))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 end++;
Mark Dickinson725bfd82009-05-03 20:33:40 +0000197 if (end == last)
198 result = PyFloat_FromDouble(x);
199 else {
200 PyOS_snprintf(buffer, sizeof(buffer),
201 "invalid literal for float(): %.200s", s);
202 PyErr_SetString(PyExc_ValueError, buffer);
203 result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000204 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000205
Guido van Rossum2be161d2007-05-15 20:43:51 +0000206 error:
207 if (s_buffer)
208 PyMem_FREE(s_buffer);
209 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210}
211
Guido van Rossum234f9421993-06-17 12:35:49 +0000212static void
Fred Drakefd99de62000-07-09 05:02:18 +0000213float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000214{
Guido van Rossum9475a232001-10-05 20:51:39 +0000215 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000216 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000217 free_list = op;
218 }
219 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000220 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000221}
222
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223double
Fred Drakefd99de62000-07-09 05:02:18 +0000224PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226 PyNumberMethods *nb;
227 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000228 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000229
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230 if (op && PyFloat_Check(op))
231 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000232
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000233 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 return -1;
236 }
Tim Petersd2364e82001-11-01 20:09:42 +0000237
Christian Heimes90aa7642007-12-19 02:45:37 +0000238 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000239 PyErr_SetString(PyExc_TypeError, "a float is required");
240 return -1;
241 }
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000244 if (fo == NULL)
245 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 if (!PyFloat_Check(fo)) {
247 PyErr_SetString(PyExc_TypeError,
248 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000249 return -1;
250 }
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000252 val = PyFloat_AS_DOUBLE(fo);
253 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000254
Guido van Rossumb6775db1994-08-01 11:34:53 +0000255 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256}
257
Neil Schemenauer32117e52001-01-04 01:44:34 +0000258/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000259 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000260 set to NULL, and the function invoking this macro returns NULL. If
261 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
262 stored in obj, and returned from the function invoking this macro.
263*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264#define CONVERT_TO_DOUBLE(obj, dbl) \
265 if (PyFloat_Check(obj)) \
266 dbl = PyFloat_AS_DOUBLE(obj); \
267 else if (convert_to_double(&(obj), &(dbl)) < 0) \
268 return obj;
269
Eric Smith0923d1d2009-04-16 20:16:10 +0000270/* Methods */
271
Neil Schemenauer32117e52001-01-04 01:44:34 +0000272static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000273convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000274{
275 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000276
Guido van Rossumddefaf32007-01-14 03:31:43 +0000277 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000279 if (*dbl == -1.0 && PyErr_Occurred()) {
280 *v = NULL;
281 return -1;
282 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000283 }
284 else {
285 Py_INCREF(Py_NotImplemented);
286 *v = Py_NotImplemented;
287 return -1;
288 }
289 return 0;
290}
291
Eric Smith0923d1d2009-04-16 20:16:10 +0000292static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000293float_str_or_repr(PyFloatObject *v, int precision, char format_code)
Eric Smith0923d1d2009-04-16 20:16:10 +0000294{
295 PyObject *result;
296 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Eric Smith63376222009-05-05 14:04:18 +0000297 format_code, precision,
298 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000299 NULL);
300 if (!buf)
301 return PyErr_NoMemory();
302 result = PyUnicode_FromString(buf);
303 PyMem_Free(buf);
304 return result;
305}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000306
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000308float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Eric Smith63376222009-05-05 14:04:18 +0000310 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000311}
312
313static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000314float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000315{
Eric Smith63376222009-05-05 14:04:18 +0000316 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317}
318
Tim Peters307fa782004-09-23 08:06:40 +0000319/* Comparison is pretty much a nightmare. When comparing float to float,
320 * we do it as straightforwardly (and long-windedly) as conceivable, so
321 * that, e.g., Python x == y delivers the same result as the platform
322 * C x == y when x and/or y is a NaN.
323 * When mixing float with an integer type, there's no good *uniform* approach.
324 * Converting the double to an integer obviously doesn't work, since we
325 * may lose info from fractional bits. Converting the integer to a double
326 * also has two failure modes: (1) a long int may trigger overflow (too
327 * large to fit in the dynamic range of a C double); (2) even a C long may have
328 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
329 * 63 bits of precision, but a C double probably has only 53), and then
330 * we can falsely claim equality when low-order integer bits are lost by
331 * coercion to double. So this part is painful too.
332 */
333
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000334static PyObject*
335float_richcompare(PyObject *v, PyObject *w, int op)
336{
337 double i, j;
338 int r = 0;
339
Tim Peters307fa782004-09-23 08:06:40 +0000340 assert(PyFloat_Check(v));
341 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342
Tim Peters307fa782004-09-23 08:06:40 +0000343 /* Switch on the type of w. Set i and j to doubles to be compared,
344 * and op to the richcomp to use.
345 */
346 if (PyFloat_Check(w))
347 j = PyFloat_AS_DOUBLE(w);
348
Thomas Wouters477c8d52006-05-27 19:21:47 +0000349 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000350 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000351 /* If i is an infinity, its magnitude exceeds any
352 * finite integer, so it doesn't matter which int we
353 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000354 */
355 j = 0.0;
356 else
357 goto Unimplemented;
358 }
359
Tim Peters307fa782004-09-23 08:06:40 +0000360 else if (PyLong_Check(w)) {
361 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
362 int wsign = _PyLong_Sign(w);
363 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000364 int exponent;
365
366 if (vsign != wsign) {
367 /* Magnitudes are irrelevant -- the signs alone
368 * determine the outcome.
369 */
370 i = (double)vsign;
371 j = (double)wsign;
372 goto Compare;
373 }
374 /* The signs are the same. */
375 /* Convert w to a double if it fits. In particular, 0 fits. */
376 nbits = _PyLong_NumBits(w);
377 if (nbits == (size_t)-1 && PyErr_Occurred()) {
378 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000379 * to hold the # of bits. Replace with little doubles
380 * that give the same outcome -- w is so large that
381 * its magnitude must exceed the magnitude of any
382 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000383 */
384 PyErr_Clear();
385 i = (double)vsign;
386 assert(wsign != 0);
387 j = wsign * 2.0;
388 goto Compare;
389 }
390 if (nbits <= 48) {
391 j = PyLong_AsDouble(w);
392 /* It's impossible that <= 48 bits overflowed. */
393 assert(j != -1.0 || ! PyErr_Occurred());
394 goto Compare;
395 }
396 assert(wsign != 0); /* else nbits was 0 */
397 assert(vsign != 0); /* if vsign were 0, then since wsign is
398 * not 0, we would have taken the
399 * vsign != wsign branch at the start */
400 /* We want to work with non-negative numbers. */
401 if (vsign < 0) {
402 /* "Multiply both sides" by -1; this also swaps the
403 * comparator.
404 */
405 i = -i;
406 op = _Py_SwappedOp[op];
407 }
408 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000409 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000410 /* exponent is the # of bits in v before the radix point;
411 * we know that nbits (the # of bits in w) > 48 at this point
412 */
413 if (exponent < 0 || (size_t)exponent < nbits) {
414 i = 1.0;
415 j = 2.0;
416 goto Compare;
417 }
418 if ((size_t)exponent > nbits) {
419 i = 2.0;
420 j = 1.0;
421 goto Compare;
422 }
423 /* v and w have the same number of bits before the radix
424 * point. Construct two longs that have the same comparison
425 * outcome.
426 */
427 {
428 double fracpart;
429 double intpart;
430 PyObject *result = NULL;
431 PyObject *one = NULL;
432 PyObject *vv = NULL;
433 PyObject *ww = w;
434
435 if (wsign < 0) {
436 ww = PyNumber_Negative(w);
437 if (ww == NULL)
438 goto Error;
439 }
440 else
441 Py_INCREF(ww);
442
443 fracpart = modf(i, &intpart);
444 vv = PyLong_FromDouble(intpart);
445 if (vv == NULL)
446 goto Error;
447
448 if (fracpart != 0.0) {
449 /* Shift left, and or a 1 bit into vv
450 * to represent the lost fraction.
451 */
452 PyObject *temp;
453
Christian Heimes217cfd12007-12-02 14:31:20 +0000454 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000455 if (one == NULL)
456 goto Error;
457
458 temp = PyNumber_Lshift(ww, one);
459 if (temp == NULL)
460 goto Error;
461 Py_DECREF(ww);
462 ww = temp;
463
464 temp = PyNumber_Lshift(vv, one);
465 if (temp == NULL)
466 goto Error;
467 Py_DECREF(vv);
468 vv = temp;
469
470 temp = PyNumber_Or(vv, one);
471 if (temp == NULL)
472 goto Error;
473 Py_DECREF(vv);
474 vv = temp;
475 }
476
477 r = PyObject_RichCompareBool(vv, ww, op);
478 if (r < 0)
479 goto Error;
480 result = PyBool_FromLong(r);
481 Error:
482 Py_XDECREF(vv);
483 Py_XDECREF(ww);
484 Py_XDECREF(one);
485 return result;
486 }
487 } /* else if (PyLong_Check(w)) */
488
489 else /* w isn't float, int, or long */
490 goto Unimplemented;
491
492 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000493 PyFPE_START_PROTECT("richcompare", return NULL)
494 switch (op) {
495 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000496 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000497 break;
498 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000499 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000500 break;
501 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000502 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000503 break;
504 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000505 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000506 break;
507 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000508 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000509 break;
510 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000511 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000512 break;
513 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000514 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000515 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000516
517 Unimplemented:
518 Py_INCREF(Py_NotImplemented);
519 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000520}
521
Guido van Rossum9bfef441993-03-29 10:43:31 +0000522static long
Fred Drakefd99de62000-07-09 05:02:18 +0000523float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000524{
Tim Peters39dce292000-08-15 03:34:48 +0000525 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526}
527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000531 double a,b;
532 CONVERT_TO_DOUBLE(v, a);
533 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000534 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000535 a = a + b;
536 PyFPE_END_PROTECT(a)
537 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538}
539
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543 double a,b;
544 CONVERT_TO_DOUBLE(v, a);
545 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000546 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000547 a = a - b;
548 PyFPE_END_PROTECT(a)
549 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000555 double a,b;
556 CONVERT_TO_DOUBLE(v, a);
557 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000558 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000559 a = a * b;
560 PyFPE_END_PROTECT(a)
561 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000567 double a,b;
568 CONVERT_TO_DOUBLE(v, a);
569 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000570#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000571 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000572 PyErr_SetString(PyExc_ZeroDivisionError,
Ezio Melotti50363262010-02-22 16:34:50 +0000573 "float division by zero");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574 return NULL;
575 }
Christian Heimes53876d92008-04-19 00:31:39 +0000576#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000577 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000578 a = a / b;
579 PyFPE_END_PROTECT(a)
580 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000586 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000587 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000588 CONVERT_TO_DOUBLE(v, vx);
589 CONVERT_TO_DOUBLE(w, wx);
590#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000592 PyErr_SetString(PyExc_ZeroDivisionError,
593 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594 return NULL;
595 }
Christian Heimes53876d92008-04-19 00:31:39 +0000596#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000597 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000598 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000599 /* note: checking mod*wx < 0 is incorrect -- underflows to
600 0 if wx < sqrt(smallest nonzero double) */
601 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000602 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000603 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000604 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606}
607
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000609float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000610{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000611 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000612 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000613 CONVERT_TO_DOUBLE(v, vx);
614 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000615 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000617 return NULL;
618 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000619 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000620 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000621 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000622 exact multiple of wx. But this is fp arithmetic, and fp
623 vx - mod is an approximation; the result is that div may
624 not be an exact integral value after the division, although
625 it will always be very close to one.
626 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000627 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000628 if (mod) {
629 /* ensure the remainder has the same sign as the denominator */
630 if ((wx < 0) != (mod < 0)) {
631 mod += wx;
632 div -= 1.0;
633 }
634 }
635 else {
636 /* the remainder is zero, and in the presence of signed zeroes
637 fmod returns different results across platforms; ensure
638 it has the same sign as the denominator; we'd like to do
639 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000640 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000641 if (wx < 0.0)
642 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000643 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000644 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000645 if (div) {
646 floordiv = floor(div);
647 if (div - floordiv > 0.5)
648 floordiv += 1.0;
649 }
650 else {
651 /* div is zero - get the same sign as the true quotient */
652 div *= div; /* hide "div = +0" from optimizers */
653 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
654 }
655 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000656 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000660float_floor_div(PyObject *v, PyObject *w)
661{
662 PyObject *t, *r;
663
664 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000665 if (t == NULL || t == Py_NotImplemented)
666 return t;
667 assert(PyTuple_CheckExact(t));
668 r = PyTuple_GET_ITEM(t, 0);
669 Py_INCREF(r);
670 Py_DECREF(t);
671 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000672}
673
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000674/* determine whether x is an odd integer or not; assumes that
675 x is not an infinity or nan. */
676#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
677
Tim Peters63a35712001-12-11 19:57:24 +0000678static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680{
681 double iv, iw, ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000682 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000683
684 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000685 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000686 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000687 return NULL;
688 }
689
Neil Schemenauer32117e52001-01-04 01:44:34 +0000690 CONVERT_TO_DOUBLE(v, iv);
691 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000692
693 /* Sort out special cases here instead of relying on pow() */
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000694 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000695 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000696 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000697 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
698 return PyFloat_FromDouble(iv);
699 }
700 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
701 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
702 }
703 if (Py_IS_INFINITY(iw)) {
704 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
705 * abs(v) > 1 (including case where v infinite)
706 *
707 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
708 * abs(v) > 1 (including case where v infinite)
709 */
710 iv = fabs(iv);
711 if (iv == 1.0)
712 return PyFloat_FromDouble(1.0);
713 else if ((iw > 0.0) == (iv > 1.0))
714 return PyFloat_FromDouble(fabs(iw)); /* return inf */
715 else
716 return PyFloat_FromDouble(0.0);
717 }
718 if (Py_IS_INFINITY(iv)) {
719 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
720 * both cases, we need to add the appropriate sign if w is
721 * an odd integer.
722 */
723 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
724 if (iw > 0.0)
725 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
726 else
727 return PyFloat_FromDouble(iw_is_odd ?
728 copysign(0.0, iv) : 0.0);
729 }
730 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
731 (already dealt with above), and an error
732 if w is negative. */
733 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000734 if (iw < 0.0) {
735 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000736 "0.0 cannot be raised to a "
737 "negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000738 return NULL;
739 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000740 /* use correct sign if iw is odd */
741 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000742 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000743
Tim Peterse87568d2003-05-24 20:18:24 +0000744 if (iv < 0.0) {
745 /* Whether this is an error is a mess, and bumps into libm
746 * bugs so we have to figure it out ourselves.
747 */
748 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000749 /* Negative numbers raised to fractional powers
750 * become complex.
751 */
752 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000753 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000754 /* iw is an exact integer, albeit perhaps a very large
755 * one. Replace iv by its absolute value and remember
756 * to negate the pow result if iw is odd.
757 */
758 iv = -iv;
759 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
760 }
761
762 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
763 /* (-1) ** large_integer also ends up here. Here's an
764 * extract from the comments for the previous
765 * implementation explaining why this special case is
766 * necessary:
767 *
Tim Peterse87568d2003-05-24 20:18:24 +0000768 * -1 raised to an exact integer should never be exceptional.
769 * Alas, some libms (chiefly glibc as of early 2003) return
770 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
771 * happen to be representable in a *C* integer. That's a
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000772 * bug.
Tim Peterse87568d2003-05-24 20:18:24 +0000773 */
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000774 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
Guido van Rossum86c04c21996-08-09 20:50:14 +0000775 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000776
777 /* Now iv and iw are finite, iw is nonzero, and iv is
778 * positive and not equal to 1.0. We finally allow
779 * the platform pow to step in and do the rest.
780 */
Tim Peters96685bf2001-08-23 22:31:37 +0000781 errno = 0;
782 PyFPE_START_PROTECT("pow", return NULL)
783 ix = pow(iv, iw);
784 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000785 Py_ADJUST_ERANGE1(ix);
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000786 if (negate_result)
787 ix = -ix;
788
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000789 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000790 /* We don't expect any errno value other than ERANGE, but
791 * the range of libm bugs appears unbounded.
792 */
793 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
794 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000796 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798}
799
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000800#undef DOUBLE_IS_ODD_INTEGER
801
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000802static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000803float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000805 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806}
807
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000809float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000810{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000811 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000814static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000815float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000816{
817 return v->ob_fval != 0.0;
818}
819
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000820static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000821float_is_integer(PyObject *v)
822{
823 double x = PyFloat_AsDouble(v);
824 PyObject *o;
825
826 if (x == -1.0 && PyErr_Occurred())
827 return NULL;
828 if (!Py_IS_FINITE(x))
829 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000830 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000831 PyFPE_START_PROTECT("is_integer", return NULL)
832 o = (floor(x) == x) ? Py_True : Py_False;
833 PyFPE_END_PROTECT(x)
834 if (errno != 0) {
835 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
836 PyExc_ValueError);
837 return NULL;
838 }
839 Py_INCREF(o);
840 return o;
841}
842
843#if 0
844static PyObject *
845float_is_inf(PyObject *v)
846{
847 double x = PyFloat_AsDouble(v);
848 if (x == -1.0 && PyErr_Occurred())
849 return NULL;
850 return PyBool_FromLong((long)Py_IS_INFINITY(x));
851}
852
853static PyObject *
854float_is_nan(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_NAN(x));
860}
861
862static PyObject *
863float_is_finite(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_FINITE(x));
869}
870#endif
871
872static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000873float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000874{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000875 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000876 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000877
878 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000879 /* Try to get out cheap if this fits in a Python int. The attempt
880 * to cast to long must be protected, as C doesn't define what
881 * happens if the double is too big to fit in a long. Some rare
882 * systems raise an exception then (RISCOS was mentioned as one,
883 * and someone using a non-default option on Sun also bumped into
884 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
885 * still be vulnerable: if a long has more bits of precision than
886 * a double, casting MIN/MAX to double may yield an approximation,
887 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
888 * yield true from the C expression wholepart<=LONG_MAX, despite
889 * that wholepart is actually greater than LONG_MAX.
890 */
891 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
892 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000893 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000894 }
895 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000896}
897
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000898/* double_round: rounds a finite double to the closest multiple of
899 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
900 ndigits <= 323). Returns a Python float, or sets a Python error and
901 returns NULL on failure (OverflowError and memory errors are possible). */
902
903#ifndef PY_NO_SHORT_FLOAT_REPR
904/* version of double_round that uses the correctly-rounded string<->double
905 conversions from Python/dtoa.c */
906
907static PyObject *
908double_round(double x, int ndigits) {
909
910 double rounded;
911 Py_ssize_t buflen, mybuflen=100;
912 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
913 int decpt, sign;
914 PyObject *result = NULL;
915
916 /* round to a decimal string */
917 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
918 if (buf == NULL) {
919 PyErr_NoMemory();
920 return NULL;
921 }
922
923 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
924 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
925 buflen = buf_end - buf;
926 if (buflen + 8 > mybuflen) {
927 mybuflen = buflen+8;
928 mybuf = (char *)PyMem_Malloc(mybuflen);
929 if (mybuf == NULL) {
930 PyErr_NoMemory();
931 goto exit;
932 }
933 }
934 /* copy buf to mybuf, adding exponent, sign and leading 0 */
935 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
936 buf, decpt - (int)buflen);
937
938 /* and convert the resulting string back to a double */
939 errno = 0;
940 rounded = _Py_dg_strtod(mybuf, NULL);
941 if (errno == ERANGE && fabs(rounded) >= 1.)
942 PyErr_SetString(PyExc_OverflowError,
943 "rounded value too large to represent");
944 else
945 result = PyFloat_FromDouble(rounded);
946
947 /* done computing value; now clean up */
948 if (mybuf != shortbuf)
949 PyMem_Free(mybuf);
950 exit:
951 _Py_dg_freedtoa(buf);
952 return result;
953}
954
955#else /* PY_NO_SHORT_FLOAT_REPR */
956
957/* fallback version, to be used when correctly rounded binary<->decimal
958 conversions aren't available */
959
960static PyObject *
961double_round(double x, int ndigits) {
962 double pow1, pow2, y, z;
963 if (ndigits >= 0) {
964 if (ndigits > 22) {
965 /* pow1 and pow2 are each safe from overflow, but
966 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
967 pow1 = pow(10.0, (double)(ndigits-22));
968 pow2 = 1e22;
969 }
970 else {
971 pow1 = pow(10.0, (double)ndigits);
972 pow2 = 1.0;
973 }
974 y = (x*pow1)*pow2;
975 /* if y overflows, then rounded value is exactly x */
976 if (!Py_IS_FINITE(y))
977 return PyFloat_FromDouble(x);
978 }
979 else {
980 pow1 = pow(10.0, (double)-ndigits);
981 pow2 = 1.0; /* unused; silences a gcc compiler warning */
982 y = x / pow1;
983 }
984
985 z = round(y);
986 if (fabs(y-z) == 0.5)
987 /* halfway between two integers; use round-half-even */
988 z = 2.0*round(y/2.0);
989
990 if (ndigits >= 0)
991 z = (z / pow2) / pow1;
992 else
993 z *= pow1;
994
995 /* if computation resulted in overflow, raise OverflowError */
996 if (!Py_IS_FINITE(z)) {
997 PyErr_SetString(PyExc_OverflowError,
998 "overflow occurred during round");
999 return NULL;
1000 }
1001
1002 return PyFloat_FromDouble(z);
1003}
1004
1005#endif /* PY_NO_SHORT_FLOAT_REPR */
1006
1007/* round a Python float v to the closest multiple of 10**-ndigits */
1008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001009static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001010float_round(PyObject *v, PyObject *args)
1011{
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001012 double x, rounded;
1013 PyObject *o_ndigits = NULL;
1014 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001015
1016 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001017 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1018 return NULL;
1019 if (o_ndigits == NULL) {
1020 /* single-argument round: round to nearest integer */
1021 rounded = round(x);
1022 if (fabs(x-rounded) == 0.5)
1023 /* halfway case: round to even */
1024 rounded = 2.0*round(x/2.0);
1025 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001026 }
1027
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001028 /* interpret second argument as a Py_ssize_t; clips on overflow */
1029 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1030 if (ndigits == -1 && PyErr_Occurred())
1031 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001032
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001033 /* nans and infinities round to themselves */
1034 if (!Py_IS_FINITE(x))
1035 return PyFloat_FromDouble(x);
1036
1037 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1038 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1039 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
1040#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1041#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
1042 if (ndigits > NDIGITS_MAX)
1043 /* return x */
1044 return PyFloat_FromDouble(x);
1045 else if (ndigits < NDIGITS_MIN)
1046 /* return 0.0, but with sign of x */
1047 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001048 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001049 /* finite x, and ndigits is not unreasonably large */
1050 return double_round(x, (int)ndigits);
1051#undef NDIGITS_MAX
1052#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001053}
1054
1055static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001056float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001057{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001058 if (PyFloat_CheckExact(v))
1059 Py_INCREF(v);
1060 else
1061 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001062 return v;
1063}
1064
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001065/* turn ASCII hex characters into integer values and vice versa */
1066
1067static char
1068char_from_hex(int x)
1069{
1070 assert(0 <= x && x < 16);
1071 return "0123456789abcdef"[x];
1072}
1073
1074static int
1075hex_from_char(char c) {
1076 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001077 switch(c) {
1078 case '0':
1079 x = 0;
1080 break;
1081 case '1':
1082 x = 1;
1083 break;
1084 case '2':
1085 x = 2;
1086 break;
1087 case '3':
1088 x = 3;
1089 break;
1090 case '4':
1091 x = 4;
1092 break;
1093 case '5':
1094 x = 5;
1095 break;
1096 case '6':
1097 x = 6;
1098 break;
1099 case '7':
1100 x = 7;
1101 break;
1102 case '8':
1103 x = 8;
1104 break;
1105 case '9':
1106 x = 9;
1107 break;
1108 case 'a':
1109 case 'A':
1110 x = 10;
1111 break;
1112 case 'b':
1113 case 'B':
1114 x = 11;
1115 break;
1116 case 'c':
1117 case 'C':
1118 x = 12;
1119 break;
1120 case 'd':
1121 case 'D':
1122 x = 13;
1123 break;
1124 case 'e':
1125 case 'E':
1126 x = 14;
1127 break;
1128 case 'f':
1129 case 'F':
1130 x = 15;
1131 break;
1132 default:
1133 x = -1;
1134 break;
1135 }
1136 return x;
1137}
1138
1139/* convert a float to a hexadecimal string */
1140
1141/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1142 of the form 4k+1. */
1143#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1144
1145static PyObject *
1146float_hex(PyObject *v)
1147{
1148 double x, m;
1149 int e, shift, i, si, esign;
1150 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1151 trailing NUL byte. */
1152 char s[(TOHEX_NBITS-1)/4+3];
1153
1154 CONVERT_TO_DOUBLE(v, x);
1155
1156 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1157 return float_str((PyFloatObject *)v);
1158
1159 if (x == 0.0) {
1160 if(copysign(1.0, x) == -1.0)
1161 return PyUnicode_FromString("-0x0.0p+0");
1162 else
1163 return PyUnicode_FromString("0x0.0p+0");
1164 }
1165
1166 m = frexp(fabs(x), &e);
1167 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1168 m = ldexp(m, shift);
1169 e -= shift;
1170
1171 si = 0;
1172 s[si] = char_from_hex((int)m);
1173 si++;
1174 m -= (int)m;
1175 s[si] = '.';
1176 si++;
1177 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1178 m *= 16.0;
1179 s[si] = char_from_hex((int)m);
1180 si++;
1181 m -= (int)m;
1182 }
1183 s[si] = '\0';
1184
1185 if (e < 0) {
1186 esign = (int)'-';
1187 e = -e;
1188 }
1189 else
1190 esign = (int)'+';
1191
1192 if (x < 0.0)
1193 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1194 else
1195 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1196}
1197
1198PyDoc_STRVAR(float_hex_doc,
1199"float.hex() -> string\n\
1200\n\
1201Return a hexadecimal representation of a floating-point number.\n\
1202>>> (-0.1).hex()\n\
1203'-0x1.999999999999ap-4'\n\
1204>>> 3.14159.hex()\n\
1205'0x1.921f9f01b866ep+1'");
1206
1207/* Convert a hexadecimal string to a float. */
1208
1209static PyObject *
1210float_fromhex(PyObject *cls, PyObject *arg)
1211{
1212 PyObject *result_as_float, *result;
1213 double x;
1214 long exp, top_exp, lsb, key_digit;
1215 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001216 int half_eps, digit, round_up, negate=0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001217 Py_ssize_t length, ndigits, fdigits, i;
1218
1219 /*
1220 * For the sake of simplicity and correctness, we impose an artificial
1221 * limit on ndigits, the total number of hex digits in the coefficient
1222 * The limit is chosen to ensure that, writing exp for the exponent,
1223 *
1224 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1225 * guaranteed to overflow (provided it's nonzero)
1226 *
1227 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1228 * guaranteed to underflow to 0.
1229 *
1230 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1231 * overflow in the calculation of exp and top_exp below.
1232 *
1233 * More specifically, ndigits is assumed to satisfy the following
1234 * inequalities:
1235 *
1236 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1237 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1238 *
1239 * If either of these inequalities is not satisfied, a ValueError is
1240 * raised. Otherwise, write x for the value of the hex string, and
1241 * assume x is nonzero. Then
1242 *
1243 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1244 *
1245 * Now if exp > LONG_MAX/2 then:
1246 *
1247 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1248 * = DBL_MAX_EXP
1249 *
1250 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1251 * double, so overflows. If exp < LONG_MIN/2, then
1252 *
1253 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1254 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1255 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1256 *
1257 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1258 * when converted to a C double.
1259 *
1260 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1261 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1262 */
1263
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001264 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001265 if (s == NULL)
1266 return NULL;
1267 s_end = s + length;
1268
1269 /********************
1270 * Parse the string *
1271 ********************/
1272
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001273 /* leading whitespace */
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001274 while (Py_ISSPACE(*s))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
1277 /* infinities and nans */
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001278 x = _Py_parse_inf_or_nan(s, &coeff_end);
1279 if (coeff_end != s) {
1280 s = coeff_end;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001281 goto finished;
1282 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001283
1284 /* optional sign */
1285 if (*s == '-') {
1286 s++;
1287 negate = 1;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001288 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001289 else if (*s == '+')
1290 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
1292 /* [0x] */
1293 s_store = s;
1294 if (*s == '0') {
1295 s++;
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001296 if (*s == 'x' || *s == 'X')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001297 s++;
1298 else
1299 s = s_store;
1300 }
1301
1302 /* coefficient: <integer> [. <fraction>] */
1303 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001304 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001305 s++;
1306 s_store = s;
1307 if (*s == '.') {
1308 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001309 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310 s++;
1311 coeff_end = s-1;
1312 }
1313 else
1314 coeff_end = s;
1315
1316 /* ndigits = total # of hex digits; fdigits = # after point */
1317 ndigits = coeff_end - coeff_start;
1318 fdigits = coeff_end - s_store;
1319 if (ndigits == 0)
1320 goto parse_error;
1321 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1322 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1323 goto insane_length_error;
1324
1325 /* [p <exponent>] */
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001326 if (*s == 'p' || *s == 'P') {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327 s++;
1328 exp_start = s;
1329 if (*s == '-' || *s == '+')
1330 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001331 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001332 goto parse_error;
1333 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001334 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335 s++;
1336 exp = strtol(exp_start, NULL, 10);
1337 }
1338 else
1339 exp = 0;
1340
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1342#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1343 coeff_end-(j) : \
1344 coeff_end-1-(j)))
1345
1346 /*******************************************
1347 * Compute rounded value of the hex string *
1348 *******************************************/
1349
1350 /* Discard leading zeros, and catch extreme overflow and underflow */
1351 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1352 ndigits--;
1353 if (ndigits == 0 || exp < LONG_MIN/2) {
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001354 x = 0.0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001355 goto finished;
1356 }
1357 if (exp > LONG_MAX/2)
1358 goto overflow_error;
1359
1360 /* Adjust exponent for fractional part. */
1361 exp = exp - 4*((long)fdigits);
1362
1363 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1364 top_exp = exp + 4*((long)ndigits - 1);
1365 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1366 top_exp++;
1367
1368 /* catch almost all nonextreme cases of overflow and underflow here */
1369 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001370 x = 0.0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001371 goto finished;
1372 }
1373 if (top_exp > DBL_MAX_EXP)
1374 goto overflow_error;
1375
1376 /* lsb = exponent of least significant bit of the *rounded* value.
1377 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1378 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1379
1380 x = 0.0;
1381 if (exp >= lsb) {
1382 /* no rounding required */
1383 for (i = ndigits-1; i >= 0; i--)
1384 x = 16.0*x + HEX_DIGIT(i);
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001385 x = ldexp(x, (int)(exp));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001386 goto finished;
1387 }
1388 /* rounding required. key_digit is the index of the hex digit
1389 containing the first bit to be rounded away. */
1390 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1391 key_digit = (lsb - exp - 1) / 4;
1392 for (i = ndigits-1; i > key_digit; i--)
1393 x = 16.0*x + HEX_DIGIT(i);
1394 digit = HEX_DIGIT(key_digit);
1395 x = 16.0*x + (double)(digit & (16-2*half_eps));
1396
1397 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1398 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1399 if ((digit & half_eps) != 0) {
1400 round_up = 0;
1401 if ((digit & (3*half_eps-1)) != 0 ||
1402 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1403 round_up = 1;
1404 else
1405 for (i = key_digit-1; i >= 0; i--)
1406 if (HEX_DIGIT(i) != 0) {
1407 round_up = 1;
1408 break;
1409 }
1410 if (round_up == 1) {
1411 x += 2*half_eps;
1412 if (top_exp == DBL_MAX_EXP &&
1413 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1414 /* overflow corner case: pre-rounded value <
1415 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1416 goto overflow_error;
1417 }
1418 }
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001419 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001420
1421 finished:
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001422 /* optional trailing whitespace leading to the end of the string */
1423 while (Py_ISSPACE(*s))
1424 s++;
1425 if (s != s_end)
1426 goto parse_error;
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001427 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001428 if (result_as_float == NULL)
1429 return NULL;
1430 result = PyObject_CallObject(cls, result_as_float);
1431 Py_DECREF(result_as_float);
1432 return result;
1433
1434 overflow_error:
1435 PyErr_SetString(PyExc_OverflowError,
1436 "hexadecimal value too large to represent as a float");
1437 return NULL;
1438
1439 parse_error:
1440 PyErr_SetString(PyExc_ValueError,
1441 "invalid hexadecimal floating-point string");
1442 return NULL;
1443
1444 insane_length_error:
1445 PyErr_SetString(PyExc_ValueError,
1446 "hexadecimal string too long to convert");
1447 return NULL;
1448}
1449
1450PyDoc_STRVAR(float_fromhex_doc,
1451"float.fromhex(string) -> float\n\
1452\n\
1453Create a floating-point number from a hexadecimal string.\n\
1454>>> float.fromhex('0x1.ffffp10')\n\
14552047.984375\n\
1456>>> float.fromhex('-0x1p-1074')\n\
1457-4.9406564584124654e-324");
1458
1459
Christian Heimes26855632008-01-27 23:50:43 +00001460static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001461float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001462{
1463 double self;
1464 double float_part;
1465 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001466 int i;
1467
Christian Heimes26855632008-01-27 23:50:43 +00001468 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001469 PyObject *py_exponent = NULL;
1470 PyObject *numerator = NULL;
1471 PyObject *denominator = NULL;
1472 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001473 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001474
1475#define INPLACE_UPDATE(obj, call) \
1476 prev = obj; \
1477 obj = call; \
1478 Py_DECREF(prev); \
1479
1480 CONVERT_TO_DOUBLE(v, self);
1481
1482 if (Py_IS_INFINITY(self)) {
1483 PyErr_SetString(PyExc_OverflowError,
1484 "Cannot pass infinity to float.as_integer_ratio.");
1485 return NULL;
1486 }
1487#ifdef Py_NAN
1488 if (Py_IS_NAN(self)) {
1489 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001490 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001491 return NULL;
1492 }
1493#endif
1494
Christian Heimes26855632008-01-27 23:50:43 +00001495 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001496 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001497 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001498
1499 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1500 float_part *= 2.0;
1501 exponent--;
1502 }
1503 /* self == float_part * 2**exponent exactly and float_part is integral.
1504 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1505 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001506
Christian Heimes292d3512008-02-03 16:51:08 +00001507 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001508 if (numerator == NULL) goto error;
1509
Christian Heimes292d3512008-02-03 16:51:08 +00001510 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001511 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001512 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001513 if (py_exponent == NULL) goto error;
1514 INPLACE_UPDATE(py_exponent,
1515 long_methods->nb_lshift(denominator, py_exponent));
1516 if (py_exponent == NULL) goto error;
1517 if (exponent > 0) {
1518 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001519 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001520 if (numerator == NULL) goto error;
1521 }
1522 else {
1523 Py_DECREF(denominator);
1524 denominator = py_exponent;
1525 py_exponent = NULL;
1526 }
1527
1528 result_pair = PyTuple_Pack(2, numerator, denominator);
1529
1530#undef INPLACE_UPDATE
1531error:
1532 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001533 Py_XDECREF(denominator);
1534 Py_XDECREF(numerator);
1535 return result_pair;
1536}
1537
1538PyDoc_STRVAR(float_as_integer_ratio_doc,
1539"float.as_integer_ratio() -> (int, int)\n"
1540"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001541"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1542"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001543"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001544"\n"
1545">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001546"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001547">>> (0.0).as_integer_ratio()\n"
1548"(0, 1)\n"
1549">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001550"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001551
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001552
Jeremy Hylton938ace62002-07-17 16:30:39 +00001553static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001554float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1555
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556static PyObject *
1557float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1558{
1559 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001560 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561
Guido van Rossumbef14172001-08-29 15:47:46 +00001562 if (type != &PyFloat_Type)
1563 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1565 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001566 /* If it's a string, but not a string subclass, use
1567 PyFloat_FromString. */
1568 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001569 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001570 return PyNumber_Float(x);
1571}
1572
Guido van Rossumbef14172001-08-29 15:47:46 +00001573/* Wimpy, slow approach to tp_new calls for subtypes of float:
1574 first create a regular float from whatever arguments we got,
1575 then allocate a subtype instance and initialize its ob_fval
1576 from the regular float. The regular float is then thrown away.
1577*/
1578static PyObject *
1579float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1580{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001581 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001582
1583 assert(PyType_IsSubtype(type, &PyFloat_Type));
1584 tmp = float_new(&PyFloat_Type, args, kwds);
1585 if (tmp == NULL)
1586 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001587 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001588 newobj = type->tp_alloc(type, 0);
1589 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001590 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001591 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001592 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001593 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001594 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001595 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001596}
1597
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001598static PyObject *
1599float_getnewargs(PyFloatObject *v)
1600{
1601 return Py_BuildValue("(d)", v->ob_fval);
1602}
1603
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001604/* this is for the benefit of the pack/unpack routines below */
1605
1606typedef enum {
1607 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1608} float_format_type;
1609
1610static float_format_type double_format, float_format;
1611static float_format_type detected_double_format, detected_float_format;
1612
1613static PyObject *
1614float_getformat(PyTypeObject *v, PyObject* arg)
1615{
1616 char* s;
1617 float_format_type r;
1618
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001619 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620 PyErr_Format(PyExc_TypeError,
1621 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001622 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001623 return NULL;
1624 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001625 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001626 if (s == NULL)
1627 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001628 if (strcmp(s, "double") == 0) {
1629 r = double_format;
1630 }
1631 else if (strcmp(s, "float") == 0) {
1632 r = float_format;
1633 }
1634 else {
1635 PyErr_SetString(PyExc_ValueError,
1636 "__getformat__() argument 1 must be "
1637 "'double' or 'float'");
1638 return NULL;
1639 }
1640
1641 switch (r) {
1642 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001643 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001644 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001645 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001646 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001647 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001648 default:
1649 Py_FatalError("insane float_format or double_format");
1650 return NULL;
1651 }
1652}
1653
1654PyDoc_STRVAR(float_getformat_doc,
1655"float.__getformat__(typestr) -> string\n"
1656"\n"
1657"You probably don't want to use this function. It exists mainly to be\n"
1658"used in Python's test suite.\n"
1659"\n"
1660"typestr must be 'double' or 'float'. This function returns whichever of\n"
1661"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1662"format of floating point numbers used by the C type named by typestr.");
1663
1664static PyObject *
1665float_setformat(PyTypeObject *v, PyObject* args)
1666{
1667 char* typestr;
1668 char* format;
1669 float_format_type f;
1670 float_format_type detected;
1671 float_format_type *p;
1672
1673 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1674 return NULL;
1675
1676 if (strcmp(typestr, "double") == 0) {
1677 p = &double_format;
1678 detected = detected_double_format;
1679 }
1680 else if (strcmp(typestr, "float") == 0) {
1681 p = &float_format;
1682 detected = detected_float_format;
1683 }
1684 else {
1685 PyErr_SetString(PyExc_ValueError,
1686 "__setformat__() argument 1 must "
1687 "be 'double' or 'float'");
1688 return NULL;
1689 }
1690
1691 if (strcmp(format, "unknown") == 0) {
1692 f = unknown_format;
1693 }
1694 else if (strcmp(format, "IEEE, little-endian") == 0) {
1695 f = ieee_little_endian_format;
1696 }
1697 else if (strcmp(format, "IEEE, big-endian") == 0) {
1698 f = ieee_big_endian_format;
1699 }
1700 else {
1701 PyErr_SetString(PyExc_ValueError,
1702 "__setformat__() argument 2 must be "
1703 "'unknown', 'IEEE, little-endian' or "
1704 "'IEEE, big-endian'");
1705 return NULL;
1706
1707 }
1708
1709 if (f != unknown_format && f != detected) {
1710 PyErr_Format(PyExc_ValueError,
1711 "can only set %s format to 'unknown' or the "
1712 "detected platform value", typestr);
1713 return NULL;
1714 }
1715
1716 *p = f;
1717 Py_RETURN_NONE;
1718}
1719
1720PyDoc_STRVAR(float_setformat_doc,
1721"float.__setformat__(typestr, fmt) -> None\n"
1722"\n"
1723"You probably don't want to use this function. It exists mainly to be\n"
1724"used in Python's test suite.\n"
1725"\n"
1726"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1727"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1728"one of the latter two if it appears to match the underlying C reality.\n"
1729"\n"
1730"Overrides the automatic determination of C-level floating point type.\n"
1731"This affects how floats are converted to and from binary strings.");
1732
Guido van Rossumb43daf72007-08-01 18:08:08 +00001733static PyObject *
1734float_getzero(PyObject *v, void *closure)
1735{
1736 return PyFloat_FromDouble(0.0);
1737}
1738
Eric Smith8c663262007-08-25 02:26:07 +00001739static PyObject *
1740float__format__(PyObject *self, PyObject *args)
1741{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001742 PyObject *format_spec;
1743
1744 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1745 return NULL;
1746 return _PyFloat_FormatAdvanced(self,
1747 PyUnicode_AS_UNICODE(format_spec),
1748 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001749}
1750
1751PyDoc_STRVAR(float__format__doc,
1752"float.__format__(format_spec) -> string\n"
1753"\n"
1754"Formats the float according to format_spec.");
1755
1756
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001757static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001758 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001759 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001760 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1761 "Returns the Integral closest to x between 0 and x."},
1762 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1763 "Returns the Integral closest to x, rounding half toward even.\n"
1764 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001765 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1766 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001767 {"fromhex", (PyCFunction)float_fromhex,
1768 METH_O|METH_CLASS, float_fromhex_doc},
1769 {"hex", (PyCFunction)float_hex,
1770 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001771 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1772 "Returns True if the float is an integer."},
1773#if 0
1774 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1775 "Returns True if the float is positive or negative infinite."},
1776 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1777 "Returns True if the float is finite, neither infinite nor NaN."},
1778 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1779 "Returns True if the float is not a number (NaN)."},
1780#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001781 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001782 {"__getformat__", (PyCFunction)float_getformat,
1783 METH_O|METH_CLASS, float_getformat_doc},
1784 {"__setformat__", (PyCFunction)float_setformat,
1785 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001786 {"__format__", (PyCFunction)float__format__,
1787 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001788 {NULL, NULL} /* sentinel */
1789};
1790
Guido van Rossumb43daf72007-08-01 18:08:08 +00001791static PyGetSetDef float_getset[] = {
1792 {"real",
1793 (getter)float_float, (setter)NULL,
1794 "the real part of a complex number",
1795 NULL},
1796 {"imag",
1797 (getter)float_getzero, (setter)NULL,
1798 "the imaginary part of a complex number",
1799 NULL},
1800 {NULL} /* Sentinel */
1801};
1802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804"float(x) -> floating point number\n\
1805\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
1808
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001809static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001810 float_add, /*nb_add*/
1811 float_sub, /*nb_subtract*/
1812 float_mul, /*nb_multiply*/
1813 float_rem, /*nb_remainder*/
1814 float_divmod, /*nb_divmod*/
1815 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001816 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001817 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001818 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001819 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001820 0, /*nb_invert*/
1821 0, /*nb_lshift*/
1822 0, /*nb_rshift*/
1823 0, /*nb_and*/
1824 0, /*nb_xor*/
1825 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001826 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001827 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001828 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001829 0, /* nb_inplace_add */
1830 0, /* nb_inplace_subtract */
1831 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001832 0, /* nb_inplace_remainder */
1833 0, /* nb_inplace_power */
1834 0, /* nb_inplace_lshift */
1835 0, /* nb_inplace_rshift */
1836 0, /* nb_inplace_and */
1837 0, /* nb_inplace_xor */
1838 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001839 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001840 float_div, /* nb_true_divide */
1841 0, /* nb_inplace_floor_divide */
1842 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001843};
1844
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001845PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001846 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001851 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 0, /* tp_getattr */
1853 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001854 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 (reprfunc)float_repr, /* tp_repr */
1856 &float_as_number, /* tp_as_number */
1857 0, /* tp_as_sequence */
1858 0, /* tp_as_mapping */
1859 (hashfunc)float_hash, /* tp_hash */
1860 0, /* tp_call */
1861 (reprfunc)float_str, /* tp_str */
1862 PyObject_GenericGetAttr, /* tp_getattro */
1863 0, /* tp_setattro */
1864 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001865 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 float_doc, /* tp_doc */
1867 0, /* tp_traverse */
1868 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001869 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870 0, /* tp_weaklistoffset */
1871 0, /* tp_iter */
1872 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001873 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001875 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 0, /* tp_base */
1877 0, /* tp_dict */
1878 0, /* tp_descr_get */
1879 0, /* tp_descr_set */
1880 0, /* tp_dictoffset */
1881 0, /* tp_init */
1882 0, /* tp_alloc */
1883 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001884};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001885
1886void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887_PyFloat_Init(void)
1888{
1889 /* We attempt to determine if this machine is using IEEE
1890 floating point formats by peering at the bits of some
1891 carefully chosen values. If it looks like we are on an
1892 IEEE platform, the float packing/unpacking routines can
1893 just copy bits, if not they resort to arithmetic & shifts
1894 and masks. The shifts & masks approach works on all finite
1895 values, but what happens to infinities, NaNs and signed
1896 zeroes on packing is an accident, and attempting to unpack
1897 a NaN or an infinity will raise an exception.
1898
1899 Note that if we're on some whacked-out platform which uses
1900 IEEE formats but isn't strictly little-endian or big-
1901 endian, we will fall back to the portable shifts & masks
1902 method. */
1903
1904#if SIZEOF_DOUBLE == 8
1905 {
1906 double x = 9006104071832581.0;
1907 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1908 detected_double_format = ieee_big_endian_format;
1909 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1910 detected_double_format = ieee_little_endian_format;
1911 else
1912 detected_double_format = unknown_format;
1913 }
1914#else
1915 detected_double_format = unknown_format;
1916#endif
1917
1918#if SIZEOF_FLOAT == 4
1919 {
1920 float y = 16711938.0;
1921 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1922 detected_float_format = ieee_big_endian_format;
1923 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1924 detected_float_format = ieee_little_endian_format;
1925 else
1926 detected_float_format = unknown_format;
1927 }
1928#else
1929 detected_float_format = unknown_format;
1930#endif
1931
1932 double_format = detected_double_format;
1933 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001934
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001935 /* Init float info */
1936 if (FloatInfoType.tp_name == 0)
1937 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001938}
1939
Georg Brandl2ee470f2008-07-16 12:55:28 +00001940int
1941PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001942{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001943 PyFloatObject *p;
1944 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001945 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001946 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001947 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001948
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001949 list = block_list;
1950 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001951 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001952 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001953 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001954 for (i = 0, p = &list->objects[0];
1955 i < N_FLOATOBJECTS;
1956 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001957 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001958 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001959 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001960 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001961 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001962 list->next = block_list;
1963 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001964 for (i = 0, p = &list->objects[0];
1965 i < N_FLOATOBJECTS;
1966 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001967 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001968 Py_REFCNT(p) == 0) {
1969 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001970 free_list;
1971 free_list = p;
1972 }
1973 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001974 }
1975 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001976 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001977 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001978 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001979 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001980 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001981 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001982}
1983
1984void
1985PyFloat_Fini(void)
1986{
1987 PyFloatObject *p;
1988 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001989 int i;
1990 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001991
Georg Brandl2ee470f2008-07-16 12:55:28 +00001992 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001993
Guido van Rossum3fce8831999-03-12 19:43:17 +00001994 if (!Py_VerboseFlag)
1995 return;
1996 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001997 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001998 fprintf(stderr, "\n");
1999 }
2000 else {
2001 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00002002 ": %d unfreed float%s\n",
2003 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002004 }
2005 if (Py_VerboseFlag > 1) {
2006 list = block_list;
2007 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002008 for (i = 0, p = &list->objects[0];
2009 i < N_FLOATOBJECTS;
2010 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002011 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00002012 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00002013 char *buf = PyOS_double_to_string(
2014 PyFloat_AS_DOUBLE(p), 'r',
2015 0, 0, NULL);
2016 if (buf) {
2017 /* XXX(twouters) cast
2018 refcount to long
2019 until %zd is
2020 universally
2021 available
2022 */
2023 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002024 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00002025 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00002026 PyMem_Free(buf);
2027 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002028 }
2029 }
2030 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002031 }
2032 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002033}
Tim Peters9905b942003-03-20 20:53:32 +00002034
2035/*----------------------------------------------------------------------------
2036 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002037 */
2038int
2039_PyFloat_Pack4(double x, unsigned char *p, int le)
2040{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002041 if (float_format == unknown_format) {
2042 unsigned char sign;
2043 int e;
2044 double f;
2045 unsigned int fbits;
2046 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002047
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002048 if (le) {
2049 p += 3;
2050 incr = -1;
2051 }
Tim Peters9905b942003-03-20 20:53:32 +00002052
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002053 if (x < 0) {
2054 sign = 1;
2055 x = -x;
2056 }
2057 else
2058 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002059
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002060 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002061
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002062 /* Normalize f to be in the range [1.0, 2.0) */
2063 if (0.5 <= f && f < 1.0) {
2064 f *= 2.0;
2065 e--;
2066 }
2067 else if (f == 0.0)
2068 e = 0;
2069 else {
2070 PyErr_SetString(PyExc_SystemError,
2071 "frexp() result out of range");
2072 return -1;
2073 }
2074
2075 if (e >= 128)
2076 goto Overflow;
2077 else if (e < -126) {
2078 /* Gradual underflow */
2079 f = ldexp(f, 126 + e);
2080 e = 0;
2081 }
2082 else if (!(e == 0 && f == 0.0)) {
2083 e += 127;
2084 f -= 1.0; /* Get rid of leading 1 */
2085 }
2086
2087 f *= 8388608.0; /* 2**23 */
2088 fbits = (unsigned int)(f + 0.5); /* Round */
2089 assert(fbits <= 8388608);
2090 if (fbits >> 23) {
2091 /* The carry propagated out of a string of 23 1 bits. */
2092 fbits = 0;
2093 ++e;
2094 if (e >= 255)
2095 goto Overflow;
2096 }
2097
2098 /* First byte */
2099 *p = (sign << 7) | (e >> 1);
2100 p += incr;
2101
2102 /* Second byte */
2103 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2104 p += incr;
2105
2106 /* Third byte */
2107 *p = (fbits >> 8) & 0xFF;
2108 p += incr;
2109
2110 /* Fourth byte */
2111 *p = fbits & 0xFF;
2112
2113 /* Done */
2114 return 0;
2115
Tim Peters9905b942003-03-20 20:53:32 +00002116 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002118 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002119 const char *s = (char*)&y;
2120 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002121
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002122 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2123 goto Overflow;
2124
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002125 if ((float_format == ieee_little_endian_format && !le)
2126 || (float_format == ieee_big_endian_format && le)) {
2127 p += 3;
2128 incr = -1;
2129 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002130
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002131 for (i = 0; i < 4; i++) {
2132 *p = *s++;
2133 p += incr;
2134 }
2135 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002136 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002137 Overflow:
2138 PyErr_SetString(PyExc_OverflowError,
2139 "float too large to pack with f format");
2140 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002141}
2142
2143int
2144_PyFloat_Pack8(double x, unsigned char *p, int le)
2145{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002146 if (double_format == unknown_format) {
2147 unsigned char sign;
2148 int e;
2149 double f;
2150 unsigned int fhi, flo;
2151 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002152
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002153 if (le) {
2154 p += 7;
2155 incr = -1;
2156 }
Tim Peters9905b942003-03-20 20:53:32 +00002157
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158 if (x < 0) {
2159 sign = 1;
2160 x = -x;
2161 }
2162 else
2163 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002164
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002165 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002166
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002167 /* Normalize f to be in the range [1.0, 2.0) */
2168 if (0.5 <= f && f < 1.0) {
2169 f *= 2.0;
2170 e--;
2171 }
2172 else if (f == 0.0)
2173 e = 0;
2174 else {
2175 PyErr_SetString(PyExc_SystemError,
2176 "frexp() result out of range");
2177 return -1;
2178 }
2179
2180 if (e >= 1024)
2181 goto Overflow;
2182 else if (e < -1022) {
2183 /* Gradual underflow */
2184 f = ldexp(f, 1022 + e);
2185 e = 0;
2186 }
2187 else if (!(e == 0 && f == 0.0)) {
2188 e += 1023;
2189 f -= 1.0; /* Get rid of leading 1 */
2190 }
2191
2192 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2193 f *= 268435456.0; /* 2**28 */
2194 fhi = (unsigned int)f; /* Truncate */
2195 assert(fhi < 268435456);
2196
2197 f -= (double)fhi;
2198 f *= 16777216.0; /* 2**24 */
2199 flo = (unsigned int)(f + 0.5); /* Round */
2200 assert(flo <= 16777216);
2201 if (flo >> 24) {
2202 /* The carry propagated out of a string of 24 1 bits. */
2203 flo = 0;
2204 ++fhi;
2205 if (fhi >> 28) {
2206 /* And it also progagated out of the next 28 bits. */
2207 fhi = 0;
2208 ++e;
2209 if (e >= 2047)
2210 goto Overflow;
2211 }
2212 }
2213
2214 /* First byte */
2215 *p = (sign << 7) | (e >> 4);
2216 p += incr;
2217
2218 /* Second byte */
2219 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2220 p += incr;
2221
2222 /* Third byte */
2223 *p = (fhi >> 16) & 0xFF;
2224 p += incr;
2225
2226 /* Fourth byte */
2227 *p = (fhi >> 8) & 0xFF;
2228 p += incr;
2229
2230 /* Fifth byte */
2231 *p = fhi & 0xFF;
2232 p += incr;
2233
2234 /* Sixth byte */
2235 *p = (flo >> 16) & 0xFF;
2236 p += incr;
2237
2238 /* Seventh byte */
2239 *p = (flo >> 8) & 0xFF;
2240 p += incr;
2241
2242 /* Eighth byte */
2243 *p = flo & 0xFF;
2244 p += incr;
2245
2246 /* Done */
2247 return 0;
2248
2249 Overflow:
2250 PyErr_SetString(PyExc_OverflowError,
2251 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002252 return -1;
2253 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002254 else {
2255 const char *s = (char*)&x;
2256 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002257
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258 if ((double_format == ieee_little_endian_format && !le)
2259 || (double_format == ieee_big_endian_format && le)) {
2260 p += 7;
2261 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002262 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002263
2264 for (i = 0; i < 8; i++) {
2265 *p = *s++;
2266 p += incr;
2267 }
2268 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002269 }
Tim Peters9905b942003-03-20 20:53:32 +00002270}
2271
2272double
2273_PyFloat_Unpack4(const unsigned char *p, int le)
2274{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002275 if (float_format == unknown_format) {
2276 unsigned char sign;
2277 int e;
2278 unsigned int f;
2279 double x;
2280 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002281
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002282 if (le) {
2283 p += 3;
2284 incr = -1;
2285 }
2286
2287 /* First byte */
2288 sign = (*p >> 7) & 1;
2289 e = (*p & 0x7F) << 1;
2290 p += incr;
2291
2292 /* Second byte */
2293 e |= (*p >> 7) & 1;
2294 f = (*p & 0x7F) << 16;
2295 p += incr;
2296
2297 if (e == 255) {
2298 PyErr_SetString(
2299 PyExc_ValueError,
2300 "can't unpack IEEE 754 special value "
2301 "on non-IEEE platform");
2302 return -1;
2303 }
2304
2305 /* Third byte */
2306 f |= *p << 8;
2307 p += incr;
2308
2309 /* Fourth byte */
2310 f |= *p;
2311
2312 x = (double)f / 8388608.0;
2313
2314 /* XXX This sadly ignores Inf/NaN issues */
2315 if (e == 0)
2316 e = -126;
2317 else {
2318 x += 1.0;
2319 e -= 127;
2320 }
2321 x = ldexp(x, e);
2322
2323 if (sign)
2324 x = -x;
2325
2326 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002327 }
Tim Peters9905b942003-03-20 20:53:32 +00002328 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002329 float x;
2330
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331 if ((float_format == ieee_little_endian_format && !le)
2332 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002333 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002334 char *d = &buf[3];
2335 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002336
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002337 for (i = 0; i < 4; i++) {
2338 *d-- = *p++;
2339 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002340 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341 }
2342 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002343 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002345
2346 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002347 }
Tim Peters9905b942003-03-20 20:53:32 +00002348}
2349
2350double
2351_PyFloat_Unpack8(const unsigned char *p, int le)
2352{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002353 if (double_format == unknown_format) {
2354 unsigned char sign;
2355 int e;
2356 unsigned int fhi, flo;
2357 double x;
2358 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002359
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360 if (le) {
2361 p += 7;
2362 incr = -1;
2363 }
2364
2365 /* First byte */
2366 sign = (*p >> 7) & 1;
2367 e = (*p & 0x7F) << 4;
2368
2369 p += incr;
2370
2371 /* Second byte */
2372 e |= (*p >> 4) & 0xF;
2373 fhi = (*p & 0xF) << 24;
2374 p += incr;
2375
2376 if (e == 2047) {
2377 PyErr_SetString(
2378 PyExc_ValueError,
2379 "can't unpack IEEE 754 special value "
2380 "on non-IEEE platform");
2381 return -1.0;
2382 }
2383
2384 /* Third byte */
2385 fhi |= *p << 16;
2386 p += incr;
2387
2388 /* Fourth byte */
2389 fhi |= *p << 8;
2390 p += incr;
2391
2392 /* Fifth byte */
2393 fhi |= *p;
2394 p += incr;
2395
2396 /* Sixth byte */
2397 flo = *p << 16;
2398 p += incr;
2399
2400 /* Seventh byte */
2401 flo |= *p << 8;
2402 p += incr;
2403
2404 /* Eighth byte */
2405 flo |= *p;
2406
2407 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2408 x /= 268435456.0; /* 2**28 */
2409
2410 if (e == 0)
2411 e = -1022;
2412 else {
2413 x += 1.0;
2414 e -= 1023;
2415 }
2416 x = ldexp(x, e);
2417
2418 if (sign)
2419 x = -x;
2420
2421 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002422 }
Tim Peters9905b942003-03-20 20:53:32 +00002423 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002424 double x;
2425
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002426 if ((double_format == ieee_little_endian_format && !le)
2427 || (double_format == ieee_big_endian_format && le)) {
2428 char buf[8];
2429 char *d = &buf[7];
2430 int i;
2431
2432 for (i = 0; i < 8; i++) {
2433 *d-- = *p++;
2434 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002435 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002436 }
2437 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002438 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002439 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002440
2441 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002442 }
Tim Peters9905b942003-03-20 20:53:32 +00002443}