blob: 8409f0a13aae5e73ba0fcd7675ec9ae723cbe798 [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);
Christian Heimes53876d92008-04-19 00:31:39 +0000578#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (b == 0.0) {
580 PyErr_SetString(PyExc_ZeroDivisionError,
581 "float division by zero");
582 return NULL;
583 }
Christian Heimes53876d92008-04-19 00:31:39 +0000584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 PyFPE_START_PROTECT("divide", return 0)
586 a = a / b;
587 PyFPE_END_PROTECT(a)
588 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000589}
590
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000592float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 double vx, wx;
595 double mod;
596 CONVERT_TO_DOUBLE(v, vx);
597 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000598#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (wx == 0.0) {
600 PyErr_SetString(PyExc_ZeroDivisionError,
601 "float modulo");
602 return NULL;
603 }
Christian Heimes53876d92008-04-19 00:31:39 +0000604#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 PyFPE_START_PROTECT("modulo", return 0)
606 mod = fmod(vx, wx);
607 /* note: checking mod*wx < 0 is incorrect -- underflows to
608 0 if wx < sqrt(smallest nonzero double) */
609 if (mod && ((wx < 0) != (mod < 0))) {
610 mod += wx;
611 }
612 PyFPE_END_PROTECT(mod)
613 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000614}
615
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000617float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 double vx, wx;
620 double div, mod, floordiv;
621 CONVERT_TO_DOUBLE(v, vx);
622 CONVERT_TO_DOUBLE(w, wx);
623 if (wx == 0.0) {
624 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
625 return NULL;
626 }
627 PyFPE_START_PROTECT("divmod", return 0)
628 mod = fmod(vx, wx);
629 /* fmod is typically exact, so vx-mod is *mathematically* an
630 exact multiple of wx. But this is fp arithmetic, and fp
631 vx - mod is an approximation; the result is that div may
632 not be an exact integral value after the division, although
633 it will always be very close to one.
634 */
635 div = (vx - mod) / wx;
636 if (mod) {
637 /* ensure the remainder has the same sign as the denominator */
638 if ((wx < 0) != (mod < 0)) {
639 mod += wx;
640 div -= 1.0;
641 }
642 }
643 else {
644 /* the remainder is zero, and in the presence of signed zeroes
645 fmod returns different results across platforms; ensure
646 it has the same sign as the denominator; we'd like to do
647 "mod = wx * 0.0", but that may get optimized away */
648 mod *= mod; /* hide "mod = +0" from optimizer */
649 if (wx < 0.0)
650 mod = -mod;
651 }
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 */
660 div *= div; /* hide "div = +0" from optimizers */
661 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
662 }
663 PyFPE_END_PROTECT(floordiv)
664 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000665}
666
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000668float_floor_div(PyObject *v, PyObject *w)
669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 t = float_divmod(v, w);
673 if (t == NULL || t == Py_NotImplemented)
674 return t;
675 assert(PyTuple_CheckExact(t));
676 r = PyTuple_GET_ITEM(t, 0);
677 Py_INCREF(r);
678 Py_DECREF(t);
679 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000680}
681
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000682/* determine whether x is an odd integer or not; assumes that
683 x is not an infinity or nan. */
684#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
685
Tim Peters63a35712001-12-11 19:57:24 +0000686static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000687float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 double iv, iw, ix;
690 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if ((PyObject *)z != Py_None) {
693 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
694 "allowed unless all arguments are integers");
695 return NULL;
696 }
Tim Peters32f453e2001-09-03 08:35:41 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 CONVERT_TO_DOUBLE(v, iv);
699 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 /* Sort out special cases here instead of relying on pow() */
702 if (iw == 0) { /* v**0 is 1, even 0**0 */
703 return PyFloat_FromDouble(1.0);
704 }
705 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
706 return PyFloat_FromDouble(iv);
707 }
708 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
709 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
710 }
711 if (Py_IS_INFINITY(iw)) {
712 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
713 * abs(v) > 1 (including case where v infinite)
714 *
715 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
716 * abs(v) > 1 (including case where v infinite)
717 */
718 iv = fabs(iv);
719 if (iv == 1.0)
720 return PyFloat_FromDouble(1.0);
721 else if ((iw > 0.0) == (iv > 1.0))
722 return PyFloat_FromDouble(fabs(iw)); /* return inf */
723 else
724 return PyFloat_FromDouble(0.0);
725 }
726 if (Py_IS_INFINITY(iv)) {
727 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
728 * both cases, we need to add the appropriate sign if w is
729 * an odd integer.
730 */
731 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
732 if (iw > 0.0)
733 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
734 else
735 return PyFloat_FromDouble(iw_is_odd ?
736 copysign(0.0, iv) : 0.0);
737 }
738 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
739 (already dealt with above), and an error
740 if w is negative. */
741 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
742 if (iw < 0.0) {
743 PyErr_SetString(PyExc_ZeroDivisionError,
744 "0.0 cannot be raised to a "
745 "negative power");
746 return NULL;
747 }
748 /* use correct sign if iw is odd */
749 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
750 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (iv < 0.0) {
753 /* Whether this is an error is a mess, and bumps into libm
754 * bugs so we have to figure it out ourselves.
755 */
756 if (iw != floor(iw)) {
757 /* Negative numbers raised to fractional powers
758 * become complex.
759 */
760 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
761 }
762 /* iw is an exact integer, albeit perhaps a very large
763 * one. Replace iv by its absolute value and remember
764 * to negate the pow result if iw is odd.
765 */
766 iv = -iv;
767 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
768 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
771 /* (-1) ** large_integer also ends up here. Here's an
772 * extract from the comments for the previous
773 * implementation explaining why this special case is
774 * necessary:
775 *
776 * -1 raised to an exact integer should never be exceptional.
777 * Alas, some libms (chiefly glibc as of early 2003) return
778 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
779 * happen to be representable in a *C* integer. That's a
780 * bug.
781 */
782 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
783 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* Now iv and iw are finite, iw is nonzero, and iv is
786 * positive and not equal to 1.0. We finally allow
787 * the platform pow to step in and do the rest.
788 */
789 errno = 0;
790 PyFPE_START_PROTECT("pow", return NULL)
791 ix = pow(iv, iw);
792 PyFPE_END_PROTECT(ix)
793 Py_ADJUST_ERANGE1(ix);
794 if (negate_result)
795 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 if (errno != 0) {
798 /* We don't expect any errno value other than ERANGE, but
799 * the range of libm bugs appears unbounded.
800 */
801 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
802 PyExc_ValueError);
803 return NULL;
804 }
805 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806}
807
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000808#undef DOUBLE_IS_ODD_INTEGER
809
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000810static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000811float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000814}
815
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000816static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000817float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820}
821
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000822static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000823float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000826}
827
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000828static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000829float_is_integer(PyObject *v)
830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 double x = PyFloat_AsDouble(v);
832 PyObject *o;
833
834 if (x == -1.0 && PyErr_Occurred())
835 return NULL;
836 if (!Py_IS_FINITE(x))
837 Py_RETURN_FALSE;
838 errno = 0;
839 PyFPE_START_PROTECT("is_integer", return NULL)
840 o = (floor(x) == x) ? Py_True : Py_False;
841 PyFPE_END_PROTECT(x)
842 if (errno != 0) {
843 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
844 PyExc_ValueError);
845 return NULL;
846 }
847 Py_INCREF(o);
848 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000849}
850
851#if 0
852static PyObject *
853float_is_inf(PyObject *v)
854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 double x = PyFloat_AsDouble(v);
856 if (x == -1.0 && PyErr_Occurred())
857 return NULL;
858 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000859}
860
861static PyObject *
862float_is_nan(PyObject *v)
863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 double x = PyFloat_AsDouble(v);
865 if (x == -1.0 && PyErr_Occurred())
866 return NULL;
867 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000868}
869
870static PyObject *
871float_is_finite(PyObject *v)
872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 double x = PyFloat_AsDouble(v);
874 if (x == -1.0 && PyErr_Occurred())
875 return NULL;
876 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000877}
878#endif
879
880static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000881float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 double x = PyFloat_AsDouble(v);
884 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 (void)modf(x, &wholepart);
887 /* Try to get out cheap if this fits in a Python int. The attempt
888 * to cast to long must be protected, as C doesn't define what
889 * happens if the double is too big to fit in a long. Some rare
890 * systems raise an exception then (RISCOS was mentioned as one,
891 * and someone using a non-default option on Sun also bumped into
892 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
893 * still be vulnerable: if a long has more bits of precision than
894 * a double, casting MIN/MAX to double may yield an approximation,
895 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
896 * yield true from the C expression wholepart<=LONG_MAX, despite
897 * that wholepart is actually greater than LONG_MAX.
898 */
899 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
900 const long aslong = (long)wholepart;
901 return PyLong_FromLong(aslong);
902 }
903 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000904}
905
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000906/* double_round: rounds a finite double to the closest multiple of
907 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
908 ndigits <= 323). Returns a Python float, or sets a Python error and
909 returns NULL on failure (OverflowError and memory errors are possible). */
910
911#ifndef PY_NO_SHORT_FLOAT_REPR
912/* version of double_round that uses the correctly-rounded string<->double
913 conversions from Python/dtoa.c */
914
915static PyObject *
916double_round(double x, int ndigits) {
917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 double rounded;
919 Py_ssize_t buflen, mybuflen=100;
920 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
921 int decpt, sign;
922 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* round to a decimal string */
925 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
926 if (buf == NULL) {
927 PyErr_NoMemory();
928 return NULL;
929 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
932 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
933 buflen = buf_end - buf;
934 if (buflen + 8 > mybuflen) {
935 mybuflen = buflen+8;
936 mybuf = (char *)PyMem_Malloc(mybuflen);
937 if (mybuf == NULL) {
938 PyErr_NoMemory();
939 goto exit;
940 }
941 }
942 /* copy buf to mybuf, adding exponent, sign and leading 0 */
943 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
944 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* and convert the resulting string back to a double */
947 errno = 0;
948 rounded = _Py_dg_strtod(mybuf, NULL);
949 if (errno == ERANGE && fabs(rounded) >= 1.)
950 PyErr_SetString(PyExc_OverflowError,
951 "rounded value too large to represent");
952 else
953 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* done computing value; now clean up */
956 if (mybuf != shortbuf)
957 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000958 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 _Py_dg_freedtoa(buf);
960 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000961}
962
963#else /* PY_NO_SHORT_FLOAT_REPR */
964
965/* fallback version, to be used when correctly rounded binary<->decimal
966 conversions aren't available */
967
968static PyObject *
969double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 double pow1, pow2, y, z;
971 if (ndigits >= 0) {
972 if (ndigits > 22) {
973 /* pow1 and pow2 are each safe from overflow, but
974 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
975 pow1 = pow(10.0, (double)(ndigits-22));
976 pow2 = 1e22;
977 }
978 else {
979 pow1 = pow(10.0, (double)ndigits);
980 pow2 = 1.0;
981 }
982 y = (x*pow1)*pow2;
983 /* if y overflows, then rounded value is exactly x */
984 if (!Py_IS_FINITE(y))
985 return PyFloat_FromDouble(x);
986 }
987 else {
988 pow1 = pow(10.0, (double)-ndigits);
989 pow2 = 1.0; /* unused; silences a gcc compiler warning */
990 y = x / pow1;
991 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 z = round(y);
994 if (fabs(y-z) == 0.5)
995 /* halfway between two integers; use round-half-even */
996 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (ndigits >= 0)
999 z = (z / pow2) / pow1;
1000 else
1001 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 /* if computation resulted in overflow, raise OverflowError */
1004 if (!Py_IS_FINITE(z)) {
1005 PyErr_SetString(PyExc_OverflowError,
1006 "overflow occurred during round");
1007 return NULL;
1008 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001011}
1012
1013#endif /* PY_NO_SHORT_FLOAT_REPR */
1014
1015/* round a Python float v to the closest multiple of 10**-ndigits */
1016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001017static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001018float_round(PyObject *v, PyObject *args)
1019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 double x, rounded;
1021 PyObject *o_ndigits = NULL;
1022 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 x = PyFloat_AsDouble(v);
1025 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1026 return NULL;
1027 if (o_ndigits == NULL) {
1028 /* single-argument round: round to nearest integer */
1029 rounded = round(x);
1030 if (fabs(x-rounded) == 0.5)
1031 /* halfway case: round to even */
1032 rounded = 2.0*round(x/2.0);
1033 return PyLong_FromDouble(rounded);
1034 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* interpret second argument as a Py_ssize_t; clips on overflow */
1037 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1038 if (ndigits == -1 && PyErr_Occurred())
1039 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* nans and infinities round to themselves */
1042 if (!Py_IS_FINITE(x))
1043 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1046 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1047 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001048#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1049#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (ndigits > NDIGITS_MAX)
1051 /* return x */
1052 return PyFloat_FromDouble(x);
1053 else if (ndigits < NDIGITS_MIN)
1054 /* return 0.0, but with sign of x */
1055 return PyFloat_FromDouble(0.0*x);
1056 else
1057 /* finite x, and ndigits is not unreasonably large */
1058 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001059#undef NDIGITS_MAX
1060#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001061}
1062
1063static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001064float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (PyFloat_CheckExact(v))
1067 Py_INCREF(v);
1068 else
1069 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1070 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001071}
1072
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001073/* turn ASCII hex characters into integer values and vice versa */
1074
1075static char
1076char_from_hex(int x)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 assert(0 <= x && x < 16);
1079 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001080}
1081
1082static int
1083hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 int x;
1085 switch(c) {
1086 case '0':
1087 x = 0;
1088 break;
1089 case '1':
1090 x = 1;
1091 break;
1092 case '2':
1093 x = 2;
1094 break;
1095 case '3':
1096 x = 3;
1097 break;
1098 case '4':
1099 x = 4;
1100 break;
1101 case '5':
1102 x = 5;
1103 break;
1104 case '6':
1105 x = 6;
1106 break;
1107 case '7':
1108 x = 7;
1109 break;
1110 case '8':
1111 x = 8;
1112 break;
1113 case '9':
1114 x = 9;
1115 break;
1116 case 'a':
1117 case 'A':
1118 x = 10;
1119 break;
1120 case 'b':
1121 case 'B':
1122 x = 11;
1123 break;
1124 case 'c':
1125 case 'C':
1126 x = 12;
1127 break;
1128 case 'd':
1129 case 'D':
1130 x = 13;
1131 break;
1132 case 'e':
1133 case 'E':
1134 x = 14;
1135 break;
1136 case 'f':
1137 case 'F':
1138 x = 15;
1139 break;
1140 default:
1141 x = -1;
1142 break;
1143 }
1144 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001145}
1146
1147/* convert a float to a hexadecimal string */
1148
1149/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1150 of the form 4k+1. */
1151#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1152
1153static PyObject *
1154float_hex(PyObject *v)
1155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 double x, m;
1157 int e, shift, i, si, esign;
1158 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1159 trailing NUL byte. */
1160 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001165 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001168 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return PyUnicode_FromString("-0x0.0p+0");
1170 else
1171 return PyUnicode_FromString("0x0.0p+0");
1172 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 m = frexp(fabs(x), &e);
1175 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1176 m = ldexp(m, shift);
1177 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 si = 0;
1180 s[si] = char_from_hex((int)m);
1181 si++;
1182 m -= (int)m;
1183 s[si] = '.';
1184 si++;
1185 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1186 m *= 16.0;
1187 s[si] = char_from_hex((int)m);
1188 si++;
1189 m -= (int)m;
1190 }
1191 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (e < 0) {
1194 esign = (int)'-';
1195 e = -e;
1196 }
1197 else
1198 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (x < 0.0)
1201 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1202 else
1203 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204}
1205
1206PyDoc_STRVAR(float_hex_doc,
1207"float.hex() -> string\n\
1208\n\
1209Return a hexadecimal representation of a floating-point number.\n\
1210>>> (-0.1).hex()\n\
1211'-0x1.999999999999ap-4'\n\
1212>>> 3.14159.hex()\n\
1213'0x1.921f9f01b866ep+1'");
1214
1215/* Convert a hexadecimal string to a float. */
1216
1217static PyObject *
1218float_fromhex(PyObject *cls, PyObject *arg)
1219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyObject *result_as_float, *result;
1221 double x;
1222 long exp, top_exp, lsb, key_digit;
1223 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1224 int half_eps, digit, round_up, negate=0;
1225 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 /*
1228 * For the sake of simplicity and correctness, we impose an artificial
1229 * limit on ndigits, the total number of hex digits in the coefficient
1230 * The limit is chosen to ensure that, writing exp for the exponent,
1231 *
1232 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1233 * guaranteed to overflow (provided it's nonzero)
1234 *
1235 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1236 * guaranteed to underflow to 0.
1237 *
1238 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1239 * overflow in the calculation of exp and top_exp below.
1240 *
1241 * More specifically, ndigits is assumed to satisfy the following
1242 * inequalities:
1243 *
1244 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1245 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1246 *
1247 * If either of these inequalities is not satisfied, a ValueError is
1248 * raised. Otherwise, write x for the value of the hex string, and
1249 * assume x is nonzero. Then
1250 *
1251 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1252 *
1253 * Now if exp > LONG_MAX/2 then:
1254 *
1255 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1256 * = DBL_MAX_EXP
1257 *
1258 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1259 * double, so overflows. If exp < LONG_MIN/2, then
1260 *
1261 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1262 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1263 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1264 *
1265 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1266 * when converted to a C double.
1267 *
1268 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1269 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1270 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 s = _PyUnicode_AsStringAndSize(arg, &length);
1273 if (s == NULL)
1274 return NULL;
1275 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 /********************
1278 * Parse the string *
1279 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 /* leading whitespace */
1282 while (Py_ISSPACE(*s))
1283 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 /* infinities and nans */
1286 x = _Py_parse_inf_or_nan(s, &coeff_end);
1287 if (coeff_end != s) {
1288 s = coeff_end;
1289 goto finished;
1290 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* optional sign */
1293 if (*s == '-') {
1294 s++;
1295 negate = 1;
1296 }
1297 else if (*s == '+')
1298 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 /* [0x] */
1301 s_store = s;
1302 if (*s == '0') {
1303 s++;
1304 if (*s == 'x' || *s == 'X')
1305 s++;
1306 else
1307 s = s_store;
1308 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 /* coefficient: <integer> [. <fraction>] */
1311 coeff_start = s;
1312 while (hex_from_char(*s) >= 0)
1313 s++;
1314 s_store = s;
1315 if (*s == '.') {
1316 s++;
1317 while (hex_from_char(*s) >= 0)
1318 s++;
1319 coeff_end = s-1;
1320 }
1321 else
1322 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /* ndigits = total # of hex digits; fdigits = # after point */
1325 ndigits = coeff_end - coeff_start;
1326 fdigits = coeff_end - s_store;
1327 if (ndigits == 0)
1328 goto parse_error;
1329 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1330 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1331 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 /* [p <exponent>] */
1334 if (*s == 'p' || *s == 'P') {
1335 s++;
1336 exp_start = s;
1337 if (*s == '-' || *s == '+')
1338 s++;
1339 if (!('0' <= *s && *s <= '9'))
1340 goto parse_error;
1341 s++;
1342 while ('0' <= *s && *s <= '9')
1343 s++;
1344 exp = strtol(exp_start, NULL, 10);
1345 }
1346 else
1347 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1351 coeff_end-(j) : \
1352 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 /*******************************************
1355 * Compute rounded value of the hex string *
1356 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* Discard leading zeros, and catch extreme overflow and underflow */
1359 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1360 ndigits--;
1361 if (ndigits == 0 || exp < LONG_MIN/2) {
1362 x = 0.0;
1363 goto finished;
1364 }
1365 if (exp > LONG_MAX/2)
1366 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* Adjust exponent for fractional part. */
1369 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1372 top_exp = exp + 4*((long)ndigits - 1);
1373 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1374 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* catch almost all nonextreme cases of overflow and underflow here */
1377 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1378 x = 0.0;
1379 goto finished;
1380 }
1381 if (top_exp > DBL_MAX_EXP)
1382 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* lsb = exponent of least significant bit of the *rounded* value.
1385 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1386 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 x = 0.0;
1389 if (exp >= lsb) {
1390 /* no rounding required */
1391 for (i = ndigits-1; i >= 0; i--)
1392 x = 16.0*x + HEX_DIGIT(i);
1393 x = ldexp(x, (int)(exp));
1394 goto finished;
1395 }
1396 /* rounding required. key_digit is the index of the hex digit
1397 containing the first bit to be rounded away. */
1398 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1399 key_digit = (lsb - exp - 1) / 4;
1400 for (i = ndigits-1; i > key_digit; i--)
1401 x = 16.0*x + HEX_DIGIT(i);
1402 digit = HEX_DIGIT(key_digit);
1403 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1406 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1407 if ((digit & half_eps) != 0) {
1408 round_up = 0;
1409 if ((digit & (3*half_eps-1)) != 0 ||
1410 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1411 round_up = 1;
1412 else
1413 for (i = key_digit-1; i >= 0; i--)
1414 if (HEX_DIGIT(i) != 0) {
1415 round_up = 1;
1416 break;
1417 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001418 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 x += 2*half_eps;
1420 if (top_exp == DBL_MAX_EXP &&
1421 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1422 /* overflow corner case: pre-rounded value <
1423 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1424 goto overflow_error;
1425 }
1426 }
1427 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001428
1429 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 /* optional trailing whitespace leading to the end of the string */
1431 while (Py_ISSPACE(*s))
1432 s++;
1433 if (s != s_end)
1434 goto parse_error;
1435 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1436 if (result_as_float == NULL)
1437 return NULL;
1438 result = PyObject_CallObject(cls, result_as_float);
1439 Py_DECREF(result_as_float);
1440 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001441
1442 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyErr_SetString(PyExc_OverflowError,
1444 "hexadecimal value too large to represent as a float");
1445 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001446
1447 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyErr_SetString(PyExc_ValueError,
1449 "invalid hexadecimal floating-point string");
1450 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001451
1452 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyErr_SetString(PyExc_ValueError,
1454 "hexadecimal string too long to convert");
1455 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001456}
1457
1458PyDoc_STRVAR(float_fromhex_doc,
1459"float.fromhex(string) -> float\n\
1460\n\
1461Create a floating-point number from a hexadecimal string.\n\
1462>>> float.fromhex('0x1.ffffp10')\n\
14632047.984375\n\
1464>>> float.fromhex('-0x1p-1074')\n\
1465-4.9406564584124654e-324");
1466
1467
Christian Heimes26855632008-01-27 23:50:43 +00001468static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001469float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 double self;
1472 double float_part;
1473 int exponent;
1474 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 PyObject *prev;
1477 PyObject *py_exponent = NULL;
1478 PyObject *numerator = NULL;
1479 PyObject *denominator = NULL;
1480 PyObject *result_pair = NULL;
1481 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001482
1483#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 prev = obj; \
1485 obj = call; \
1486 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (Py_IS_INFINITY(self)) {
1491 PyErr_SetString(PyExc_OverflowError,
1492 "Cannot pass infinity to float.as_integer_ratio.");
1493 return NULL;
1494 }
Christian Heimes26855632008-01-27 23:50:43 +00001495#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (Py_IS_NAN(self)) {
1497 PyErr_SetString(PyExc_ValueError,
1498 "Cannot pass NaN to float.as_integer_ratio.");
1499 return NULL;
1500 }
Christian Heimes26855632008-01-27 23:50:43 +00001501#endif
1502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1504 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1505 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1508 float_part *= 2.0;
1509 exponent--;
1510 }
1511 /* self == float_part * 2**exponent exactly and float_part is integral.
1512 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1513 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 numerator = PyLong_FromDouble(float_part);
1516 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 /* fold in 2**exponent */
1519 denominator = PyLong_FromLong(1);
1520 py_exponent = PyLong_FromLong(labs((long)exponent));
1521 if (py_exponent == NULL) goto error;
1522 INPLACE_UPDATE(py_exponent,
1523 long_methods->nb_lshift(denominator, py_exponent));
1524 if (py_exponent == NULL) goto error;
1525 if (exponent > 0) {
1526 INPLACE_UPDATE(numerator,
1527 long_methods->nb_multiply(numerator, py_exponent));
1528 if (numerator == NULL) goto error;
1529 }
1530 else {
1531 Py_DECREF(denominator);
1532 denominator = py_exponent;
1533 py_exponent = NULL;
1534 }
1535
1536 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001537
1538#undef INPLACE_UPDATE
1539error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 Py_XDECREF(py_exponent);
1541 Py_XDECREF(denominator);
1542 Py_XDECREF(numerator);
1543 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001544}
1545
1546PyDoc_STRVAR(float_as_integer_ratio_doc,
1547"float.as_integer_ratio() -> (int, int)\n"
1548"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001549"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1550"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001551"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001552"\n"
1553">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001554"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001555">>> (0.0).as_integer_ratio()\n"
1556"(0, 1)\n"
1557">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001558"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001559
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001560
Jeremy Hylton938ace62002-07-17 16:30:39 +00001561static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001562float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1563
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564static PyObject *
1565float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyObject *x = Py_False; /* Integer zero */
1568 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (type != &PyFloat_Type)
1571 return float_subtype_new(type, args, kwds); /* Wimp out */
1572 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1573 return NULL;
1574 /* If it's a string, but not a string subclass, use
1575 PyFloat_FromString. */
1576 if (PyUnicode_CheckExact(x))
1577 return PyFloat_FromString(x);
1578 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579}
1580
Guido van Rossumbef14172001-08-29 15:47:46 +00001581/* Wimpy, slow approach to tp_new calls for subtypes of float:
1582 first create a regular float from whatever arguments we got,
1583 then allocate a subtype instance and initialize its ob_fval
1584 from the regular float. The regular float is then thrown away.
1585*/
1586static PyObject *
1587float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 assert(PyType_IsSubtype(type, &PyFloat_Type));
1592 tmp = float_new(&PyFloat_Type, args, kwds);
1593 if (tmp == NULL)
1594 return NULL;
1595 assert(PyFloat_CheckExact(tmp));
1596 newobj = type->tp_alloc(type, 0);
1597 if (newobj == NULL) {
1598 Py_DECREF(tmp);
1599 return NULL;
1600 }
1601 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1602 Py_DECREF(tmp);
1603 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001604}
1605
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001606static PyObject *
1607float_getnewargs(PyFloatObject *v)
1608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001610}
1611
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001612/* this is for the benefit of the pack/unpack routines below */
1613
1614typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001616} float_format_type;
1617
1618static float_format_type double_format, float_format;
1619static float_format_type detected_double_format, detected_float_format;
1620
1621static PyObject *
1622float_getformat(PyTypeObject *v, PyObject* arg)
1623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 char* s;
1625 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (!PyUnicode_Check(arg)) {
1628 PyErr_Format(PyExc_TypeError,
1629 "__getformat__() argument must be string, not %.500s",
1630 Py_TYPE(arg)->tp_name);
1631 return NULL;
1632 }
1633 s = _PyUnicode_AsString(arg);
1634 if (s == NULL)
1635 return NULL;
1636 if (strcmp(s, "double") == 0) {
1637 r = double_format;
1638 }
1639 else if (strcmp(s, "float") == 0) {
1640 r = float_format;
1641 }
1642 else {
1643 PyErr_SetString(PyExc_ValueError,
1644 "__getformat__() argument 1 must be "
1645 "'double' or 'float'");
1646 return NULL;
1647 }
1648
1649 switch (r) {
1650 case unknown_format:
1651 return PyUnicode_FromString("unknown");
1652 case ieee_little_endian_format:
1653 return PyUnicode_FromString("IEEE, little-endian");
1654 case ieee_big_endian_format:
1655 return PyUnicode_FromString("IEEE, big-endian");
1656 default:
1657 Py_FatalError("insane float_format or double_format");
1658 return NULL;
1659 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001660}
1661
1662PyDoc_STRVAR(float_getformat_doc,
1663"float.__getformat__(typestr) -> string\n"
1664"\n"
1665"You probably don't want to use this function. It exists mainly to be\n"
1666"used in Python's test suite.\n"
1667"\n"
1668"typestr must be 'double' or 'float'. This function returns whichever of\n"
1669"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1670"format of floating point numbers used by the C type named by typestr.");
1671
1672static PyObject *
1673float_setformat(PyTypeObject *v, PyObject* args)
1674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 char* typestr;
1676 char* format;
1677 float_format_type f;
1678 float_format_type detected;
1679 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1682 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (strcmp(typestr, "double") == 0) {
1685 p = &double_format;
1686 detected = detected_double_format;
1687 }
1688 else if (strcmp(typestr, "float") == 0) {
1689 p = &float_format;
1690 detected = detected_float_format;
1691 }
1692 else {
1693 PyErr_SetString(PyExc_ValueError,
1694 "__setformat__() argument 1 must "
1695 "be 'double' or 'float'");
1696 return NULL;
1697 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (strcmp(format, "unknown") == 0) {
1700 f = unknown_format;
1701 }
1702 else if (strcmp(format, "IEEE, little-endian") == 0) {
1703 f = ieee_little_endian_format;
1704 }
1705 else if (strcmp(format, "IEEE, big-endian") == 0) {
1706 f = ieee_big_endian_format;
1707 }
1708 else {
1709 PyErr_SetString(PyExc_ValueError,
1710 "__setformat__() argument 2 must be "
1711 "'unknown', 'IEEE, little-endian' or "
1712 "'IEEE, big-endian'");
1713 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (f != unknown_format && f != detected) {
1718 PyErr_Format(PyExc_ValueError,
1719 "can only set %s format to 'unknown' or the "
1720 "detected platform value", typestr);
1721 return NULL;
1722 }
1723
1724 *p = f;
1725 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001726}
1727
1728PyDoc_STRVAR(float_setformat_doc,
1729"float.__setformat__(typestr, fmt) -> None\n"
1730"\n"
1731"You probably don't want to use this function. It exists mainly to be\n"
1732"used in Python's test suite.\n"
1733"\n"
1734"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1735"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1736"one of the latter two if it appears to match the underlying C reality.\n"
1737"\n"
1738"Overrides the automatic determination of C-level floating point type.\n"
1739"This affects how floats are converted to and from binary strings.");
1740
Guido van Rossumb43daf72007-08-01 18:08:08 +00001741static PyObject *
1742float_getzero(PyObject *v, void *closure)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001745}
1746
Eric Smith8c663262007-08-25 02:26:07 +00001747static PyObject *
1748float__format__(PyObject *self, PyObject *args)
1749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1753 return NULL;
1754 return _PyFloat_FormatAdvanced(self,
1755 PyUnicode_AS_UNICODE(format_spec),
1756 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001757}
1758
1759PyDoc_STRVAR(float__format__doc,
1760"float.__format__(format_spec) -> string\n"
1761"\n"
1762"Formats the float according to format_spec.");
1763
1764
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001765static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1767 "Returns self, the complex conjugate of any float."},
1768 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1769 "Returns the Integral closest to x between 0 and x."},
1770 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1771 "Returns the Integral closest to x, rounding half toward even.\n"
1772 "When an argument is passed, works like built-in round(x, ndigits)."},
1773 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1774 float_as_integer_ratio_doc},
1775 {"fromhex", (PyCFunction)float_fromhex,
1776 METH_O|METH_CLASS, float_fromhex_doc},
1777 {"hex", (PyCFunction)float_hex,
1778 METH_NOARGS, float_hex_doc},
1779 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1780 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001781#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1783 "Returns True if the float is positive or negative infinite."},
1784 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1785 "Returns True if the float is finite, neither infinite nor NaN."},
1786 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1787 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001788#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1790 {"__getformat__", (PyCFunction)float_getformat,
1791 METH_O|METH_CLASS, float_getformat_doc},
1792 {"__setformat__", (PyCFunction)float_setformat,
1793 METH_VARARGS|METH_CLASS, float_setformat_doc},
1794 {"__format__", (PyCFunction)float__format__,
1795 METH_VARARGS, float__format__doc},
1796 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001797};
1798
Guido van Rossumb43daf72007-08-01 18:08:08 +00001799static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001801 (getter)float_float, (setter)NULL,
1802 "the real part of a complex number",
1803 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001805 (getter)float_getzero, (setter)NULL,
1806 "the imaginary part of a complex number",
1807 NULL},
1808 {NULL} /* Sentinel */
1809};
1810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001811PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812"float(x) -> floating point number\n\
1813\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001814Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815
1816
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001817static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 float_add, /*nb_add*/
1819 float_sub, /*nb_subtract*/
1820 float_mul, /*nb_multiply*/
1821 float_rem, /*nb_remainder*/
1822 float_divmod, /*nb_divmod*/
1823 float_pow, /*nb_power*/
1824 (unaryfunc)float_neg, /*nb_negative*/
1825 (unaryfunc)float_float, /*nb_positive*/
1826 (unaryfunc)float_abs, /*nb_absolute*/
1827 (inquiry)float_bool, /*nb_bool*/
1828 0, /*nb_invert*/
1829 0, /*nb_lshift*/
1830 0, /*nb_rshift*/
1831 0, /*nb_and*/
1832 0, /*nb_xor*/
1833 0, /*nb_or*/
1834 float_trunc, /*nb_int*/
1835 0, /*nb_reserved*/
1836 float_float, /*nb_float*/
1837 0, /* nb_inplace_add */
1838 0, /* nb_inplace_subtract */
1839 0, /* nb_inplace_multiply */
1840 0, /* nb_inplace_remainder */
1841 0, /* nb_inplace_power */
1842 0, /* nb_inplace_lshift */
1843 0, /* nb_inplace_rshift */
1844 0, /* nb_inplace_and */
1845 0, /* nb_inplace_xor */
1846 0, /* nb_inplace_or */
1847 float_floor_div, /* nb_floor_divide */
1848 float_div, /* nb_true_divide */
1849 0, /* nb_inplace_floor_divide */
1850 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851};
1852
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001853PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1855 "float",
1856 sizeof(PyFloatObject),
1857 0,
1858 (destructor)float_dealloc, /* tp_dealloc */
1859 0, /* tp_print */
1860 0, /* tp_getattr */
1861 0, /* tp_setattr */
1862 0, /* tp_reserved */
1863 (reprfunc)float_repr, /* tp_repr */
1864 &float_as_number, /* tp_as_number */
1865 0, /* tp_as_sequence */
1866 0, /* tp_as_mapping */
1867 (hashfunc)float_hash, /* tp_hash */
1868 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001869 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject_GenericGetAttr, /* tp_getattro */
1871 0, /* tp_setattro */
1872 0, /* tp_as_buffer */
1873 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1874 float_doc, /* tp_doc */
1875 0, /* tp_traverse */
1876 0, /* tp_clear */
1877 float_richcompare, /* tp_richcompare */
1878 0, /* tp_weaklistoffset */
1879 0, /* tp_iter */
1880 0, /* tp_iternext */
1881 float_methods, /* tp_methods */
1882 0, /* tp_members */
1883 float_getset, /* tp_getset */
1884 0, /* tp_base */
1885 0, /* tp_dict */
1886 0, /* tp_descr_get */
1887 0, /* tp_descr_set */
1888 0, /* tp_dictoffset */
1889 0, /* tp_init */
1890 0, /* tp_alloc */
1891 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001893
1894void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001895_PyFloat_Init(void)
1896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 /* We attempt to determine if this machine is using IEEE
1898 floating point formats by peering at the bits of some
1899 carefully chosen values. If it looks like we are on an
1900 IEEE platform, the float packing/unpacking routines can
1901 just copy bits, if not they resort to arithmetic & shifts
1902 and masks. The shifts & masks approach works on all finite
1903 values, but what happens to infinities, NaNs and signed
1904 zeroes on packing is an accident, and attempting to unpack
1905 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 Note that if we're on some whacked-out platform which uses
1908 IEEE formats but isn't strictly little-endian or big-
1909 endian, we will fall back to the portable shifts & masks
1910 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001911
1912#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 {
1914 double x = 9006104071832581.0;
1915 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1916 detected_double_format = ieee_big_endian_format;
1917 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1918 detected_double_format = ieee_little_endian_format;
1919 else
1920 detected_double_format = unknown_format;
1921 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001922#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924#endif
1925
1926#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 {
1928 float y = 16711938.0;
1929 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1930 detected_float_format = ieee_big_endian_format;
1931 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1932 detected_float_format = ieee_little_endian_format;
1933 else
1934 detected_float_format = unknown_format;
1935 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001938#endif
1939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 double_format = detected_double_format;
1941 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* Init float info */
1944 if (FloatInfoType.tp_name == 0)
1945 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001946}
1947
Georg Brandl2ee470f2008-07-16 12:55:28 +00001948int
1949PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 PyFloatObject *p;
1952 PyFloatBlock *list, *next;
1953 int i;
1954 int u; /* remaining unfreed floats per block */
1955 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 list = block_list;
1958 block_list = NULL;
1959 free_list = NULL;
1960 while (list != NULL) {
1961 u = 0;
1962 for (i = 0, p = &list->objects[0];
1963 i < N_FLOATOBJECTS;
1964 i++, p++) {
1965 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1966 u++;
1967 }
1968 next = list->next;
1969 if (u) {
1970 list->next = block_list;
1971 block_list = list;
1972 for (i = 0, p = &list->objects[0];
1973 i < N_FLOATOBJECTS;
1974 i++, p++) {
1975 if (!PyFloat_CheckExact(p) ||
1976 Py_REFCNT(p) == 0) {
1977 Py_TYPE(p) = (struct _typeobject *)
1978 free_list;
1979 free_list = p;
1980 }
1981 }
1982 }
1983 else {
1984 PyMem_FREE(list);
1985 }
1986 freelist_size += u;
1987 list = next;
1988 }
1989 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001990}
1991
1992void
1993PyFloat_Fini(void)
1994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 PyFloatObject *p;
1996 PyFloatBlock *list;
1997 int i;
1998 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (!Py_VerboseFlag)
2003 return;
2004 fprintf(stderr, "# cleanup floats");
2005 if (!u) {
2006 fprintf(stderr, "\n");
2007 }
2008 else {
2009 fprintf(stderr,
2010 ": %d unfreed float%s\n",
2011 u, u == 1 ? "" : "s");
2012 }
2013 if (Py_VerboseFlag > 1) {
2014 list = block_list;
2015 while (list != NULL) {
2016 for (i = 0, p = &list->objects[0];
2017 i < N_FLOATOBJECTS;
2018 i++, p++) {
2019 if (PyFloat_CheckExact(p) &&
2020 Py_REFCNT(p) != 0) {
2021 char *buf = PyOS_double_to_string(
2022 PyFloat_AS_DOUBLE(p), 'r',
2023 0, 0, NULL);
2024 if (buf) {
2025 /* XXX(twouters) cast
2026 refcount to long
2027 until %zd is
2028 universally
2029 available
2030 */
2031 fprintf(stderr,
2032 "# <float at %p, refcnt=%ld, val=%s>\n",
2033 p, (long)Py_REFCNT(p), buf);
2034 PyMem_Free(buf);
2035 }
2036 }
2037 }
2038 list = list->next;
2039 }
2040 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002041}
Tim Peters9905b942003-03-20 20:53:32 +00002042
2043/*----------------------------------------------------------------------------
2044 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002045 */
2046int
2047_PyFloat_Pack4(double x, unsigned char *p, int le)
2048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (float_format == unknown_format) {
2050 unsigned char sign;
2051 int e;
2052 double f;
2053 unsigned int fbits;
2054 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (le) {
2057 p += 3;
2058 incr = -1;
2059 }
Tim Peters9905b942003-03-20 20:53:32 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (x < 0) {
2062 sign = 1;
2063 x = -x;
2064 }
2065 else
2066 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* Normalize f to be in the range [1.0, 2.0) */
2071 if (0.5 <= f && f < 1.0) {
2072 f *= 2.0;
2073 e--;
2074 }
2075 else if (f == 0.0)
2076 e = 0;
2077 else {
2078 PyErr_SetString(PyExc_SystemError,
2079 "frexp() result out of range");
2080 return -1;
2081 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (e >= 128)
2084 goto Overflow;
2085 else if (e < -126) {
2086 /* Gradual underflow */
2087 f = ldexp(f, 126 + e);
2088 e = 0;
2089 }
2090 else if (!(e == 0 && f == 0.0)) {
2091 e += 127;
2092 f -= 1.0; /* Get rid of leading 1 */
2093 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 f *= 8388608.0; /* 2**23 */
2096 fbits = (unsigned int)(f + 0.5); /* Round */
2097 assert(fbits <= 8388608);
2098 if (fbits >> 23) {
2099 /* The carry propagated out of a string of 23 1 bits. */
2100 fbits = 0;
2101 ++e;
2102 if (e >= 255)
2103 goto Overflow;
2104 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* First byte */
2107 *p = (sign << 7) | (e >> 1);
2108 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* Second byte */
2111 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2112 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Third byte */
2115 *p = (fbits >> 8) & 0xFF;
2116 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* Fourth byte */
2119 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* Done */
2122 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 }
2125 else {
2126 float y = (float)x;
2127 const char *s = (char*)&y;
2128 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2131 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if ((float_format == ieee_little_endian_format && !le)
2134 || (float_format == ieee_big_endian_format && le)) {
2135 p += 3;
2136 incr = -1;
2137 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 for (i = 0; i < 4; i++) {
2140 *p = *s++;
2141 p += incr;
2142 }
2143 return 0;
2144 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002145 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyErr_SetString(PyExc_OverflowError,
2147 "float too large to pack with f format");
2148 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002149}
2150
2151int
2152_PyFloat_Pack8(double x, unsigned char *p, int le)
2153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 if (double_format == unknown_format) {
2155 unsigned char sign;
2156 int e;
2157 double f;
2158 unsigned int fhi, flo;
2159 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (le) {
2162 p += 7;
2163 incr = -1;
2164 }
Tim Peters9905b942003-03-20 20:53:32 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (x < 0) {
2167 sign = 1;
2168 x = -x;
2169 }
2170 else
2171 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* Normalize f to be in the range [1.0, 2.0) */
2176 if (0.5 <= f && f < 1.0) {
2177 f *= 2.0;
2178 e--;
2179 }
2180 else if (f == 0.0)
2181 e = 0;
2182 else {
2183 PyErr_SetString(PyExc_SystemError,
2184 "frexp() result out of range");
2185 return -1;
2186 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (e >= 1024)
2189 goto Overflow;
2190 else if (e < -1022) {
2191 /* Gradual underflow */
2192 f = ldexp(f, 1022 + e);
2193 e = 0;
2194 }
2195 else if (!(e == 0 && f == 0.0)) {
2196 e += 1023;
2197 f -= 1.0; /* Get rid of leading 1 */
2198 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2201 f *= 268435456.0; /* 2**28 */
2202 fhi = (unsigned int)f; /* Truncate */
2203 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 f -= (double)fhi;
2206 f *= 16777216.0; /* 2**24 */
2207 flo = (unsigned int)(f + 0.5); /* Round */
2208 assert(flo <= 16777216);
2209 if (flo >> 24) {
2210 /* The carry propagated out of a string of 24 1 bits. */
2211 flo = 0;
2212 ++fhi;
2213 if (fhi >> 28) {
2214 /* And it also progagated out of the next 28 bits. */
2215 fhi = 0;
2216 ++e;
2217 if (e >= 2047)
2218 goto Overflow;
2219 }
2220 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* First byte */
2223 *p = (sign << 7) | (e >> 4);
2224 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Second byte */
2227 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2228 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Third byte */
2231 *p = (fhi >> 16) & 0xFF;
2232 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Fourth byte */
2235 *p = (fhi >> 8) & 0xFF;
2236 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Fifth byte */
2239 *p = fhi & 0xFF;
2240 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Sixth byte */
2243 *p = (flo >> 16) & 0xFF;
2244 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Seventh byte */
2247 *p = (flo >> 8) & 0xFF;
2248 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* Eighth byte */
2251 *p = flo & 0xFF;
2252 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* Done */
2255 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 Overflow:
2258 PyErr_SetString(PyExc_OverflowError,
2259 "float too large to pack with d format");
2260 return -1;
2261 }
2262 else {
2263 const char *s = (char*)&x;
2264 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if ((double_format == ieee_little_endian_format && !le)
2267 || (double_format == ieee_big_endian_format && le)) {
2268 p += 7;
2269 incr = -1;
2270 }
2271
2272 for (i = 0; i < 8; i++) {
2273 *p = *s++;
2274 p += incr;
2275 }
2276 return 0;
2277 }
Tim Peters9905b942003-03-20 20:53:32 +00002278}
2279
2280double
2281_PyFloat_Unpack4(const unsigned char *p, int le)
2282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 if (float_format == unknown_format) {
2284 unsigned char sign;
2285 int e;
2286 unsigned int f;
2287 double x;
2288 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 if (le) {
2291 p += 3;
2292 incr = -1;
2293 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* First byte */
2296 sign = (*p >> 7) & 1;
2297 e = (*p & 0x7F) << 1;
2298 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Second byte */
2301 e |= (*p >> 7) & 1;
2302 f = (*p & 0x7F) << 16;
2303 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 if (e == 255) {
2306 PyErr_SetString(
2307 PyExc_ValueError,
2308 "can't unpack IEEE 754 special value "
2309 "on non-IEEE platform");
2310 return -1;
2311 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Third byte */
2314 f |= *p << 8;
2315 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Fourth byte */
2318 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* XXX This sadly ignores Inf/NaN issues */
2323 if (e == 0)
2324 e = -126;
2325 else {
2326 x += 1.0;
2327 e -= 127;
2328 }
2329 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (sign)
2332 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return x;
2335 }
2336 else {
2337 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 if ((float_format == ieee_little_endian_format && !le)
2340 || (float_format == ieee_big_endian_format && le)) {
2341 char buf[4];
2342 char *d = &buf[3];
2343 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 for (i = 0; i < 4; i++) {
2346 *d-- = *p++;
2347 }
2348 memcpy(&x, buf, 4);
2349 }
2350 else {
2351 memcpy(&x, p, 4);
2352 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 return x;
2355 }
Tim Peters9905b942003-03-20 20:53:32 +00002356}
2357
2358double
2359_PyFloat_Unpack8(const unsigned char *p, int le)
2360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 if (double_format == unknown_format) {
2362 unsigned char sign;
2363 int e;
2364 unsigned int fhi, flo;
2365 double x;
2366 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (le) {
2369 p += 7;
2370 incr = -1;
2371 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* First byte */
2374 sign = (*p >> 7) & 1;
2375 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* Second byte */
2380 e |= (*p >> 4) & 0xF;
2381 fhi = (*p & 0xF) << 24;
2382 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (e == 2047) {
2385 PyErr_SetString(
2386 PyExc_ValueError,
2387 "can't unpack IEEE 754 special value "
2388 "on non-IEEE platform");
2389 return -1.0;
2390 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Third byte */
2393 fhi |= *p << 16;
2394 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* Fourth byte */
2397 fhi |= *p << 8;
2398 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Fifth byte */
2401 fhi |= *p;
2402 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* Sixth byte */
2405 flo = *p << 16;
2406 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* Seventh byte */
2409 flo |= *p << 8;
2410 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 /* Eighth byte */
2413 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2416 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (e == 0)
2419 e = -1022;
2420 else {
2421 x += 1.0;
2422 e -= 1023;
2423 }
2424 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 if (sign)
2427 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return x;
2430 }
2431 else {
2432 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if ((double_format == ieee_little_endian_format && !le)
2435 || (double_format == ieee_big_endian_format && le)) {
2436 char buf[8];
2437 char *d = &buf[7];
2438 int i;
2439
2440 for (i = 0; i < 8; i++) {
2441 *d-- = *p++;
2442 }
2443 memcpy(&x, buf, 8);
2444 }
2445 else {
2446 memcpy(&x, p, 8);
2447 }
2448
2449 return x;
2450 }
Tim Peters9905b942003-03-20 20:53:32 +00002451}