blob: e146a4fc7c7ead7b5b041d60433c90582536c529 [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"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Mark Dickinson65fe25e2008-07-16 11:30:51 +000012#undef MAX
13#undef MIN
14#define MAX(x, y) ((x) < (y) ? (y) : (x))
15#define MIN(x, y) ((x) < (y) ? (x) : (y))
16
Guido van Rossum6923e131990-11-02 17:50:43 +000017
Christian Heimes969fe572008-01-25 11:23:10 +000018#ifdef _OSF_SOURCE
19/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20extern int finite(double);
21#endif
22
Mark Dickinsond19052c2010-06-27 18:19:09 +000023/* Special free list
24
25 Since some Python programs can spend much of their time allocating
26 and deallocating floats, these operations should be very fast.
27 Therefore we use a dedicated allocation scheme with a much lower
28 overhead (in space and time) than straight malloc(): a simple
29 dedicated free list, filled when necessary with memory from malloc().
30
31 block_list is a singly-linked list of all PyFloatBlocks ever allocated,
32 linked via their next members. PyFloatBlocks are never returned to the
33 system before shutdown (PyFloat_Fini).
34
35 free_list is a singly-linked list of available PyFloatObjects, linked
36 via abuse of their ob_type members.
37*/
38
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
40#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
41#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000042
Guido van Rossum3fce8831999-03-12 19:43:17 +000043struct _floatblock {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 struct _floatblock *next;
45 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000046};
47
48typedef struct _floatblock PyFloatBlock;
49
50static PyFloatBlock *block_list = NULL;
51static PyFloatObject *free_list = NULL;
52
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000054fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyFloatObject *p, *q;
57 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
58 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
59 if (p == NULL)
60 return (PyFloatObject *) PyErr_NoMemory();
61 ((PyFloatBlock *)p)->next = block_list;
62 block_list = (PyFloatBlock *)p;
63 p = &((PyFloatBlock *)p)->objects[0];
64 q = p + N_FLOATOBJECTS;
65 while (--q > p)
66 Py_TYPE(q) = (struct _typeobject *)(q-1);
67 Py_TYPE(q) = NULL;
68 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000069}
70
Christian Heimes93852662007-12-01 12:22:32 +000071double
72PyFloat_GetMax(void)
73{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000075}
76
77double
78PyFloat_GetMin(void)
79{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000081}
82
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083static PyTypeObject FloatInfoType;
84
85PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000086"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000087\n\
88A structseq holding information about the float type. It contains low level\n\
89information about the precision and internal representation. Please study\n\
90your system's :file:`float.h` for more information.");
91
92static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 {"max", "DBL_MAX -- maximum representable finite float"},
94 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
95 "is representable"},
96 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
97 "is representable"},
98 {"min", "DBL_MIN -- Minimum positive normalizer float"},
99 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
100 "is a normalized float"},
101 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
102 "a normalized"},
103 {"dig", "DBL_DIG -- digits"},
104 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
105 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
106 "representable float"},
107 {"radix", "FLT_RADIX -- radix of exponent"},
108 {"rounds", "FLT_ROUNDS -- addition rounds"},
109 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000110};
111
112static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 "sys.float_info", /* name */
114 floatinfo__doc__, /* doc */
115 floatinfo_fields, /* fields */
116 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000117};
118
Christian Heimes93852662007-12-01 12:22:32 +0000119PyObject *
120PyFloat_GetInfo(void)
121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject* floatinfo;
123 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 floatinfo = PyStructSequence_New(&FloatInfoType);
126 if (floatinfo == NULL) {
127 return NULL;
128 }
Christian Heimes93852662007-12-01 12:22:32 +0000129
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000130#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000132#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 SetDblFlag(DBL_MAX);
136 SetIntFlag(DBL_MAX_EXP);
137 SetIntFlag(DBL_MAX_10_EXP);
138 SetDblFlag(DBL_MIN);
139 SetIntFlag(DBL_MIN_EXP);
140 SetIntFlag(DBL_MIN_10_EXP);
141 SetIntFlag(DBL_DIG);
142 SetIntFlag(DBL_MANT_DIG);
143 SetDblFlag(DBL_EPSILON);
144 SetIntFlag(FLT_RADIX);
145 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000146#undef SetIntFlag
147#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148
149 if (PyErr_Occurred()) {
150 Py_CLEAR(floatinfo);
151 return NULL;
152 }
153 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000154}
155
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 register PyFloatObject *op;
160 if (free_list == NULL) {
161 if ((free_list = fill_free_list()) == NULL)
162 return NULL;
163 }
164 /* Inline PyObject_New */
165 op = free_list;
166 free_list = (PyFloatObject *)Py_TYPE(op);
167 PyObject_INIT(op, &PyFloat_Type);
168 op->ob_fval = fval;
169 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170}
171
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000173PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 const char *s, *last, *end;
176 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000177 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 Py_ssize_t len;
179 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (PyUnicode_Check(v)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
183 Py_UNICODE *bufptr;
184 s_buffer = PyUnicode_TransformDecimalToASCII(
185 PyUnicode_AS_UNICODE(v), buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000187 return NULL;
188 /* Replace non-ASCII whitespace with ' ' */
189 bufptr = PyUnicode_AS_UNICODE(s_buffer);
190 for (i = 0; i < buflen; i++) {
191 Py_UNICODE ch = bufptr[i];
192 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
193 bufptr[i] = ' ';
194 }
195 s = _PyUnicode_AsStringAndSize(s_buffer, &len);
196 if (s == NULL) {
197 Py_DECREF(s_buffer);
198 return NULL;
199 }
200 last = s + len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 }
202 else if (PyObject_AsCharBuffer(v, &s, &len)) {
203 PyErr_SetString(PyExc_TypeError,
204 "float() argument must be a string or a number");
205 return NULL;
206 }
207 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000208 /* strip space */
209 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000211 while (s < last - 1 && Py_ISSPACE(last[-1]))
212 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* We don't care about overflow or underflow. If the platform
214 * supports them, infinities and signed zeroes (on underflow) are
215 * fine. */
216 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000217 if (end != last) {
218 PyErr_Format(PyExc_ValueError,
219 "could not convert string to float: "
220 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 result = NULL;
222 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000223 else if (x == -1.0 && PyErr_Occurred())
224 result = NULL;
225 else
226 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000227
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000228 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000230}
231
Guido van Rossum234f9421993-06-17 12:35:49 +0000232static void
Fred Drakefd99de62000-07-09 05:02:18 +0000233float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (PyFloat_CheckExact(op)) {
236 Py_TYPE(op) = (struct _typeobject *)free_list;
237 free_list = op;
238 }
239 else
240 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000241}
242
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243double
Fred Drakefd99de62000-07-09 05:02:18 +0000244PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyNumberMethods *nb;
247 PyFloatObject *fo;
248 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (op && PyFloat_Check(op))
251 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (op == NULL) {
254 PyErr_BadArgument();
255 return -1;
256 }
Tim Petersd2364e82001-11-01 20:09:42 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
259 PyErr_SetString(PyExc_TypeError, "a float is required");
260 return -1;
261 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 fo = (PyFloatObject*) (*nb->nb_float) (op);
264 if (fo == NULL)
265 return -1;
266 if (!PyFloat_Check(fo)) {
267 PyErr_SetString(PyExc_TypeError,
268 "nb_float should return float object");
269 return -1;
270 }
Tim Petersd2364e82001-11-01 20:09:42 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 val = PyFloat_AS_DOUBLE(fo);
273 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276}
277
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000279 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000280 set to NULL, and the function invoking this macro returns NULL. If
281 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
282 stored in obj, and returned from the function invoking this macro.
283*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284#define CONVERT_TO_DOUBLE(obj, dbl) \
285 if (PyFloat_Check(obj)) \
286 dbl = PyFloat_AS_DOUBLE(obj); \
287 else if (convert_to_double(&(obj), &(dbl)) < 0) \
288 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000289
Eric Smith0923d1d2009-04-16 20:16:10 +0000290/* Methods */
291
Neil Schemenauer32117e52001-01-04 01:44:34 +0000292static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000293convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (PyLong_Check(obj)) {
298 *dbl = PyLong_AsDouble(obj);
299 if (*dbl == -1.0 && PyErr_Occurred()) {
300 *v = NULL;
301 return -1;
302 }
303 }
304 else {
305 Py_INCREF(Py_NotImplemented);
306 *v = Py_NotImplemented;
307 return -1;
308 }
309 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000310}
311
Eric Smith0923d1d2009-04-16 20:16:10 +0000312static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000313float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000314{
315 PyObject *result;
316 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000317 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000318 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000319 NULL);
320 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000321 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000322 result = PyUnicode_FromString(buf);
323 PyMem_Free(buf);
324 return result;
325}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000326
Tim Peters307fa782004-09-23 08:06:40 +0000327/* Comparison is pretty much a nightmare. When comparing float to float,
328 * we do it as straightforwardly (and long-windedly) as conceivable, so
329 * that, e.g., Python x == y delivers the same result as the platform
330 * C x == y when x and/or y is a NaN.
331 * When mixing float with an integer type, there's no good *uniform* approach.
332 * Converting the double to an integer obviously doesn't work, since we
333 * may lose info from fractional bits. Converting the integer to a double
334 * also has two failure modes: (1) a long int may trigger overflow (too
335 * large to fit in the dynamic range of a C double); (2) even a C long may have
336 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
337 * 63 bits of precision, but a C double probably has only 53), and then
338 * we can falsely claim equality when low-order integer bits are lost by
339 * coercion to double. So this part is painful too.
340 */
341
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342static PyObject*
343float_richcompare(PyObject *v, PyObject *w, int op)
344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 double i, j;
346 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 assert(PyFloat_Check(v));
349 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* Switch on the type of w. Set i and j to doubles to be compared,
352 * and op to the richcomp to use.
353 */
354 if (PyFloat_Check(w))
355 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 else if (!Py_IS_FINITE(i)) {
358 if (PyLong_Check(w))
359 /* If i is an infinity, its magnitude exceeds any
360 * finite integer, so it doesn't matter which int we
361 * compare i with. If i is a NaN, similarly.
362 */
363 j = 0.0;
364 else
365 goto Unimplemented;
366 }
Tim Peters307fa782004-09-23 08:06:40 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 else if (PyLong_Check(w)) {
369 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
370 int wsign = _PyLong_Sign(w);
371 size_t nbits;
372 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (vsign != wsign) {
375 /* Magnitudes are irrelevant -- the signs alone
376 * determine the outcome.
377 */
378 i = (double)vsign;
379 j = (double)wsign;
380 goto Compare;
381 }
382 /* The signs are the same. */
383 /* Convert w to a double if it fits. In particular, 0 fits. */
384 nbits = _PyLong_NumBits(w);
385 if (nbits == (size_t)-1 && PyErr_Occurred()) {
386 /* This long is so large that size_t isn't big enough
387 * to hold the # of bits. Replace with little doubles
388 * that give the same outcome -- w is so large that
389 * its magnitude must exceed the magnitude of any
390 * finite float.
391 */
392 PyErr_Clear();
393 i = (double)vsign;
394 assert(wsign != 0);
395 j = wsign * 2.0;
396 goto Compare;
397 }
398 if (nbits <= 48) {
399 j = PyLong_AsDouble(w);
400 /* It's impossible that <= 48 bits overflowed. */
401 assert(j != -1.0 || ! PyErr_Occurred());
402 goto Compare;
403 }
404 assert(wsign != 0); /* else nbits was 0 */
405 assert(vsign != 0); /* if vsign were 0, then since wsign is
406 * not 0, we would have taken the
407 * vsign != wsign branch at the start */
408 /* We want to work with non-negative numbers. */
409 if (vsign < 0) {
410 /* "Multiply both sides" by -1; this also swaps the
411 * comparator.
412 */
413 i = -i;
414 op = _Py_SwappedOp[op];
415 }
416 assert(i > 0.0);
417 (void) frexp(i, &exponent);
418 /* exponent is the # of bits in v before the radix point;
419 * we know that nbits (the # of bits in w) > 48 at this point
420 */
421 if (exponent < 0 || (size_t)exponent < nbits) {
422 i = 1.0;
423 j = 2.0;
424 goto Compare;
425 }
426 if ((size_t)exponent > nbits) {
427 i = 2.0;
428 j = 1.0;
429 goto Compare;
430 }
431 /* v and w have the same number of bits before the radix
432 * point. Construct two longs that have the same comparison
433 * outcome.
434 */
435 {
436 double fracpart;
437 double intpart;
438 PyObject *result = NULL;
439 PyObject *one = NULL;
440 PyObject *vv = NULL;
441 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (wsign < 0) {
444 ww = PyNumber_Negative(w);
445 if (ww == NULL)
446 goto Error;
447 }
448 else
449 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 fracpart = modf(i, &intpart);
452 vv = PyLong_FromDouble(intpart);
453 if (vv == NULL)
454 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (fracpart != 0.0) {
457 /* Shift left, and or a 1 bit into vv
458 * to represent the lost fraction.
459 */
460 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 one = PyLong_FromLong(1);
463 if (one == NULL)
464 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 temp = PyNumber_Lshift(ww, one);
467 if (temp == NULL)
468 goto Error;
469 Py_DECREF(ww);
470 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 temp = PyNumber_Lshift(vv, one);
473 if (temp == NULL)
474 goto Error;
475 Py_DECREF(vv);
476 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 temp = PyNumber_Or(vv, one);
479 if (temp == NULL)
480 goto Error;
481 Py_DECREF(vv);
482 vv = temp;
483 }
Tim Peters307fa782004-09-23 08:06:40 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 r = PyObject_RichCompareBool(vv, ww, op);
486 if (r < 0)
487 goto Error;
488 result = PyBool_FromLong(r);
489 Error:
490 Py_XDECREF(vv);
491 Py_XDECREF(ww);
492 Py_XDECREF(one);
493 return result;
494 }
495 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 else /* w isn't float, int, or long */
498 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000499
500 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyFPE_START_PROTECT("richcompare", return NULL)
502 switch (op) {
503 case Py_EQ:
504 r = i == j;
505 break;
506 case Py_NE:
507 r = i != j;
508 break;
509 case Py_LE:
510 r = i <= j;
511 break;
512 case Py_GE:
513 r = i >= j;
514 break;
515 case Py_LT:
516 r = i < j;
517 break;
518 case Py_GT:
519 r = i > j;
520 break;
521 }
522 PyFPE_END_PROTECT(r)
523 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000524
525 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 Py_INCREF(Py_NotImplemented);
527 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000528}
529
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000530static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000534}
535
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 double a,b;
540 CONVERT_TO_DOUBLE(v, a);
541 CONVERT_TO_DOUBLE(w, b);
542 PyFPE_START_PROTECT("add", return 0)
543 a = a + b;
544 PyFPE_END_PROTECT(a)
545 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000549float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 double a,b;
552 CONVERT_TO_DOUBLE(v, a);
553 CONVERT_TO_DOUBLE(w, b);
554 PyFPE_START_PROTECT("subtract", return 0)
555 a = a - b;
556 PyFPE_END_PROTECT(a)
557 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 double a,b;
564 CONVERT_TO_DOUBLE(v, a);
565 CONVERT_TO_DOUBLE(w, b);
566 PyFPE_START_PROTECT("multiply", return 0)
567 a = a * b;
568 PyFPE_END_PROTECT(a)
569 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double a,b;
576 CONVERT_TO_DOUBLE(v, a);
577 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (b == 0.0) {
579 PyErr_SetString(PyExc_ZeroDivisionError,
580 "float division by zero");
581 return NULL;
582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyFPE_START_PROTECT("divide", return 0)
584 a = a / b;
585 PyFPE_END_PROTECT(a)
586 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 double vx, wx;
593 double mod;
594 CONVERT_TO_DOUBLE(v, vx);
595 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (wx == 0.0) {
597 PyErr_SetString(PyExc_ZeroDivisionError,
598 "float modulo");
599 return NULL;
600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyFPE_START_PROTECT("modulo", return 0)
602 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000603 if (mod) {
604 /* ensure the remainder has the same sign as the denominator */
605 if ((wx < 0) != (mod < 0)) {
606 mod += wx;
607 }
608 }
609 else {
610 /* the remainder is zero, and in the presence of signed zeroes
611 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000612 it has the same sign as the denominator. */
613 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 }
615 PyFPE_END_PROTECT(mod)
616 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 double vx, wx;
623 double div, mod, floordiv;
624 CONVERT_TO_DOUBLE(v, vx);
625 CONVERT_TO_DOUBLE(w, wx);
626 if (wx == 0.0) {
627 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
628 return NULL;
629 }
630 PyFPE_START_PROTECT("divmod", return 0)
631 mod = fmod(vx, wx);
632 /* fmod is typically exact, so vx-mod is *mathematically* an
633 exact multiple of wx. But this is fp arithmetic, and fp
634 vx - mod is an approximation; the result is that div may
635 not be an exact integral value after the division, although
636 it will always be very close to one.
637 */
638 div = (vx - mod) / wx;
639 if (mod) {
640 /* ensure the remainder has the same sign as the denominator */
641 if ((wx < 0) != (mod < 0)) {
642 mod += wx;
643 div -= 1.0;
644 }
645 }
646 else {
647 /* the remainder is zero, and in the presence of signed zeroes
648 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000649 it has the same sign as the denominator. */
650 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 /* snap quotient to nearest integral value */
653 if (div) {
654 floordiv = floor(div);
655 if (div - floordiv > 0.5)
656 floordiv += 1.0;
657 }
658 else {
659 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000660 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 PyFPE_END_PROTECT(floordiv)
663 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000667float_floor_div(PyObject *v, PyObject *w)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 t = float_divmod(v, w);
672 if (t == NULL || t == Py_NotImplemented)
673 return t;
674 assert(PyTuple_CheckExact(t));
675 r = PyTuple_GET_ITEM(t, 0);
676 Py_INCREF(r);
677 Py_DECREF(t);
678 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000679}
680
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000681/* determine whether x is an odd integer or not; assumes that
682 x is not an infinity or nan. */
683#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
684
Tim Peters63a35712001-12-11 19:57:24 +0000685static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000686float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 double iv, iw, ix;
689 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if ((PyObject *)z != Py_None) {
692 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
693 "allowed unless all arguments are integers");
694 return NULL;
695 }
Tim Peters32f453e2001-09-03 08:35:41 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 CONVERT_TO_DOUBLE(v, iv);
698 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Sort out special cases here instead of relying on pow() */
701 if (iw == 0) { /* v**0 is 1, even 0**0 */
702 return PyFloat_FromDouble(1.0);
703 }
704 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
705 return PyFloat_FromDouble(iv);
706 }
707 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
708 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
709 }
710 if (Py_IS_INFINITY(iw)) {
711 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
712 * abs(v) > 1 (including case where v infinite)
713 *
714 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
715 * abs(v) > 1 (including case where v infinite)
716 */
717 iv = fabs(iv);
718 if (iv == 1.0)
719 return PyFloat_FromDouble(1.0);
720 else if ((iw > 0.0) == (iv > 1.0))
721 return PyFloat_FromDouble(fabs(iw)); /* return inf */
722 else
723 return PyFloat_FromDouble(0.0);
724 }
725 if (Py_IS_INFINITY(iv)) {
726 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
727 * both cases, we need to add the appropriate sign if w is
728 * an odd integer.
729 */
730 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
731 if (iw > 0.0)
732 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
733 else
734 return PyFloat_FromDouble(iw_is_odd ?
735 copysign(0.0, iv) : 0.0);
736 }
737 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
738 (already dealt with above), and an error
739 if w is negative. */
740 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
741 if (iw < 0.0) {
742 PyErr_SetString(PyExc_ZeroDivisionError,
743 "0.0 cannot be raised to a "
744 "negative power");
745 return NULL;
746 }
747 /* use correct sign if iw is odd */
748 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
749 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (iv < 0.0) {
752 /* Whether this is an error is a mess, and bumps into libm
753 * bugs so we have to figure it out ourselves.
754 */
755 if (iw != floor(iw)) {
756 /* Negative numbers raised to fractional powers
757 * become complex.
758 */
759 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
760 }
761 /* iw is an exact integer, albeit perhaps a very large
762 * one. Replace iv by its absolute value and remember
763 * to negate the pow result if iw is odd.
764 */
765 iv = -iv;
766 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
767 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
770 /* (-1) ** large_integer also ends up here. Here's an
771 * extract from the comments for the previous
772 * implementation explaining why this special case is
773 * necessary:
774 *
775 * -1 raised to an exact integer should never be exceptional.
776 * Alas, some libms (chiefly glibc as of early 2003) return
777 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
778 * happen to be representable in a *C* integer. That's a
779 * bug.
780 */
781 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
782 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Now iv and iw are finite, iw is nonzero, and iv is
785 * positive and not equal to 1.0. We finally allow
786 * the platform pow to step in and do the rest.
787 */
788 errno = 0;
789 PyFPE_START_PROTECT("pow", return NULL)
790 ix = pow(iv, iw);
791 PyFPE_END_PROTECT(ix)
792 Py_ADJUST_ERANGE1(ix);
793 if (negate_result)
794 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (errno != 0) {
797 /* We don't expect any errno value other than ERANGE, but
798 * the range of libm bugs appears unbounded.
799 */
800 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
801 PyExc_ValueError);
802 return NULL;
803 }
804 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805}
806
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000807#undef DOUBLE_IS_ODD_INTEGER
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000816float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819}
820
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000821static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000822float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000825}
826
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000827static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000828float_is_integer(PyObject *v)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 double x = PyFloat_AsDouble(v);
831 PyObject *o;
832
833 if (x == -1.0 && PyErr_Occurred())
834 return NULL;
835 if (!Py_IS_FINITE(x))
836 Py_RETURN_FALSE;
837 errno = 0;
838 PyFPE_START_PROTECT("is_integer", return NULL)
839 o = (floor(x) == x) ? Py_True : Py_False;
840 PyFPE_END_PROTECT(x)
841 if (errno != 0) {
842 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
843 PyExc_ValueError);
844 return NULL;
845 }
846 Py_INCREF(o);
847 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000848}
849
850#if 0
851static PyObject *
852float_is_inf(PyObject *v)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 double x = PyFloat_AsDouble(v);
855 if (x == -1.0 && PyErr_Occurred())
856 return NULL;
857 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000858}
859
860static PyObject *
861float_is_nan(PyObject *v)
862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 double x = PyFloat_AsDouble(v);
864 if (x == -1.0 && PyErr_Occurred())
865 return NULL;
866 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000867}
868
869static PyObject *
870float_is_finite(PyObject *v)
871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 double x = PyFloat_AsDouble(v);
873 if (x == -1.0 && PyErr_Occurred())
874 return NULL;
875 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000876}
877#endif
878
879static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000880float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 double x = PyFloat_AsDouble(v);
883 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 (void)modf(x, &wholepart);
886 /* Try to get out cheap if this fits in a Python int. The attempt
887 * to cast to long must be protected, as C doesn't define what
888 * happens if the double is too big to fit in a long. Some rare
889 * systems raise an exception then (RISCOS was mentioned as one,
890 * and someone using a non-default option on Sun also bumped into
891 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
892 * still be vulnerable: if a long has more bits of precision than
893 * a double, casting MIN/MAX to double may yield an approximation,
894 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
895 * yield true from the C expression wholepart<=LONG_MAX, despite
896 * that wholepart is actually greater than LONG_MAX.
897 */
898 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
899 const long aslong = (long)wholepart;
900 return PyLong_FromLong(aslong);
901 }
902 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000903}
904
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905/* double_round: rounds a finite double to the closest multiple of
906 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
907 ndigits <= 323). Returns a Python float, or sets a Python error and
908 returns NULL on failure (OverflowError and memory errors are possible). */
909
910#ifndef PY_NO_SHORT_FLOAT_REPR
911/* version of double_round that uses the correctly-rounded string<->double
912 conversions from Python/dtoa.c */
913
914static PyObject *
915double_round(double x, int ndigits) {
916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 double rounded;
918 Py_ssize_t buflen, mybuflen=100;
919 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
920 int decpt, sign;
921 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000922 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000925 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000927 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (buf == NULL) {
929 PyErr_NoMemory();
930 return NULL;
931 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
934 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
935 buflen = buf_end - buf;
936 if (buflen + 8 > mybuflen) {
937 mybuflen = buflen+8;
938 mybuf = (char *)PyMem_Malloc(mybuflen);
939 if (mybuf == NULL) {
940 PyErr_NoMemory();
941 goto exit;
942 }
943 }
944 /* copy buf to mybuf, adding exponent, sign and leading 0 */
945 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
946 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* and convert the resulting string back to a double */
949 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000950 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000952 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (errno == ERANGE && fabs(rounded) >= 1.)
954 PyErr_SetString(PyExc_OverflowError,
955 "rounded value too large to represent");
956 else
957 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* done computing value; now clean up */
960 if (mybuf != shortbuf)
961 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000962 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 _Py_dg_freedtoa(buf);
964 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000965}
966
967#else /* PY_NO_SHORT_FLOAT_REPR */
968
969/* fallback version, to be used when correctly rounded binary<->decimal
970 conversions aren't available */
971
972static PyObject *
973double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 double pow1, pow2, y, z;
975 if (ndigits >= 0) {
976 if (ndigits > 22) {
977 /* pow1 and pow2 are each safe from overflow, but
978 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
979 pow1 = pow(10.0, (double)(ndigits-22));
980 pow2 = 1e22;
981 }
982 else {
983 pow1 = pow(10.0, (double)ndigits);
984 pow2 = 1.0;
985 }
986 y = (x*pow1)*pow2;
987 /* if y overflows, then rounded value is exactly x */
988 if (!Py_IS_FINITE(y))
989 return PyFloat_FromDouble(x);
990 }
991 else {
992 pow1 = pow(10.0, (double)-ndigits);
993 pow2 = 1.0; /* unused; silences a gcc compiler warning */
994 y = x / pow1;
995 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 z = round(y);
998 if (fabs(y-z) == 0.5)
999 /* halfway between two integers; use round-half-even */
1000 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (ndigits >= 0)
1003 z = (z / pow2) / pow1;
1004 else
1005 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* if computation resulted in overflow, raise OverflowError */
1008 if (!Py_IS_FINITE(z)) {
1009 PyErr_SetString(PyExc_OverflowError,
1010 "overflow occurred during round");
1011 return NULL;
1012 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001015}
1016
1017#endif /* PY_NO_SHORT_FLOAT_REPR */
1018
1019/* round a Python float v to the closest multiple of 10**-ndigits */
1020
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001021static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001022float_round(PyObject *v, PyObject *args)
1023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 double x, rounded;
1025 PyObject *o_ndigits = NULL;
1026 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 x = PyFloat_AsDouble(v);
1029 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1030 return NULL;
1031 if (o_ndigits == NULL) {
1032 /* single-argument round: round to nearest integer */
1033 rounded = round(x);
1034 if (fabs(x-rounded) == 0.5)
1035 /* halfway case: round to even */
1036 rounded = 2.0*round(x/2.0);
1037 return PyLong_FromDouble(rounded);
1038 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* interpret second argument as a Py_ssize_t; clips on overflow */
1041 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1042 if (ndigits == -1 && PyErr_Occurred())
1043 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* nans and infinities round to themselves */
1046 if (!Py_IS_FINITE(x))
1047 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1050 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1051 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001052#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1053#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (ndigits > NDIGITS_MAX)
1055 /* return x */
1056 return PyFloat_FromDouble(x);
1057 else if (ndigits < NDIGITS_MIN)
1058 /* return 0.0, but with sign of x */
1059 return PyFloat_FromDouble(0.0*x);
1060 else
1061 /* finite x, and ndigits is not unreasonably large */
1062 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001063#undef NDIGITS_MAX
1064#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001065}
1066
1067static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001068float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (PyFloat_CheckExact(v))
1071 Py_INCREF(v);
1072 else
1073 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1074 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001075}
1076
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001077/* turn ASCII hex characters into integer values and vice versa */
1078
1079static char
1080char_from_hex(int x)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 assert(0 <= x && x < 16);
1083 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001084}
1085
1086static int
1087hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 int x;
1089 switch(c) {
1090 case '0':
1091 x = 0;
1092 break;
1093 case '1':
1094 x = 1;
1095 break;
1096 case '2':
1097 x = 2;
1098 break;
1099 case '3':
1100 x = 3;
1101 break;
1102 case '4':
1103 x = 4;
1104 break;
1105 case '5':
1106 x = 5;
1107 break;
1108 case '6':
1109 x = 6;
1110 break;
1111 case '7':
1112 x = 7;
1113 break;
1114 case '8':
1115 x = 8;
1116 break;
1117 case '9':
1118 x = 9;
1119 break;
1120 case 'a':
1121 case 'A':
1122 x = 10;
1123 break;
1124 case 'b':
1125 case 'B':
1126 x = 11;
1127 break;
1128 case 'c':
1129 case 'C':
1130 x = 12;
1131 break;
1132 case 'd':
1133 case 'D':
1134 x = 13;
1135 break;
1136 case 'e':
1137 case 'E':
1138 x = 14;
1139 break;
1140 case 'f':
1141 case 'F':
1142 x = 15;
1143 break;
1144 default:
1145 x = -1;
1146 break;
1147 }
1148 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001149}
1150
1151/* convert a float to a hexadecimal string */
1152
1153/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1154 of the form 4k+1. */
1155#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1156
1157static PyObject *
1158float_hex(PyObject *v)
1159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 double x, m;
1161 int e, shift, i, si, esign;
1162 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1163 trailing NUL byte. */
1164 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001169 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001172 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 return PyUnicode_FromString("-0x0.0p+0");
1174 else
1175 return PyUnicode_FromString("0x0.0p+0");
1176 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 m = frexp(fabs(x), &e);
1179 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1180 m = ldexp(m, shift);
1181 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 si = 0;
1184 s[si] = char_from_hex((int)m);
1185 si++;
1186 m -= (int)m;
1187 s[si] = '.';
1188 si++;
1189 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1190 m *= 16.0;
1191 s[si] = char_from_hex((int)m);
1192 si++;
1193 m -= (int)m;
1194 }
1195 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (e < 0) {
1198 esign = (int)'-';
1199 e = -e;
1200 }
1201 else
1202 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (x < 0.0)
1205 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1206 else
1207 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001208}
1209
1210PyDoc_STRVAR(float_hex_doc,
1211"float.hex() -> string\n\
1212\n\
1213Return a hexadecimal representation of a floating-point number.\n\
1214>>> (-0.1).hex()\n\
1215'-0x1.999999999999ap-4'\n\
1216>>> 3.14159.hex()\n\
1217'0x1.921f9f01b866ep+1'");
1218
1219/* Convert a hexadecimal string to a float. */
1220
1221static PyObject *
1222float_fromhex(PyObject *cls, PyObject *arg)
1223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject *result_as_float, *result;
1225 double x;
1226 long exp, top_exp, lsb, key_digit;
1227 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1228 int half_eps, digit, round_up, negate=0;
1229 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 /*
1232 * For the sake of simplicity and correctness, we impose an artificial
1233 * limit on ndigits, the total number of hex digits in the coefficient
1234 * The limit is chosen to ensure that, writing exp for the exponent,
1235 *
1236 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1237 * guaranteed to overflow (provided it's nonzero)
1238 *
1239 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1240 * guaranteed to underflow to 0.
1241 *
1242 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1243 * overflow in the calculation of exp and top_exp below.
1244 *
1245 * More specifically, ndigits is assumed to satisfy the following
1246 * inequalities:
1247 *
1248 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1249 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1250 *
1251 * If either of these inequalities is not satisfied, a ValueError is
1252 * raised. Otherwise, write x for the value of the hex string, and
1253 * assume x is nonzero. Then
1254 *
1255 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1256 *
1257 * Now if exp > LONG_MAX/2 then:
1258 *
1259 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1260 * = DBL_MAX_EXP
1261 *
1262 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1263 * double, so overflows. If exp < LONG_MIN/2, then
1264 *
1265 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1266 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1267 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1268 *
1269 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1270 * when converted to a C double.
1271 *
1272 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1273 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1274 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 s = _PyUnicode_AsStringAndSize(arg, &length);
1277 if (s == NULL)
1278 return NULL;
1279 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 /********************
1282 * Parse the string *
1283 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 /* leading whitespace */
1286 while (Py_ISSPACE(*s))
1287 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 /* infinities and nans */
1290 x = _Py_parse_inf_or_nan(s, &coeff_end);
1291 if (coeff_end != s) {
1292 s = coeff_end;
1293 goto finished;
1294 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 /* optional sign */
1297 if (*s == '-') {
1298 s++;
1299 negate = 1;
1300 }
1301 else if (*s == '+')
1302 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /* [0x] */
1305 s_store = s;
1306 if (*s == '0') {
1307 s++;
1308 if (*s == 'x' || *s == 'X')
1309 s++;
1310 else
1311 s = s_store;
1312 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /* coefficient: <integer> [. <fraction>] */
1315 coeff_start = s;
1316 while (hex_from_char(*s) >= 0)
1317 s++;
1318 s_store = s;
1319 if (*s == '.') {
1320 s++;
1321 while (hex_from_char(*s) >= 0)
1322 s++;
1323 coeff_end = s-1;
1324 }
1325 else
1326 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* ndigits = total # of hex digits; fdigits = # after point */
1329 ndigits = coeff_end - coeff_start;
1330 fdigits = coeff_end - s_store;
1331 if (ndigits == 0)
1332 goto parse_error;
1333 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1334 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1335 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* [p <exponent>] */
1338 if (*s == 'p' || *s == 'P') {
1339 s++;
1340 exp_start = s;
1341 if (*s == '-' || *s == '+')
1342 s++;
1343 if (!('0' <= *s && *s <= '9'))
1344 goto parse_error;
1345 s++;
1346 while ('0' <= *s && *s <= '9')
1347 s++;
1348 exp = strtol(exp_start, NULL, 10);
1349 }
1350 else
1351 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001352
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001353/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1355 coeff_end-(j) : \
1356 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /*******************************************
1359 * Compute rounded value of the hex string *
1360 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* Discard leading zeros, and catch extreme overflow and underflow */
1363 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1364 ndigits--;
1365 if (ndigits == 0 || exp < LONG_MIN/2) {
1366 x = 0.0;
1367 goto finished;
1368 }
1369 if (exp > LONG_MAX/2)
1370 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* Adjust exponent for fractional part. */
1373 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1376 top_exp = exp + 4*((long)ndigits - 1);
1377 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1378 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 /* catch almost all nonextreme cases of overflow and underflow here */
1381 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1382 x = 0.0;
1383 goto finished;
1384 }
1385 if (top_exp > DBL_MAX_EXP)
1386 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 /* lsb = exponent of least significant bit of the *rounded* value.
1389 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1390 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 x = 0.0;
1393 if (exp >= lsb) {
1394 /* no rounding required */
1395 for (i = ndigits-1; i >= 0; i--)
1396 x = 16.0*x + HEX_DIGIT(i);
1397 x = ldexp(x, (int)(exp));
1398 goto finished;
1399 }
1400 /* rounding required. key_digit is the index of the hex digit
1401 containing the first bit to be rounded away. */
1402 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1403 key_digit = (lsb - exp - 1) / 4;
1404 for (i = ndigits-1; i > key_digit; i--)
1405 x = 16.0*x + HEX_DIGIT(i);
1406 digit = HEX_DIGIT(key_digit);
1407 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1410 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1411 if ((digit & half_eps) != 0) {
1412 round_up = 0;
1413 if ((digit & (3*half_eps-1)) != 0 ||
1414 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1415 round_up = 1;
1416 else
1417 for (i = key_digit-1; i >= 0; i--)
1418 if (HEX_DIGIT(i) != 0) {
1419 round_up = 1;
1420 break;
1421 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001422 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 x += 2*half_eps;
1424 if (top_exp == DBL_MAX_EXP &&
1425 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1426 /* overflow corner case: pre-rounded value <
1427 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1428 goto overflow_error;
1429 }
1430 }
1431 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001432
1433 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 /* optional trailing whitespace leading to the end of the string */
1435 while (Py_ISSPACE(*s))
1436 s++;
1437 if (s != s_end)
1438 goto parse_error;
1439 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1440 if (result_as_float == NULL)
1441 return NULL;
1442 result = PyObject_CallObject(cls, result_as_float);
1443 Py_DECREF(result_as_float);
1444 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001445
1446 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyErr_SetString(PyExc_OverflowError,
1448 "hexadecimal value too large to represent as a float");
1449 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001450
1451 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyErr_SetString(PyExc_ValueError,
1453 "invalid hexadecimal floating-point string");
1454 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001455
1456 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyErr_SetString(PyExc_ValueError,
1458 "hexadecimal string too long to convert");
1459 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001460}
1461
1462PyDoc_STRVAR(float_fromhex_doc,
1463"float.fromhex(string) -> float\n\
1464\n\
1465Create a floating-point number from a hexadecimal string.\n\
1466>>> float.fromhex('0x1.ffffp10')\n\
14672047.984375\n\
1468>>> float.fromhex('-0x1p-1074')\n\
1469-4.9406564584124654e-324");
1470
1471
Christian Heimes26855632008-01-27 23:50:43 +00001472static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001473float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 double self;
1476 double float_part;
1477 int exponent;
1478 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *prev;
1481 PyObject *py_exponent = NULL;
1482 PyObject *numerator = NULL;
1483 PyObject *denominator = NULL;
1484 PyObject *result_pair = NULL;
1485 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001486
1487#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 prev = obj; \
1489 obj = call; \
1490 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (Py_IS_INFINITY(self)) {
1495 PyErr_SetString(PyExc_OverflowError,
1496 "Cannot pass infinity to float.as_integer_ratio.");
1497 return NULL;
1498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (Py_IS_NAN(self)) {
1500 PyErr_SetString(PyExc_ValueError,
1501 "Cannot pass NaN to float.as_integer_ratio.");
1502 return NULL;
1503 }
Christian Heimes26855632008-01-27 23:50:43 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1506 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1507 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1510 float_part *= 2.0;
1511 exponent--;
1512 }
1513 /* self == float_part * 2**exponent exactly and float_part is integral.
1514 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1515 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 numerator = PyLong_FromDouble(float_part);
1518 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 /* fold in 2**exponent */
1521 denominator = PyLong_FromLong(1);
1522 py_exponent = PyLong_FromLong(labs((long)exponent));
1523 if (py_exponent == NULL) goto error;
1524 INPLACE_UPDATE(py_exponent,
1525 long_methods->nb_lshift(denominator, py_exponent));
1526 if (py_exponent == NULL) goto error;
1527 if (exponent > 0) {
1528 INPLACE_UPDATE(numerator,
1529 long_methods->nb_multiply(numerator, py_exponent));
1530 if (numerator == NULL) goto error;
1531 }
1532 else {
1533 Py_DECREF(denominator);
1534 denominator = py_exponent;
1535 py_exponent = NULL;
1536 }
1537
1538 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001539
1540#undef INPLACE_UPDATE
1541error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 Py_XDECREF(py_exponent);
1543 Py_XDECREF(denominator);
1544 Py_XDECREF(numerator);
1545 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001546}
1547
1548PyDoc_STRVAR(float_as_integer_ratio_doc,
1549"float.as_integer_ratio() -> (int, int)\n"
1550"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001551"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1552"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001553"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001554"\n"
1555">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001556"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001557">>> (0.0).as_integer_ratio()\n"
1558"(0, 1)\n"
1559">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001560"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001561
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001562
Jeremy Hylton938ace62002-07-17 16:30:39 +00001563static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001564float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1565
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566static PyObject *
1567float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyObject *x = Py_False; /* Integer zero */
1570 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (type != &PyFloat_Type)
1573 return float_subtype_new(type, args, kwds); /* Wimp out */
1574 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1575 return NULL;
1576 /* If it's a string, but not a string subclass, use
1577 PyFloat_FromString. */
1578 if (PyUnicode_CheckExact(x))
1579 return PyFloat_FromString(x);
1580 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581}
1582
Guido van Rossumbef14172001-08-29 15:47:46 +00001583/* Wimpy, slow approach to tp_new calls for subtypes of float:
1584 first create a regular float from whatever arguments we got,
1585 then allocate a subtype instance and initialize its ob_fval
1586 from the regular float. The regular float is then thrown away.
1587*/
1588static PyObject *
1589float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 assert(PyType_IsSubtype(type, &PyFloat_Type));
1594 tmp = float_new(&PyFloat_Type, args, kwds);
1595 if (tmp == NULL)
1596 return NULL;
1597 assert(PyFloat_CheckExact(tmp));
1598 newobj = type->tp_alloc(type, 0);
1599 if (newobj == NULL) {
1600 Py_DECREF(tmp);
1601 return NULL;
1602 }
1603 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1604 Py_DECREF(tmp);
1605 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001606}
1607
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001608static PyObject *
1609float_getnewargs(PyFloatObject *v)
1610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001612}
1613
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614/* this is for the benefit of the pack/unpack routines below */
1615
1616typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618} float_format_type;
1619
1620static float_format_type double_format, float_format;
1621static float_format_type detected_double_format, detected_float_format;
1622
1623static PyObject *
1624float_getformat(PyTypeObject *v, PyObject* arg)
1625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 char* s;
1627 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (!PyUnicode_Check(arg)) {
1630 PyErr_Format(PyExc_TypeError,
1631 "__getformat__() argument must be string, not %.500s",
1632 Py_TYPE(arg)->tp_name);
1633 return NULL;
1634 }
1635 s = _PyUnicode_AsString(arg);
1636 if (s == NULL)
1637 return NULL;
1638 if (strcmp(s, "double") == 0) {
1639 r = double_format;
1640 }
1641 else if (strcmp(s, "float") == 0) {
1642 r = float_format;
1643 }
1644 else {
1645 PyErr_SetString(PyExc_ValueError,
1646 "__getformat__() argument 1 must be "
1647 "'double' or 'float'");
1648 return NULL;
1649 }
1650
1651 switch (r) {
1652 case unknown_format:
1653 return PyUnicode_FromString("unknown");
1654 case ieee_little_endian_format:
1655 return PyUnicode_FromString("IEEE, little-endian");
1656 case ieee_big_endian_format:
1657 return PyUnicode_FromString("IEEE, big-endian");
1658 default:
1659 Py_FatalError("insane float_format or double_format");
1660 return NULL;
1661 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001662}
1663
1664PyDoc_STRVAR(float_getformat_doc,
1665"float.__getformat__(typestr) -> string\n"
1666"\n"
1667"You probably don't want to use this function. It exists mainly to be\n"
1668"used in Python's test suite.\n"
1669"\n"
1670"typestr must be 'double' or 'float'. This function returns whichever of\n"
1671"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1672"format of floating point numbers used by the C type named by typestr.");
1673
1674static PyObject *
1675float_setformat(PyTypeObject *v, PyObject* args)
1676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 char* typestr;
1678 char* format;
1679 float_format_type f;
1680 float_format_type detected;
1681 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1684 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (strcmp(typestr, "double") == 0) {
1687 p = &double_format;
1688 detected = detected_double_format;
1689 }
1690 else if (strcmp(typestr, "float") == 0) {
1691 p = &float_format;
1692 detected = detected_float_format;
1693 }
1694 else {
1695 PyErr_SetString(PyExc_ValueError,
1696 "__setformat__() argument 1 must "
1697 "be 'double' or 'float'");
1698 return NULL;
1699 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (strcmp(format, "unknown") == 0) {
1702 f = unknown_format;
1703 }
1704 else if (strcmp(format, "IEEE, little-endian") == 0) {
1705 f = ieee_little_endian_format;
1706 }
1707 else if (strcmp(format, "IEEE, big-endian") == 0) {
1708 f = ieee_big_endian_format;
1709 }
1710 else {
1711 PyErr_SetString(PyExc_ValueError,
1712 "__setformat__() argument 2 must be "
1713 "'unknown', 'IEEE, little-endian' or "
1714 "'IEEE, big-endian'");
1715 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (f != unknown_format && f != detected) {
1720 PyErr_Format(PyExc_ValueError,
1721 "can only set %s format to 'unknown' or the "
1722 "detected platform value", typestr);
1723 return NULL;
1724 }
1725
1726 *p = f;
1727 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001728}
1729
1730PyDoc_STRVAR(float_setformat_doc,
1731"float.__setformat__(typestr, fmt) -> None\n"
1732"\n"
1733"You probably don't want to use this function. It exists mainly to be\n"
1734"used in Python's test suite.\n"
1735"\n"
1736"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1737"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1738"one of the latter two if it appears to match the underlying C reality.\n"
1739"\n"
1740"Overrides the automatic determination of C-level floating point type.\n"
1741"This affects how floats are converted to and from binary strings.");
1742
Guido van Rossumb43daf72007-08-01 18:08:08 +00001743static PyObject *
1744float_getzero(PyObject *v, void *closure)
1745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001747}
1748
Eric Smith8c663262007-08-25 02:26:07 +00001749static PyObject *
1750float__format__(PyObject *self, PyObject *args)
1751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1755 return NULL;
1756 return _PyFloat_FormatAdvanced(self,
1757 PyUnicode_AS_UNICODE(format_spec),
1758 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001759}
1760
1761PyDoc_STRVAR(float__format__doc,
1762"float.__format__(format_spec) -> string\n"
1763"\n"
1764"Formats the float according to format_spec.");
1765
1766
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001767static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1769 "Returns self, the complex conjugate of any float."},
1770 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1771 "Returns the Integral closest to x between 0 and x."},
1772 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1773 "Returns the Integral closest to x, rounding half toward even.\n"
1774 "When an argument is passed, works like built-in round(x, ndigits)."},
1775 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1776 float_as_integer_ratio_doc},
1777 {"fromhex", (PyCFunction)float_fromhex,
1778 METH_O|METH_CLASS, float_fromhex_doc},
1779 {"hex", (PyCFunction)float_hex,
1780 METH_NOARGS, float_hex_doc},
1781 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1782 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001783#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1785 "Returns True if the float is positive or negative infinite."},
1786 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1787 "Returns True if the float is finite, neither infinite nor NaN."},
1788 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1789 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001790#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1792 {"__getformat__", (PyCFunction)float_getformat,
1793 METH_O|METH_CLASS, float_getformat_doc},
1794 {"__setformat__", (PyCFunction)float_setformat,
1795 METH_VARARGS|METH_CLASS, float_setformat_doc},
1796 {"__format__", (PyCFunction)float__format__,
1797 METH_VARARGS, float__format__doc},
1798 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001799};
1800
Guido van Rossumb43daf72007-08-01 18:08:08 +00001801static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001803 (getter)float_float, (setter)NULL,
1804 "the real part of a complex number",
1805 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001807 (getter)float_getzero, (setter)NULL,
1808 "the imaginary part of a complex number",
1809 NULL},
1810 {NULL} /* Sentinel */
1811};
1812
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001813PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814"float(x) -> floating point number\n\
1815\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001816Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817
1818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 float_add, /*nb_add*/
1821 float_sub, /*nb_subtract*/
1822 float_mul, /*nb_multiply*/
1823 float_rem, /*nb_remainder*/
1824 float_divmod, /*nb_divmod*/
1825 float_pow, /*nb_power*/
1826 (unaryfunc)float_neg, /*nb_negative*/
1827 (unaryfunc)float_float, /*nb_positive*/
1828 (unaryfunc)float_abs, /*nb_absolute*/
1829 (inquiry)float_bool, /*nb_bool*/
1830 0, /*nb_invert*/
1831 0, /*nb_lshift*/
1832 0, /*nb_rshift*/
1833 0, /*nb_and*/
1834 0, /*nb_xor*/
1835 0, /*nb_or*/
1836 float_trunc, /*nb_int*/
1837 0, /*nb_reserved*/
1838 float_float, /*nb_float*/
1839 0, /* nb_inplace_add */
1840 0, /* nb_inplace_subtract */
1841 0, /* nb_inplace_multiply */
1842 0, /* nb_inplace_remainder */
1843 0, /* nb_inplace_power */
1844 0, /* nb_inplace_lshift */
1845 0, /* nb_inplace_rshift */
1846 0, /* nb_inplace_and */
1847 0, /* nb_inplace_xor */
1848 0, /* nb_inplace_or */
1849 float_floor_div, /* nb_floor_divide */
1850 float_div, /* nb_true_divide */
1851 0, /* nb_inplace_floor_divide */
1852 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853};
1854
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001855PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1857 "float",
1858 sizeof(PyFloatObject),
1859 0,
1860 (destructor)float_dealloc, /* tp_dealloc */
1861 0, /* tp_print */
1862 0, /* tp_getattr */
1863 0, /* tp_setattr */
1864 0, /* tp_reserved */
1865 (reprfunc)float_repr, /* tp_repr */
1866 &float_as_number, /* tp_as_number */
1867 0, /* tp_as_sequence */
1868 0, /* tp_as_mapping */
1869 (hashfunc)float_hash, /* tp_hash */
1870 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001871 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyObject_GenericGetAttr, /* tp_getattro */
1873 0, /* tp_setattro */
1874 0, /* tp_as_buffer */
1875 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1876 float_doc, /* tp_doc */
1877 0, /* tp_traverse */
1878 0, /* tp_clear */
1879 float_richcompare, /* tp_richcompare */
1880 0, /* tp_weaklistoffset */
1881 0, /* tp_iter */
1882 0, /* tp_iternext */
1883 float_methods, /* tp_methods */
1884 0, /* tp_members */
1885 float_getset, /* tp_getset */
1886 0, /* tp_base */
1887 0, /* tp_dict */
1888 0, /* tp_descr_get */
1889 0, /* tp_descr_set */
1890 0, /* tp_dictoffset */
1891 0, /* tp_init */
1892 0, /* tp_alloc */
1893 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001894};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001895
1896void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001897_PyFloat_Init(void)
1898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* We attempt to determine if this machine is using IEEE
1900 floating point formats by peering at the bits of some
1901 carefully chosen values. If it looks like we are on an
1902 IEEE platform, the float packing/unpacking routines can
1903 just copy bits, if not they resort to arithmetic & shifts
1904 and masks. The shifts & masks approach works on all finite
1905 values, but what happens to infinities, NaNs and signed
1906 zeroes on packing is an accident, and attempting to unpack
1907 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 Note that if we're on some whacked-out platform which uses
1910 IEEE formats but isn't strictly little-endian or big-
1911 endian, we will fall back to the portable shifts & masks
1912 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001913
1914#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 {
1916 double x = 9006104071832581.0;
1917 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1918 detected_double_format = ieee_big_endian_format;
1919 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1920 detected_double_format = ieee_little_endian_format;
1921 else
1922 detected_double_format = unknown_format;
1923 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001926#endif
1927
1928#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 {
1930 float y = 16711938.0;
1931 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1932 detected_float_format = ieee_big_endian_format;
1933 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1934 detected_float_format = ieee_little_endian_format;
1935 else
1936 detected_float_format = unknown_format;
1937 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001938#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940#endif
1941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 double_format = detected_double_format;
1943 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* Init float info */
1946 if (FloatInfoType.tp_name == 0)
1947 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001948}
1949
Georg Brandl2ee470f2008-07-16 12:55:28 +00001950int
1951PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyFloatObject *p;
1954 PyFloatBlock *list, *next;
1955 int i;
1956 int u; /* remaining unfreed floats per block */
1957 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 list = block_list;
1960 block_list = NULL;
1961 free_list = NULL;
1962 while (list != NULL) {
1963 u = 0;
1964 for (i = 0, p = &list->objects[0];
1965 i < N_FLOATOBJECTS;
1966 i++, p++) {
1967 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1968 u++;
1969 }
1970 next = list->next;
1971 if (u) {
1972 list->next = block_list;
1973 block_list = list;
1974 for (i = 0, p = &list->objects[0];
1975 i < N_FLOATOBJECTS;
1976 i++, p++) {
1977 if (!PyFloat_CheckExact(p) ||
1978 Py_REFCNT(p) == 0) {
1979 Py_TYPE(p) = (struct _typeobject *)
1980 free_list;
1981 free_list = p;
1982 }
1983 }
1984 }
1985 else {
1986 PyMem_FREE(list);
1987 }
1988 freelist_size += u;
1989 list = next;
1990 }
1991 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001992}
1993
1994void
1995PyFloat_Fini(void)
1996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 PyFloatObject *p;
1998 PyFloatBlock *list;
1999 int i;
2000 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (!Py_VerboseFlag)
2005 return;
2006 fprintf(stderr, "# cleanup floats");
2007 if (!u) {
2008 fprintf(stderr, "\n");
2009 }
2010 else {
2011 fprintf(stderr,
2012 ": %d unfreed float%s\n",
2013 u, u == 1 ? "" : "s");
2014 }
2015 if (Py_VerboseFlag > 1) {
2016 list = block_list;
2017 while (list != NULL) {
2018 for (i = 0, p = &list->objects[0];
2019 i < N_FLOATOBJECTS;
2020 i++, p++) {
2021 if (PyFloat_CheckExact(p) &&
2022 Py_REFCNT(p) != 0) {
2023 char *buf = PyOS_double_to_string(
2024 PyFloat_AS_DOUBLE(p), 'r',
2025 0, 0, NULL);
2026 if (buf) {
2027 /* XXX(twouters) cast
2028 refcount to long
2029 until %zd is
2030 universally
2031 available
2032 */
2033 fprintf(stderr,
2034 "# <float at %p, refcnt=%ld, val=%s>\n",
2035 p, (long)Py_REFCNT(p), buf);
2036 PyMem_Free(buf);
2037 }
2038 }
2039 }
2040 list = list->next;
2041 }
2042 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002043}
Tim Peters9905b942003-03-20 20:53:32 +00002044
2045/*----------------------------------------------------------------------------
2046 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002047 */
2048int
2049_PyFloat_Pack4(double x, unsigned char *p, int le)
2050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (float_format == unknown_format) {
2052 unsigned char sign;
2053 int e;
2054 double f;
2055 unsigned int fbits;
2056 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (le) {
2059 p += 3;
2060 incr = -1;
2061 }
Tim Peters9905b942003-03-20 20:53:32 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (x < 0) {
2064 sign = 1;
2065 x = -x;
2066 }
2067 else
2068 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 /* Normalize f to be in the range [1.0, 2.0) */
2073 if (0.5 <= f && f < 1.0) {
2074 f *= 2.0;
2075 e--;
2076 }
2077 else if (f == 0.0)
2078 e = 0;
2079 else {
2080 PyErr_SetString(PyExc_SystemError,
2081 "frexp() result out of range");
2082 return -1;
2083 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (e >= 128)
2086 goto Overflow;
2087 else if (e < -126) {
2088 /* Gradual underflow */
2089 f = ldexp(f, 126 + e);
2090 e = 0;
2091 }
2092 else if (!(e == 0 && f == 0.0)) {
2093 e += 127;
2094 f -= 1.0; /* Get rid of leading 1 */
2095 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 f *= 8388608.0; /* 2**23 */
2098 fbits = (unsigned int)(f + 0.5); /* Round */
2099 assert(fbits <= 8388608);
2100 if (fbits >> 23) {
2101 /* The carry propagated out of a string of 23 1 bits. */
2102 fbits = 0;
2103 ++e;
2104 if (e >= 255)
2105 goto Overflow;
2106 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 /* First byte */
2109 *p = (sign << 7) | (e >> 1);
2110 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 /* Second byte */
2113 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2114 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 /* Third byte */
2117 *p = (fbits >> 8) & 0xFF;
2118 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 /* Fourth byte */
2121 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* Done */
2124 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 }
2127 else {
2128 float y = (float)x;
2129 const char *s = (char*)&y;
2130 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2133 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if ((float_format == ieee_little_endian_format && !le)
2136 || (float_format == ieee_big_endian_format && le)) {
2137 p += 3;
2138 incr = -1;
2139 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 for (i = 0; i < 4; i++) {
2142 *p = *s++;
2143 p += incr;
2144 }
2145 return 0;
2146 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002147 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyErr_SetString(PyExc_OverflowError,
2149 "float too large to pack with f format");
2150 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002151}
2152
2153int
2154_PyFloat_Pack8(double x, unsigned char *p, int le)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (double_format == unknown_format) {
2157 unsigned char sign;
2158 int e;
2159 double f;
2160 unsigned int fhi, flo;
2161 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (le) {
2164 p += 7;
2165 incr = -1;
2166 }
Tim Peters9905b942003-03-20 20:53:32 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (x < 0) {
2169 sign = 1;
2170 x = -x;
2171 }
2172 else
2173 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* Normalize f to be in the range [1.0, 2.0) */
2178 if (0.5 <= f && f < 1.0) {
2179 f *= 2.0;
2180 e--;
2181 }
2182 else if (f == 0.0)
2183 e = 0;
2184 else {
2185 PyErr_SetString(PyExc_SystemError,
2186 "frexp() result out of range");
2187 return -1;
2188 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (e >= 1024)
2191 goto Overflow;
2192 else if (e < -1022) {
2193 /* Gradual underflow */
2194 f = ldexp(f, 1022 + e);
2195 e = 0;
2196 }
2197 else if (!(e == 0 && f == 0.0)) {
2198 e += 1023;
2199 f -= 1.0; /* Get rid of leading 1 */
2200 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2203 f *= 268435456.0; /* 2**28 */
2204 fhi = (unsigned int)f; /* Truncate */
2205 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 f -= (double)fhi;
2208 f *= 16777216.0; /* 2**24 */
2209 flo = (unsigned int)(f + 0.5); /* Round */
2210 assert(flo <= 16777216);
2211 if (flo >> 24) {
2212 /* The carry propagated out of a string of 24 1 bits. */
2213 flo = 0;
2214 ++fhi;
2215 if (fhi >> 28) {
2216 /* And it also progagated out of the next 28 bits. */
2217 fhi = 0;
2218 ++e;
2219 if (e >= 2047)
2220 goto Overflow;
2221 }
2222 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* First byte */
2225 *p = (sign << 7) | (e >> 4);
2226 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Second byte */
2229 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2230 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* Third byte */
2233 *p = (fhi >> 16) & 0xFF;
2234 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Fourth byte */
2237 *p = (fhi >> 8) & 0xFF;
2238 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Fifth byte */
2241 *p = fhi & 0xFF;
2242 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Sixth byte */
2245 *p = (flo >> 16) & 0xFF;
2246 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* Seventh byte */
2249 *p = (flo >> 8) & 0xFF;
2250 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* Eighth byte */
2253 *p = flo & 0xFF;
2254 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* Done */
2257 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Overflow:
2260 PyErr_SetString(PyExc_OverflowError,
2261 "float too large to pack with d format");
2262 return -1;
2263 }
2264 else {
2265 const char *s = (char*)&x;
2266 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if ((double_format == ieee_little_endian_format && !le)
2269 || (double_format == ieee_big_endian_format && le)) {
2270 p += 7;
2271 incr = -1;
2272 }
2273
2274 for (i = 0; i < 8; i++) {
2275 *p = *s++;
2276 p += incr;
2277 }
2278 return 0;
2279 }
Tim Peters9905b942003-03-20 20:53:32 +00002280}
2281
2282double
2283_PyFloat_Unpack4(const unsigned char *p, int le)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (float_format == unknown_format) {
2286 unsigned char sign;
2287 int e;
2288 unsigned int f;
2289 double x;
2290 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (le) {
2293 p += 3;
2294 incr = -1;
2295 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* First byte */
2298 sign = (*p >> 7) & 1;
2299 e = (*p & 0x7F) << 1;
2300 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Second byte */
2303 e |= (*p >> 7) & 1;
2304 f = (*p & 0x7F) << 16;
2305 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (e == 255) {
2308 PyErr_SetString(
2309 PyExc_ValueError,
2310 "can't unpack IEEE 754 special value "
2311 "on non-IEEE platform");
2312 return -1;
2313 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* Third byte */
2316 f |= *p << 8;
2317 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* Fourth byte */
2320 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* XXX This sadly ignores Inf/NaN issues */
2325 if (e == 0)
2326 e = -126;
2327 else {
2328 x += 1.0;
2329 e -= 127;
2330 }
2331 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (sign)
2334 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 return x;
2337 }
2338 else {
2339 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 if ((float_format == ieee_little_endian_format && !le)
2342 || (float_format == ieee_big_endian_format && le)) {
2343 char buf[4];
2344 char *d = &buf[3];
2345 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 for (i = 0; i < 4; i++) {
2348 *d-- = *p++;
2349 }
2350 memcpy(&x, buf, 4);
2351 }
2352 else {
2353 memcpy(&x, p, 4);
2354 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return x;
2357 }
Tim Peters9905b942003-03-20 20:53:32 +00002358}
2359
2360double
2361_PyFloat_Unpack8(const unsigned char *p, int le)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (double_format == unknown_format) {
2364 unsigned char sign;
2365 int e;
2366 unsigned int fhi, flo;
2367 double x;
2368 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 if (le) {
2371 p += 7;
2372 incr = -1;
2373 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* First byte */
2376 sign = (*p >> 7) & 1;
2377 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Second byte */
2382 e |= (*p >> 4) & 0xF;
2383 fhi = (*p & 0xF) << 24;
2384 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (e == 2047) {
2387 PyErr_SetString(
2388 PyExc_ValueError,
2389 "can't unpack IEEE 754 special value "
2390 "on non-IEEE platform");
2391 return -1.0;
2392 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* Third byte */
2395 fhi |= *p << 16;
2396 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 /* Fourth byte */
2399 fhi |= *p << 8;
2400 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Fifth byte */
2403 fhi |= *p;
2404 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 /* Sixth byte */
2407 flo = *p << 16;
2408 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* Seventh byte */
2411 flo |= *p << 8;
2412 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* Eighth byte */
2415 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2418 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (e == 0)
2421 e = -1022;
2422 else {
2423 x += 1.0;
2424 e -= 1023;
2425 }
2426 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 if (sign)
2429 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 return x;
2432 }
2433 else {
2434 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 if ((double_format == ieee_little_endian_format && !le)
2437 || (double_format == ieee_big_endian_format && le)) {
2438 char buf[8];
2439 char *d = &buf[7];
2440 int i;
2441
2442 for (i = 0; i < 8; i++) {
2443 *d-- = *p++;
2444 }
2445 memcpy(&x, buf, 8);
2446 }
2447 else {
2448 memcpy(&x, p, 8);
2449 }
2450
2451 return x;
2452 }
Tim Peters9905b942003-03-20 20:53:32 +00002453}