blob: 09c0e961ba54bdc863f3adfaba0896c8e4121ef8 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Mark Dickinson65fe25e2008-07-16 11:30:51 +000012#undef MAX
13#undef MIN
14#define MAX(x, y) ((x) < (y) ? (y) : (x))
15#define MIN(x, y) ((x) < (y) ? (x) : (y))
16
Guido van Rossum6923e131990-11-02 17:50:43 +000017
Christian Heimes969fe572008-01-25 11:23:10 +000018#ifdef _OSF_SOURCE
19/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20extern int finite(double);
21#endif
22
Mark Dickinsond19052c2010-06-27 18:19:09 +000023/* Special free list
24
25 Since some Python programs can spend much of their time allocating
26 and deallocating floats, these operations should be very fast.
27 Therefore we use a dedicated allocation scheme with a much lower
28 overhead (in space and time) than straight malloc(): a simple
29 dedicated free list, filled when necessary with memory from malloc().
30
31 block_list is a singly-linked list of all PyFloatBlocks ever allocated,
32 linked via their next members. PyFloatBlocks are never returned to the
33 system before shutdown (PyFloat_Fini).
34
35 free_list is a singly-linked list of available PyFloatObjects, linked
36 via abuse of their ob_type members.
37*/
38
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
40#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
41#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000042
Guido van Rossum3fce8831999-03-12 19:43:17 +000043struct _floatblock {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 struct _floatblock *next;
45 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000046};
47
48typedef struct _floatblock PyFloatBlock;
49
50static PyFloatBlock *block_list = NULL;
51static PyFloatObject *free_list = NULL;
52
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000054fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyFloatObject *p, *q;
57 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
58 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
59 if (p == NULL)
60 return (PyFloatObject *) PyErr_NoMemory();
61 ((PyFloatBlock *)p)->next = block_list;
62 block_list = (PyFloatBlock *)p;
63 p = &((PyFloatBlock *)p)->objects[0];
64 q = p + N_FLOATOBJECTS;
65 while (--q > p)
66 Py_TYPE(q) = (struct _typeobject *)(q-1);
67 Py_TYPE(q) = NULL;
68 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000069}
70
Christian Heimes93852662007-12-01 12:22:32 +000071double
72PyFloat_GetMax(void)
73{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000075}
76
77double
78PyFloat_GetMin(void)
79{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000081}
82
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083static PyTypeObject FloatInfoType;
84
85PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000086"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000087\n\
88A structseq holding information about the float type. It contains low level\n\
89information about the precision and internal representation. Please study\n\
90your system's :file:`float.h` for more information.");
91
92static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 {"max", "DBL_MAX -- maximum representable finite float"},
94 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
95 "is representable"},
96 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
97 "is representable"},
98 {"min", "DBL_MIN -- Minimum positive normalizer float"},
99 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
100 "is a normalized float"},
101 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
102 "a normalized"},
103 {"dig", "DBL_DIG -- digits"},
104 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
105 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
106 "representable float"},
107 {"radix", "FLT_RADIX -- radix of exponent"},
108 {"rounds", "FLT_ROUNDS -- addition rounds"},
109 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000110};
111
112static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 "sys.float_info", /* name */
114 floatinfo__doc__, /* doc */
115 floatinfo_fields, /* fields */
116 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000117};
118
Christian Heimes93852662007-12-01 12:22:32 +0000119PyObject *
120PyFloat_GetInfo(void)
121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject* floatinfo;
123 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 floatinfo = PyStructSequence_New(&FloatInfoType);
126 if (floatinfo == NULL) {
127 return NULL;
128 }
Christian Heimes93852662007-12-01 12:22:32 +0000129
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000130#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000132#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 SetDblFlag(DBL_MAX);
136 SetIntFlag(DBL_MAX_EXP);
137 SetIntFlag(DBL_MAX_10_EXP);
138 SetDblFlag(DBL_MIN);
139 SetIntFlag(DBL_MIN_EXP);
140 SetIntFlag(DBL_MIN_10_EXP);
141 SetIntFlag(DBL_DIG);
142 SetIntFlag(DBL_MANT_DIG);
143 SetDblFlag(DBL_EPSILON);
144 SetIntFlag(FLT_RADIX);
145 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000146#undef SetIntFlag
147#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148
149 if (PyErr_Occurred()) {
150 Py_CLEAR(floatinfo);
151 return NULL;
152 }
153 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000154}
155
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 register PyFloatObject *op;
160 if (free_list == NULL) {
161 if ((free_list = fill_free_list()) == NULL)
162 return NULL;
163 }
164 /* Inline PyObject_New */
165 op = free_list;
166 free_list = (PyFloatObject *)Py_TYPE(op);
167 PyObject_INIT(op, &PyFloat_Type);
168 op->ob_fval = fval;
169 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170}
171
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000173PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 const char *s, *last, *end;
176 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000177 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 Py_ssize_t len;
179 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (PyUnicode_Check(v)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
183 Py_UNICODE *bufptr;
184 s_buffer = PyUnicode_TransformDecimalToASCII(
185 PyUnicode_AS_UNICODE(v), buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000187 return NULL;
188 /* Replace non-ASCII whitespace with ' ' */
189 bufptr = PyUnicode_AS_UNICODE(s_buffer);
190 for (i = 0; i < buflen; i++) {
191 Py_UNICODE ch = bufptr[i];
192 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
193 bufptr[i] = ' ';
194 }
195 s = _PyUnicode_AsStringAndSize(s_buffer, &len);
196 if (s == NULL) {
197 Py_DECREF(s_buffer);
198 return NULL;
199 }
200 last = s + len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 }
202 else if (PyObject_AsCharBuffer(v, &s, &len)) {
203 PyErr_SetString(PyExc_TypeError,
204 "float() argument must be a string or a number");
205 return NULL;
206 }
207 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000208 /* strip space */
209 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000211 while (s < last - 1 && Py_ISSPACE(last[-1]))
212 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* We don't care about overflow or underflow. If the platform
214 * supports them, infinities and signed zeroes (on underflow) are
215 * fine. */
216 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000217 if (end != last) {
218 PyErr_Format(PyExc_ValueError,
219 "could not convert string to float: "
220 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 result = NULL;
222 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000223 else if (x == -1.0 && PyErr_Occurred())
224 result = NULL;
225 else
226 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000227
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000228 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000230}
231
Guido van Rossum234f9421993-06-17 12:35:49 +0000232static void
Fred Drakefd99de62000-07-09 05:02:18 +0000233float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (PyFloat_CheckExact(op)) {
236 Py_TYPE(op) = (struct _typeobject *)free_list;
237 free_list = op;
238 }
239 else
240 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000241}
242
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243double
Fred Drakefd99de62000-07-09 05:02:18 +0000244PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyNumberMethods *nb;
247 PyFloatObject *fo;
248 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (op && PyFloat_Check(op))
251 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (op == NULL) {
254 PyErr_BadArgument();
255 return -1;
256 }
Tim Petersd2364e82001-11-01 20:09:42 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
259 PyErr_SetString(PyExc_TypeError, "a float is required");
260 return -1;
261 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 fo = (PyFloatObject*) (*nb->nb_float) (op);
264 if (fo == NULL)
265 return -1;
266 if (!PyFloat_Check(fo)) {
267 PyErr_SetString(PyExc_TypeError,
268 "nb_float should return float object");
269 return -1;
270 }
Tim Petersd2364e82001-11-01 20:09:42 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 val = PyFloat_AS_DOUBLE(fo);
273 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276}
277
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000279 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000280 set to NULL, and the function invoking this macro returns NULL. If
281 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
282 stored in obj, and returned from the function invoking this macro.
283*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284#define CONVERT_TO_DOUBLE(obj, dbl) \
285 if (PyFloat_Check(obj)) \
286 dbl = PyFloat_AS_DOUBLE(obj); \
287 else if (convert_to_double(&(obj), &(dbl)) < 0) \
288 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000289
Eric Smith0923d1d2009-04-16 20:16:10 +0000290/* Methods */
291
Neil Schemenauer32117e52001-01-04 01:44:34 +0000292static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000293convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (PyLong_Check(obj)) {
298 *dbl = PyLong_AsDouble(obj);
299 if (*dbl == -1.0 && PyErr_Occurred()) {
300 *v = NULL;
301 return -1;
302 }
303 }
304 else {
305 Py_INCREF(Py_NotImplemented);
306 *v = Py_NotImplemented;
307 return -1;
308 }
309 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000310}
311
Eric Smith0923d1d2009-04-16 20:16:10 +0000312static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000313float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000314{
315 PyObject *result;
316 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000317 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000318 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000319 NULL);
320 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000321 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000322 result = PyUnicode_FromString(buf);
323 PyMem_Free(buf);
324 return result;
325}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000326
Tim Peters307fa782004-09-23 08:06:40 +0000327/* Comparison is pretty much a nightmare. When comparing float to float,
328 * we do it as straightforwardly (and long-windedly) as conceivable, so
329 * that, e.g., Python x == y delivers the same result as the platform
330 * C x == y when x and/or y is a NaN.
331 * When mixing float with an integer type, there's no good *uniform* approach.
332 * Converting the double to an integer obviously doesn't work, since we
333 * may lose info from fractional bits. Converting the integer to a double
334 * also has two failure modes: (1) a long int may trigger overflow (too
335 * large to fit in the dynamic range of a C double); (2) even a C long may have
336 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
337 * 63 bits of precision, but a C double probably has only 53), and then
338 * we can falsely claim equality when low-order integer bits are lost by
339 * coercion to double. So this part is painful too.
340 */
341
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342static PyObject*
343float_richcompare(PyObject *v, PyObject *w, int op)
344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 double i, j;
346 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 assert(PyFloat_Check(v));
349 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* Switch on the type of w. Set i and j to doubles to be compared,
352 * and op to the richcomp to use.
353 */
354 if (PyFloat_Check(w))
355 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 else if (!Py_IS_FINITE(i)) {
358 if (PyLong_Check(w))
359 /* If i is an infinity, its magnitude exceeds any
360 * finite integer, so it doesn't matter which int we
361 * compare i with. If i is a NaN, similarly.
362 */
363 j = 0.0;
364 else
365 goto Unimplemented;
366 }
Tim Peters307fa782004-09-23 08:06:40 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 else if (PyLong_Check(w)) {
369 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
370 int wsign = _PyLong_Sign(w);
371 size_t nbits;
372 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (vsign != wsign) {
375 /* Magnitudes are irrelevant -- the signs alone
376 * determine the outcome.
377 */
378 i = (double)vsign;
379 j = (double)wsign;
380 goto Compare;
381 }
382 /* The signs are the same. */
383 /* Convert w to a double if it fits. In particular, 0 fits. */
384 nbits = _PyLong_NumBits(w);
385 if (nbits == (size_t)-1 && PyErr_Occurred()) {
386 /* This long is so large that size_t isn't big enough
387 * to hold the # of bits. Replace with little doubles
388 * that give the same outcome -- w is so large that
389 * its magnitude must exceed the magnitude of any
390 * finite float.
391 */
392 PyErr_Clear();
393 i = (double)vsign;
394 assert(wsign != 0);
395 j = wsign * 2.0;
396 goto Compare;
397 }
398 if (nbits <= 48) {
399 j = PyLong_AsDouble(w);
400 /* It's impossible that <= 48 bits overflowed. */
401 assert(j != -1.0 || ! PyErr_Occurred());
402 goto Compare;
403 }
404 assert(wsign != 0); /* else nbits was 0 */
405 assert(vsign != 0); /* if vsign were 0, then since wsign is
406 * not 0, we would have taken the
407 * vsign != wsign branch at the start */
408 /* We want to work with non-negative numbers. */
409 if (vsign < 0) {
410 /* "Multiply both sides" by -1; this also swaps the
411 * comparator.
412 */
413 i = -i;
414 op = _Py_SwappedOp[op];
415 }
416 assert(i > 0.0);
417 (void) frexp(i, &exponent);
418 /* exponent is the # of bits in v before the radix point;
419 * we know that nbits (the # of bits in w) > 48 at this point
420 */
421 if (exponent < 0 || (size_t)exponent < nbits) {
422 i = 1.0;
423 j = 2.0;
424 goto Compare;
425 }
426 if ((size_t)exponent > nbits) {
427 i = 2.0;
428 j = 1.0;
429 goto Compare;
430 }
431 /* v and w have the same number of bits before the radix
432 * point. Construct two longs that have the same comparison
433 * outcome.
434 */
435 {
436 double fracpart;
437 double intpart;
438 PyObject *result = NULL;
439 PyObject *one = NULL;
440 PyObject *vv = NULL;
441 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (wsign < 0) {
444 ww = PyNumber_Negative(w);
445 if (ww == NULL)
446 goto Error;
447 }
448 else
449 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 fracpart = modf(i, &intpart);
452 vv = PyLong_FromDouble(intpart);
453 if (vv == NULL)
454 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (fracpart != 0.0) {
457 /* Shift left, and or a 1 bit into vv
458 * to represent the lost fraction.
459 */
460 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 one = PyLong_FromLong(1);
463 if (one == NULL)
464 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 temp = PyNumber_Lshift(ww, one);
467 if (temp == NULL)
468 goto Error;
469 Py_DECREF(ww);
470 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 temp = PyNumber_Lshift(vv, one);
473 if (temp == NULL)
474 goto Error;
475 Py_DECREF(vv);
476 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 temp = PyNumber_Or(vv, one);
479 if (temp == NULL)
480 goto Error;
481 Py_DECREF(vv);
482 vv = temp;
483 }
Tim Peters307fa782004-09-23 08:06:40 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 r = PyObject_RichCompareBool(vv, ww, op);
486 if (r < 0)
487 goto Error;
488 result = PyBool_FromLong(r);
489 Error:
490 Py_XDECREF(vv);
491 Py_XDECREF(ww);
492 Py_XDECREF(one);
493 return result;
494 }
495 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 else /* w isn't float, int, or long */
498 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000499
500 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyFPE_START_PROTECT("richcompare", return NULL)
502 switch (op) {
503 case Py_EQ:
504 r = i == j;
505 break;
506 case Py_NE:
507 r = i != j;
508 break;
509 case Py_LE:
510 r = i <= j;
511 break;
512 case Py_GE:
513 r = i >= j;
514 break;
515 case Py_LT:
516 r = i < j;
517 break;
518 case Py_GT:
519 r = i > j;
520 break;
521 }
522 PyFPE_END_PROTECT(r)
523 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000524
525 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 Py_INCREF(Py_NotImplemented);
527 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000528}
529
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000530static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000534}
535
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 double a,b;
540 CONVERT_TO_DOUBLE(v, a);
541 CONVERT_TO_DOUBLE(w, b);
542 PyFPE_START_PROTECT("add", return 0)
543 a = a + b;
544 PyFPE_END_PROTECT(a)
545 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000549float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 double a,b;
552 CONVERT_TO_DOUBLE(v, a);
553 CONVERT_TO_DOUBLE(w, b);
554 PyFPE_START_PROTECT("subtract", return 0)
555 a = a - b;
556 PyFPE_END_PROTECT(a)
557 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 double a,b;
564 CONVERT_TO_DOUBLE(v, a);
565 CONVERT_TO_DOUBLE(w, b);
566 PyFPE_START_PROTECT("multiply", return 0)
567 a = a * b;
568 PyFPE_END_PROTECT(a)
569 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double a,b;
576 CONVERT_TO_DOUBLE(v, a);
577 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (b == 0.0) {
579 PyErr_SetString(PyExc_ZeroDivisionError,
580 "float division by zero");
581 return NULL;
582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyFPE_START_PROTECT("divide", return 0)
584 a = a / b;
585 PyFPE_END_PROTECT(a)
586 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 double vx, wx;
593 double mod;
594 CONVERT_TO_DOUBLE(v, vx);
595 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (wx == 0.0) {
597 PyErr_SetString(PyExc_ZeroDivisionError,
598 "float modulo");
599 return NULL;
600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyFPE_START_PROTECT("modulo", return 0)
602 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000603 if (mod) {
604 /* ensure the remainder has the same sign as the denominator */
605 if ((wx < 0) != (mod < 0)) {
606 mod += wx;
607 }
608 }
609 else {
610 /* the remainder is zero, and in the presence of signed zeroes
611 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000612 it has the same sign as the denominator. */
613 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 }
615 PyFPE_END_PROTECT(mod)
616 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 double vx, wx;
623 double div, mod, floordiv;
624 CONVERT_TO_DOUBLE(v, vx);
625 CONVERT_TO_DOUBLE(w, wx);
626 if (wx == 0.0) {
627 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
628 return NULL;
629 }
630 PyFPE_START_PROTECT("divmod", return 0)
631 mod = fmod(vx, wx);
632 /* fmod is typically exact, so vx-mod is *mathematically* an
633 exact multiple of wx. But this is fp arithmetic, and fp
634 vx - mod is an approximation; the result is that div may
635 not be an exact integral value after the division, although
636 it will always be very close to one.
637 */
638 div = (vx - mod) / wx;
639 if (mod) {
640 /* ensure the remainder has the same sign as the denominator */
641 if ((wx < 0) != (mod < 0)) {
642 mod += wx;
643 div -= 1.0;
644 }
645 }
646 else {
647 /* the remainder is zero, and in the presence of signed zeroes
648 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000649 it has the same sign as the denominator. */
650 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 /* snap quotient to nearest integral value */
653 if (div) {
654 floordiv = floor(div);
655 if (div - floordiv > 0.5)
656 floordiv += 1.0;
657 }
658 else {
659 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000660 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 PyFPE_END_PROTECT(floordiv)
663 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000667float_floor_div(PyObject *v, PyObject *w)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 t = float_divmod(v, w);
672 if (t == NULL || t == Py_NotImplemented)
673 return t;
674 assert(PyTuple_CheckExact(t));
675 r = PyTuple_GET_ITEM(t, 0);
676 Py_INCREF(r);
677 Py_DECREF(t);
678 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000679}
680
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000681/* determine whether x is an odd integer or not; assumes that
682 x is not an infinity or nan. */
683#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
684
Tim Peters63a35712001-12-11 19:57:24 +0000685static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000686float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 double iv, iw, ix;
689 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if ((PyObject *)z != Py_None) {
692 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
693 "allowed unless all arguments are integers");
694 return NULL;
695 }
Tim Peters32f453e2001-09-03 08:35:41 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 CONVERT_TO_DOUBLE(v, iv);
698 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Sort out special cases here instead of relying on pow() */
701 if (iw == 0) { /* v**0 is 1, even 0**0 */
702 return PyFloat_FromDouble(1.0);
703 }
704 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
705 return PyFloat_FromDouble(iv);
706 }
707 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
708 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
709 }
710 if (Py_IS_INFINITY(iw)) {
711 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
712 * abs(v) > 1 (including case where v infinite)
713 *
714 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
715 * abs(v) > 1 (including case where v infinite)
716 */
717 iv = fabs(iv);
718 if (iv == 1.0)
719 return PyFloat_FromDouble(1.0);
720 else if ((iw > 0.0) == (iv > 1.0))
721 return PyFloat_FromDouble(fabs(iw)); /* return inf */
722 else
723 return PyFloat_FromDouble(0.0);
724 }
725 if (Py_IS_INFINITY(iv)) {
726 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
727 * both cases, we need to add the appropriate sign if w is
728 * an odd integer.
729 */
730 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
731 if (iw > 0.0)
732 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
733 else
734 return PyFloat_FromDouble(iw_is_odd ?
735 copysign(0.0, iv) : 0.0);
736 }
737 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
738 (already dealt with above), and an error
739 if w is negative. */
740 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
741 if (iw < 0.0) {
742 PyErr_SetString(PyExc_ZeroDivisionError,
743 "0.0 cannot be raised to a "
744 "negative power");
745 return NULL;
746 }
747 /* use correct sign if iw is odd */
748 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
749 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (iv < 0.0) {
752 /* Whether this is an error is a mess, and bumps into libm
753 * bugs so we have to figure it out ourselves.
754 */
755 if (iw != floor(iw)) {
756 /* Negative numbers raised to fractional powers
757 * become complex.
758 */
759 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
760 }
761 /* iw is an exact integer, albeit perhaps a very large
762 * one. Replace iv by its absolute value and remember
763 * to negate the pow result if iw is odd.
764 */
765 iv = -iv;
766 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
767 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
770 /* (-1) ** large_integer also ends up here. Here's an
771 * extract from the comments for the previous
772 * implementation explaining why this special case is
773 * necessary:
774 *
775 * -1 raised to an exact integer should never be exceptional.
776 * Alas, some libms (chiefly glibc as of early 2003) return
777 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
778 * happen to be representable in a *C* integer. That's a
779 * bug.
780 */
781 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
782 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Now iv and iw are finite, iw is nonzero, and iv is
785 * positive and not equal to 1.0. We finally allow
786 * the platform pow to step in and do the rest.
787 */
788 errno = 0;
789 PyFPE_START_PROTECT("pow", return NULL)
790 ix = pow(iv, iw);
791 PyFPE_END_PROTECT(ix)
792 Py_ADJUST_ERANGE1(ix);
793 if (negate_result)
794 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (errno != 0) {
797 /* We don't expect any errno value other than ERANGE, but
798 * the range of libm bugs appears unbounded.
799 */
800 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
801 PyExc_ValueError);
802 return NULL;
803 }
804 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805}
806
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000807#undef DOUBLE_IS_ODD_INTEGER
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000816float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819}
820
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000821static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000822float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000825}
826
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000827static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000828float_is_integer(PyObject *v)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 double x = PyFloat_AsDouble(v);
831 PyObject *o;
832
833 if (x == -1.0 && PyErr_Occurred())
834 return NULL;
835 if (!Py_IS_FINITE(x))
836 Py_RETURN_FALSE;
837 errno = 0;
838 PyFPE_START_PROTECT("is_integer", return NULL)
839 o = (floor(x) == x) ? Py_True : Py_False;
840 PyFPE_END_PROTECT(x)
841 if (errno != 0) {
842 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
843 PyExc_ValueError);
844 return NULL;
845 }
846 Py_INCREF(o);
847 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000848}
849
850#if 0
851static PyObject *
852float_is_inf(PyObject *v)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 double x = PyFloat_AsDouble(v);
855 if (x == -1.0 && PyErr_Occurred())
856 return NULL;
857 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000858}
859
860static PyObject *
861float_is_nan(PyObject *v)
862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 double x = PyFloat_AsDouble(v);
864 if (x == -1.0 && PyErr_Occurred())
865 return NULL;
866 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000867}
868
869static PyObject *
870float_is_finite(PyObject *v)
871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 double x = PyFloat_AsDouble(v);
873 if (x == -1.0 && PyErr_Occurred())
874 return NULL;
875 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000876}
877#endif
878
879static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000880float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 double x = PyFloat_AsDouble(v);
883 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 (void)modf(x, &wholepart);
886 /* Try to get out cheap if this fits in a Python int. The attempt
887 * to cast to long must be protected, as C doesn't define what
888 * happens if the double is too big to fit in a long. Some rare
889 * systems raise an exception then (RISCOS was mentioned as one,
890 * and someone using a non-default option on Sun also bumped into
891 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
892 * still be vulnerable: if a long has more bits of precision than
893 * a double, casting MIN/MAX to double may yield an approximation,
894 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
895 * yield true from the C expression wholepart<=LONG_MAX, despite
896 * that wholepart is actually greater than LONG_MAX.
897 */
898 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
899 const long aslong = (long)wholepart;
900 return PyLong_FromLong(aslong);
901 }
902 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000903}
904
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905/* double_round: rounds a finite double to the closest multiple of
906 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
907 ndigits <= 323). Returns a Python float, or sets a Python error and
908 returns NULL on failure (OverflowError and memory errors are possible). */
909
910#ifndef PY_NO_SHORT_FLOAT_REPR
911/* version of double_round that uses the correctly-rounded string<->double
912 conversions from Python/dtoa.c */
913
914static PyObject *
915double_round(double x, int ndigits) {
916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 double rounded;
918 Py_ssize_t buflen, mybuflen=100;
919 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
920 int decpt, sign;
921 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* round to a decimal string */
924 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
925 if (buf == NULL) {
926 PyErr_NoMemory();
927 return NULL;
928 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
931 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
932 buflen = buf_end - buf;
933 if (buflen + 8 > mybuflen) {
934 mybuflen = buflen+8;
935 mybuf = (char *)PyMem_Malloc(mybuflen);
936 if (mybuf == NULL) {
937 PyErr_NoMemory();
938 goto exit;
939 }
940 }
941 /* copy buf to mybuf, adding exponent, sign and leading 0 */
942 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
943 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* and convert the resulting string back to a double */
946 errno = 0;
947 rounded = _Py_dg_strtod(mybuf, NULL);
948 if (errno == ERANGE && fabs(rounded) >= 1.)
949 PyErr_SetString(PyExc_OverflowError,
950 "rounded value too large to represent");
951 else
952 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* done computing value; now clean up */
955 if (mybuf != shortbuf)
956 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000957 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 _Py_dg_freedtoa(buf);
959 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000960}
961
962#else /* PY_NO_SHORT_FLOAT_REPR */
963
964/* fallback version, to be used when correctly rounded binary<->decimal
965 conversions aren't available */
966
967static PyObject *
968double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 double pow1, pow2, y, z;
970 if (ndigits >= 0) {
971 if (ndigits > 22) {
972 /* pow1 and pow2 are each safe from overflow, but
973 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
974 pow1 = pow(10.0, (double)(ndigits-22));
975 pow2 = 1e22;
976 }
977 else {
978 pow1 = pow(10.0, (double)ndigits);
979 pow2 = 1.0;
980 }
981 y = (x*pow1)*pow2;
982 /* if y overflows, then rounded value is exactly x */
983 if (!Py_IS_FINITE(y))
984 return PyFloat_FromDouble(x);
985 }
986 else {
987 pow1 = pow(10.0, (double)-ndigits);
988 pow2 = 1.0; /* unused; silences a gcc compiler warning */
989 y = x / pow1;
990 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 z = round(y);
993 if (fabs(y-z) == 0.5)
994 /* halfway between two integers; use round-half-even */
995 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (ndigits >= 0)
998 z = (z / pow2) / pow1;
999 else
1000 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* if computation resulted in overflow, raise OverflowError */
1003 if (!Py_IS_FINITE(z)) {
1004 PyErr_SetString(PyExc_OverflowError,
1005 "overflow occurred during round");
1006 return NULL;
1007 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001010}
1011
1012#endif /* PY_NO_SHORT_FLOAT_REPR */
1013
1014/* round a Python float v to the closest multiple of 10**-ndigits */
1015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001016static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001017float_round(PyObject *v, PyObject *args)
1018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 double x, rounded;
1020 PyObject *o_ndigits = NULL;
1021 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 x = PyFloat_AsDouble(v);
1024 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1025 return NULL;
1026 if (o_ndigits == NULL) {
1027 /* single-argument round: round to nearest integer */
1028 rounded = round(x);
1029 if (fabs(x-rounded) == 0.5)
1030 /* halfway case: round to even */
1031 rounded = 2.0*round(x/2.0);
1032 return PyLong_FromDouble(rounded);
1033 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* interpret second argument as a Py_ssize_t; clips on overflow */
1036 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1037 if (ndigits == -1 && PyErr_Occurred())
1038 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* nans and infinities round to themselves */
1041 if (!Py_IS_FINITE(x))
1042 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1045 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1046 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001047#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1048#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (ndigits > NDIGITS_MAX)
1050 /* return x */
1051 return PyFloat_FromDouble(x);
1052 else if (ndigits < NDIGITS_MIN)
1053 /* return 0.0, but with sign of x */
1054 return PyFloat_FromDouble(0.0*x);
1055 else
1056 /* finite x, and ndigits is not unreasonably large */
1057 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001058#undef NDIGITS_MAX
1059#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001060}
1061
1062static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001063float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (PyFloat_CheckExact(v))
1066 Py_INCREF(v);
1067 else
1068 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1069 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001070}
1071
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001072/* turn ASCII hex characters into integer values and vice versa */
1073
1074static char
1075char_from_hex(int x)
1076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 assert(0 <= x && x < 16);
1078 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001079}
1080
1081static int
1082hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 int x;
1084 switch(c) {
1085 case '0':
1086 x = 0;
1087 break;
1088 case '1':
1089 x = 1;
1090 break;
1091 case '2':
1092 x = 2;
1093 break;
1094 case '3':
1095 x = 3;
1096 break;
1097 case '4':
1098 x = 4;
1099 break;
1100 case '5':
1101 x = 5;
1102 break;
1103 case '6':
1104 x = 6;
1105 break;
1106 case '7':
1107 x = 7;
1108 break;
1109 case '8':
1110 x = 8;
1111 break;
1112 case '9':
1113 x = 9;
1114 break;
1115 case 'a':
1116 case 'A':
1117 x = 10;
1118 break;
1119 case 'b':
1120 case 'B':
1121 x = 11;
1122 break;
1123 case 'c':
1124 case 'C':
1125 x = 12;
1126 break;
1127 case 'd':
1128 case 'D':
1129 x = 13;
1130 break;
1131 case 'e':
1132 case 'E':
1133 x = 14;
1134 break;
1135 case 'f':
1136 case 'F':
1137 x = 15;
1138 break;
1139 default:
1140 x = -1;
1141 break;
1142 }
1143 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001144}
1145
1146/* convert a float to a hexadecimal string */
1147
1148/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1149 of the form 4k+1. */
1150#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1151
1152static PyObject *
1153float_hex(PyObject *v)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 double x, m;
1156 int e, shift, i, si, esign;
1157 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1158 trailing NUL byte. */
1159 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001164 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001167 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 return PyUnicode_FromString("-0x0.0p+0");
1169 else
1170 return PyUnicode_FromString("0x0.0p+0");
1171 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 m = frexp(fabs(x), &e);
1174 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1175 m = ldexp(m, shift);
1176 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 si = 0;
1179 s[si] = char_from_hex((int)m);
1180 si++;
1181 m -= (int)m;
1182 s[si] = '.';
1183 si++;
1184 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1185 m *= 16.0;
1186 s[si] = char_from_hex((int)m);
1187 si++;
1188 m -= (int)m;
1189 }
1190 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (e < 0) {
1193 esign = (int)'-';
1194 e = -e;
1195 }
1196 else
1197 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (x < 0.0)
1200 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1201 else
1202 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001203}
1204
1205PyDoc_STRVAR(float_hex_doc,
1206"float.hex() -> string\n\
1207\n\
1208Return a hexadecimal representation of a floating-point number.\n\
1209>>> (-0.1).hex()\n\
1210'-0x1.999999999999ap-4'\n\
1211>>> 3.14159.hex()\n\
1212'0x1.921f9f01b866ep+1'");
1213
1214/* Convert a hexadecimal string to a float. */
1215
1216static PyObject *
1217float_fromhex(PyObject *cls, PyObject *arg)
1218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 PyObject *result_as_float, *result;
1220 double x;
1221 long exp, top_exp, lsb, key_digit;
1222 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1223 int half_eps, digit, round_up, negate=0;
1224 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 /*
1227 * For the sake of simplicity and correctness, we impose an artificial
1228 * limit on ndigits, the total number of hex digits in the coefficient
1229 * The limit is chosen to ensure that, writing exp for the exponent,
1230 *
1231 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1232 * guaranteed to overflow (provided it's nonzero)
1233 *
1234 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1235 * guaranteed to underflow to 0.
1236 *
1237 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1238 * overflow in the calculation of exp and top_exp below.
1239 *
1240 * More specifically, ndigits is assumed to satisfy the following
1241 * inequalities:
1242 *
1243 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1244 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1245 *
1246 * If either of these inequalities is not satisfied, a ValueError is
1247 * raised. Otherwise, write x for the value of the hex string, and
1248 * assume x is nonzero. Then
1249 *
1250 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1251 *
1252 * Now if exp > LONG_MAX/2 then:
1253 *
1254 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1255 * = DBL_MAX_EXP
1256 *
1257 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1258 * double, so overflows. If exp < LONG_MIN/2, then
1259 *
1260 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1261 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1262 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1263 *
1264 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1265 * when converted to a C double.
1266 *
1267 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1268 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1269 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 s = _PyUnicode_AsStringAndSize(arg, &length);
1272 if (s == NULL)
1273 return NULL;
1274 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 /********************
1277 * Parse the string *
1278 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 /* leading whitespace */
1281 while (Py_ISSPACE(*s))
1282 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* infinities and nans */
1285 x = _Py_parse_inf_or_nan(s, &coeff_end);
1286 if (coeff_end != s) {
1287 s = coeff_end;
1288 goto finished;
1289 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 /* optional sign */
1292 if (*s == '-') {
1293 s++;
1294 negate = 1;
1295 }
1296 else if (*s == '+')
1297 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* [0x] */
1300 s_store = s;
1301 if (*s == '0') {
1302 s++;
1303 if (*s == 'x' || *s == 'X')
1304 s++;
1305 else
1306 s = s_store;
1307 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /* coefficient: <integer> [. <fraction>] */
1310 coeff_start = s;
1311 while (hex_from_char(*s) >= 0)
1312 s++;
1313 s_store = s;
1314 if (*s == '.') {
1315 s++;
1316 while (hex_from_char(*s) >= 0)
1317 s++;
1318 coeff_end = s-1;
1319 }
1320 else
1321 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* ndigits = total # of hex digits; fdigits = # after point */
1324 ndigits = coeff_end - coeff_start;
1325 fdigits = coeff_end - s_store;
1326 if (ndigits == 0)
1327 goto parse_error;
1328 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1329 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1330 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* [p <exponent>] */
1333 if (*s == 'p' || *s == 'P') {
1334 s++;
1335 exp_start = s;
1336 if (*s == '-' || *s == '+')
1337 s++;
1338 if (!('0' <= *s && *s <= '9'))
1339 goto parse_error;
1340 s++;
1341 while ('0' <= *s && *s <= '9')
1342 s++;
1343 exp = strtol(exp_start, NULL, 10);
1344 }
1345 else
1346 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1350 coeff_end-(j) : \
1351 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /*******************************************
1354 * Compute rounded value of the hex string *
1355 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* Discard leading zeros, and catch extreme overflow and underflow */
1358 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1359 ndigits--;
1360 if (ndigits == 0 || exp < LONG_MIN/2) {
1361 x = 0.0;
1362 goto finished;
1363 }
1364 if (exp > LONG_MAX/2)
1365 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* Adjust exponent for fractional part. */
1368 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1371 top_exp = exp + 4*((long)ndigits - 1);
1372 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1373 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* catch almost all nonextreme cases of overflow and underflow here */
1376 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1377 x = 0.0;
1378 goto finished;
1379 }
1380 if (top_exp > DBL_MAX_EXP)
1381 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* lsb = exponent of least significant bit of the *rounded* value.
1384 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1385 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 x = 0.0;
1388 if (exp >= lsb) {
1389 /* no rounding required */
1390 for (i = ndigits-1; i >= 0; i--)
1391 x = 16.0*x + HEX_DIGIT(i);
1392 x = ldexp(x, (int)(exp));
1393 goto finished;
1394 }
1395 /* rounding required. key_digit is the index of the hex digit
1396 containing the first bit to be rounded away. */
1397 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1398 key_digit = (lsb - exp - 1) / 4;
1399 for (i = ndigits-1; i > key_digit; i--)
1400 x = 16.0*x + HEX_DIGIT(i);
1401 digit = HEX_DIGIT(key_digit);
1402 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1405 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1406 if ((digit & half_eps) != 0) {
1407 round_up = 0;
1408 if ((digit & (3*half_eps-1)) != 0 ||
1409 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1410 round_up = 1;
1411 else
1412 for (i = key_digit-1; i >= 0; i--)
1413 if (HEX_DIGIT(i) != 0) {
1414 round_up = 1;
1415 break;
1416 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001417 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 x += 2*half_eps;
1419 if (top_exp == DBL_MAX_EXP &&
1420 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1421 /* overflow corner case: pre-rounded value <
1422 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1423 goto overflow_error;
1424 }
1425 }
1426 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001427
1428 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* optional trailing whitespace leading to the end of the string */
1430 while (Py_ISSPACE(*s))
1431 s++;
1432 if (s != s_end)
1433 goto parse_error;
1434 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1435 if (result_as_float == NULL)
1436 return NULL;
1437 result = PyObject_CallObject(cls, result_as_float);
1438 Py_DECREF(result_as_float);
1439 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001440
1441 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyErr_SetString(PyExc_OverflowError,
1443 "hexadecimal value too large to represent as a float");
1444 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001445
1446 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyErr_SetString(PyExc_ValueError,
1448 "invalid hexadecimal floating-point string");
1449 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001450
1451 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyErr_SetString(PyExc_ValueError,
1453 "hexadecimal string too long to convert");
1454 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001455}
1456
1457PyDoc_STRVAR(float_fromhex_doc,
1458"float.fromhex(string) -> float\n\
1459\n\
1460Create a floating-point number from a hexadecimal string.\n\
1461>>> float.fromhex('0x1.ffffp10')\n\
14622047.984375\n\
1463>>> float.fromhex('-0x1p-1074')\n\
1464-4.9406564584124654e-324");
1465
1466
Christian Heimes26855632008-01-27 23:50:43 +00001467static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001468float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 double self;
1471 double float_part;
1472 int exponent;
1473 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyObject *prev;
1476 PyObject *py_exponent = NULL;
1477 PyObject *numerator = NULL;
1478 PyObject *denominator = NULL;
1479 PyObject *result_pair = NULL;
1480 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001481
1482#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 prev = obj; \
1484 obj = call; \
1485 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (Py_IS_INFINITY(self)) {
1490 PyErr_SetString(PyExc_OverflowError,
1491 "Cannot pass infinity to float.as_integer_ratio.");
1492 return NULL;
1493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (Py_IS_NAN(self)) {
1495 PyErr_SetString(PyExc_ValueError,
1496 "Cannot pass NaN to float.as_integer_ratio.");
1497 return NULL;
1498 }
Christian Heimes26855632008-01-27 23:50:43 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1501 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1502 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1505 float_part *= 2.0;
1506 exponent--;
1507 }
1508 /* self == float_part * 2**exponent exactly and float_part is integral.
1509 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1510 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 numerator = PyLong_FromDouble(float_part);
1513 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 /* fold in 2**exponent */
1516 denominator = PyLong_FromLong(1);
1517 py_exponent = PyLong_FromLong(labs((long)exponent));
1518 if (py_exponent == NULL) goto error;
1519 INPLACE_UPDATE(py_exponent,
1520 long_methods->nb_lshift(denominator, py_exponent));
1521 if (py_exponent == NULL) goto error;
1522 if (exponent > 0) {
1523 INPLACE_UPDATE(numerator,
1524 long_methods->nb_multiply(numerator, py_exponent));
1525 if (numerator == NULL) goto error;
1526 }
1527 else {
1528 Py_DECREF(denominator);
1529 denominator = py_exponent;
1530 py_exponent = NULL;
1531 }
1532
1533 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001534
1535#undef INPLACE_UPDATE
1536error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_XDECREF(py_exponent);
1538 Py_XDECREF(denominator);
1539 Py_XDECREF(numerator);
1540 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001541}
1542
1543PyDoc_STRVAR(float_as_integer_ratio_doc,
1544"float.as_integer_ratio() -> (int, int)\n"
1545"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001546"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1547"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001548"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001549"\n"
1550">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001551"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001552">>> (0.0).as_integer_ratio()\n"
1553"(0, 1)\n"
1554">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001555"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001556
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001557
Jeremy Hylton938ace62002-07-17 16:30:39 +00001558static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001559float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1560
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561static PyObject *
1562float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 PyObject *x = Py_False; /* Integer zero */
1565 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (type != &PyFloat_Type)
1568 return float_subtype_new(type, args, kwds); /* Wimp out */
1569 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1570 return NULL;
1571 /* If it's a string, but not a string subclass, use
1572 PyFloat_FromString. */
1573 if (PyUnicode_CheckExact(x))
1574 return PyFloat_FromString(x);
1575 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576}
1577
Guido van Rossumbef14172001-08-29 15:47:46 +00001578/* Wimpy, slow approach to tp_new calls for subtypes of float:
1579 first create a regular float from whatever arguments we got,
1580 then allocate a subtype instance and initialize its ob_fval
1581 from the regular float. The regular float is then thrown away.
1582*/
1583static PyObject *
1584float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 assert(PyType_IsSubtype(type, &PyFloat_Type));
1589 tmp = float_new(&PyFloat_Type, args, kwds);
1590 if (tmp == NULL)
1591 return NULL;
1592 assert(PyFloat_CheckExact(tmp));
1593 newobj = type->tp_alloc(type, 0);
1594 if (newobj == NULL) {
1595 Py_DECREF(tmp);
1596 return NULL;
1597 }
1598 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1599 Py_DECREF(tmp);
1600 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001601}
1602
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001603static PyObject *
1604float_getnewargs(PyFloatObject *v)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001607}
1608
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001609/* this is for the benefit of the pack/unpack routines below */
1610
1611typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613} float_format_type;
1614
1615static float_format_type double_format, float_format;
1616static float_format_type detected_double_format, detected_float_format;
1617
1618static PyObject *
1619float_getformat(PyTypeObject *v, PyObject* arg)
1620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 char* s;
1622 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (!PyUnicode_Check(arg)) {
1625 PyErr_Format(PyExc_TypeError,
1626 "__getformat__() argument must be string, not %.500s",
1627 Py_TYPE(arg)->tp_name);
1628 return NULL;
1629 }
1630 s = _PyUnicode_AsString(arg);
1631 if (s == NULL)
1632 return NULL;
1633 if (strcmp(s, "double") == 0) {
1634 r = double_format;
1635 }
1636 else if (strcmp(s, "float") == 0) {
1637 r = float_format;
1638 }
1639 else {
1640 PyErr_SetString(PyExc_ValueError,
1641 "__getformat__() argument 1 must be "
1642 "'double' or 'float'");
1643 return NULL;
1644 }
1645
1646 switch (r) {
1647 case unknown_format:
1648 return PyUnicode_FromString("unknown");
1649 case ieee_little_endian_format:
1650 return PyUnicode_FromString("IEEE, little-endian");
1651 case ieee_big_endian_format:
1652 return PyUnicode_FromString("IEEE, big-endian");
1653 default:
1654 Py_FatalError("insane float_format or double_format");
1655 return NULL;
1656 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001657}
1658
1659PyDoc_STRVAR(float_getformat_doc,
1660"float.__getformat__(typestr) -> string\n"
1661"\n"
1662"You probably don't want to use this function. It exists mainly to be\n"
1663"used in Python's test suite.\n"
1664"\n"
1665"typestr must be 'double' or 'float'. This function returns whichever of\n"
1666"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1667"format of floating point numbers used by the C type named by typestr.");
1668
1669static PyObject *
1670float_setformat(PyTypeObject *v, PyObject* args)
1671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 char* typestr;
1673 char* format;
1674 float_format_type f;
1675 float_format_type detected;
1676 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1679 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (strcmp(typestr, "double") == 0) {
1682 p = &double_format;
1683 detected = detected_double_format;
1684 }
1685 else if (strcmp(typestr, "float") == 0) {
1686 p = &float_format;
1687 detected = detected_float_format;
1688 }
1689 else {
1690 PyErr_SetString(PyExc_ValueError,
1691 "__setformat__() argument 1 must "
1692 "be 'double' or 'float'");
1693 return NULL;
1694 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (strcmp(format, "unknown") == 0) {
1697 f = unknown_format;
1698 }
1699 else if (strcmp(format, "IEEE, little-endian") == 0) {
1700 f = ieee_little_endian_format;
1701 }
1702 else if (strcmp(format, "IEEE, big-endian") == 0) {
1703 f = ieee_big_endian_format;
1704 }
1705 else {
1706 PyErr_SetString(PyExc_ValueError,
1707 "__setformat__() argument 2 must be "
1708 "'unknown', 'IEEE, little-endian' or "
1709 "'IEEE, big-endian'");
1710 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (f != unknown_format && f != detected) {
1715 PyErr_Format(PyExc_ValueError,
1716 "can only set %s format to 'unknown' or the "
1717 "detected platform value", typestr);
1718 return NULL;
1719 }
1720
1721 *p = f;
1722 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001723}
1724
1725PyDoc_STRVAR(float_setformat_doc,
1726"float.__setformat__(typestr, fmt) -> None\n"
1727"\n"
1728"You probably don't want to use this function. It exists mainly to be\n"
1729"used in Python's test suite.\n"
1730"\n"
1731"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1732"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1733"one of the latter two if it appears to match the underlying C reality.\n"
1734"\n"
1735"Overrides the automatic determination of C-level floating point type.\n"
1736"This affects how floats are converted to and from binary strings.");
1737
Guido van Rossumb43daf72007-08-01 18:08:08 +00001738static PyObject *
1739float_getzero(PyObject *v, void *closure)
1740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001742}
1743
Eric Smith8c663262007-08-25 02:26:07 +00001744static PyObject *
1745float__format__(PyObject *self, PyObject *args)
1746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1750 return NULL;
1751 return _PyFloat_FormatAdvanced(self,
1752 PyUnicode_AS_UNICODE(format_spec),
1753 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001754}
1755
1756PyDoc_STRVAR(float__format__doc,
1757"float.__format__(format_spec) -> string\n"
1758"\n"
1759"Formats the float according to format_spec.");
1760
1761
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001762static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1764 "Returns self, the complex conjugate of any float."},
1765 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1766 "Returns the Integral closest to x between 0 and x."},
1767 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1768 "Returns the Integral closest to x, rounding half toward even.\n"
1769 "When an argument is passed, works like built-in round(x, ndigits)."},
1770 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1771 float_as_integer_ratio_doc},
1772 {"fromhex", (PyCFunction)float_fromhex,
1773 METH_O|METH_CLASS, float_fromhex_doc},
1774 {"hex", (PyCFunction)float_hex,
1775 METH_NOARGS, float_hex_doc},
1776 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1777 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001778#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1780 "Returns True if the float is positive or negative infinite."},
1781 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1782 "Returns True if the float is finite, neither infinite nor NaN."},
1783 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1784 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001785#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1787 {"__getformat__", (PyCFunction)float_getformat,
1788 METH_O|METH_CLASS, float_getformat_doc},
1789 {"__setformat__", (PyCFunction)float_setformat,
1790 METH_VARARGS|METH_CLASS, float_setformat_doc},
1791 {"__format__", (PyCFunction)float__format__,
1792 METH_VARARGS, float__format__doc},
1793 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001794};
1795
Guido van Rossumb43daf72007-08-01 18:08:08 +00001796static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001798 (getter)float_float, (setter)NULL,
1799 "the real part of a complex number",
1800 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001802 (getter)float_getzero, (setter)NULL,
1803 "the imaginary part of a complex number",
1804 NULL},
1805 {NULL} /* Sentinel */
1806};
1807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001808PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809"float(x) -> floating point number\n\
1810\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001811Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812
1813
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001814static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 float_add, /*nb_add*/
1816 float_sub, /*nb_subtract*/
1817 float_mul, /*nb_multiply*/
1818 float_rem, /*nb_remainder*/
1819 float_divmod, /*nb_divmod*/
1820 float_pow, /*nb_power*/
1821 (unaryfunc)float_neg, /*nb_negative*/
1822 (unaryfunc)float_float, /*nb_positive*/
1823 (unaryfunc)float_abs, /*nb_absolute*/
1824 (inquiry)float_bool, /*nb_bool*/
1825 0, /*nb_invert*/
1826 0, /*nb_lshift*/
1827 0, /*nb_rshift*/
1828 0, /*nb_and*/
1829 0, /*nb_xor*/
1830 0, /*nb_or*/
1831 float_trunc, /*nb_int*/
1832 0, /*nb_reserved*/
1833 float_float, /*nb_float*/
1834 0, /* nb_inplace_add */
1835 0, /* nb_inplace_subtract */
1836 0, /* nb_inplace_multiply */
1837 0, /* nb_inplace_remainder */
1838 0, /* nb_inplace_power */
1839 0, /* nb_inplace_lshift */
1840 0, /* nb_inplace_rshift */
1841 0, /* nb_inplace_and */
1842 0, /* nb_inplace_xor */
1843 0, /* nb_inplace_or */
1844 float_floor_div, /* nb_floor_divide */
1845 float_div, /* nb_true_divide */
1846 0, /* nb_inplace_floor_divide */
1847 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001848};
1849
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1852 "float",
1853 sizeof(PyFloatObject),
1854 0,
1855 (destructor)float_dealloc, /* tp_dealloc */
1856 0, /* tp_print */
1857 0, /* tp_getattr */
1858 0, /* tp_setattr */
1859 0, /* tp_reserved */
1860 (reprfunc)float_repr, /* tp_repr */
1861 &float_as_number, /* tp_as_number */
1862 0, /* tp_as_sequence */
1863 0, /* tp_as_mapping */
1864 (hashfunc)float_hash, /* tp_hash */
1865 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001866 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 PyObject_GenericGetAttr, /* tp_getattro */
1868 0, /* tp_setattro */
1869 0, /* tp_as_buffer */
1870 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1871 float_doc, /* tp_doc */
1872 0, /* tp_traverse */
1873 0, /* tp_clear */
1874 float_richcompare, /* tp_richcompare */
1875 0, /* tp_weaklistoffset */
1876 0, /* tp_iter */
1877 0, /* tp_iternext */
1878 float_methods, /* tp_methods */
1879 0, /* tp_members */
1880 float_getset, /* tp_getset */
1881 0, /* tp_base */
1882 0, /* tp_dict */
1883 0, /* tp_descr_get */
1884 0, /* tp_descr_set */
1885 0, /* tp_dictoffset */
1886 0, /* tp_init */
1887 0, /* tp_alloc */
1888 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001889};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001890
1891void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892_PyFloat_Init(void)
1893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* We attempt to determine if this machine is using IEEE
1895 floating point formats by peering at the bits of some
1896 carefully chosen values. If it looks like we are on an
1897 IEEE platform, the float packing/unpacking routines can
1898 just copy bits, if not they resort to arithmetic & shifts
1899 and masks. The shifts & masks approach works on all finite
1900 values, but what happens to infinities, NaNs and signed
1901 zeroes on packing is an accident, and attempting to unpack
1902 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 Note that if we're on some whacked-out platform which uses
1905 IEEE formats but isn't strictly little-endian or big-
1906 endian, we will fall back to the portable shifts & masks
1907 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908
1909#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 {
1911 double x = 9006104071832581.0;
1912 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1913 detected_double_format = ieee_big_endian_format;
1914 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1915 detected_double_format = ieee_little_endian_format;
1916 else
1917 detected_double_format = unknown_format;
1918 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001921#endif
1922
1923#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 {
1925 float y = 16711938.0;
1926 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1927 detected_float_format = ieee_big_endian_format;
1928 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1929 detected_float_format = ieee_little_endian_format;
1930 else
1931 detected_float_format = unknown_format;
1932 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001933#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001935#endif
1936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 double_format = detected_double_format;
1938 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* Init float info */
1941 if (FloatInfoType.tp_name == 0)
1942 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943}
1944
Georg Brandl2ee470f2008-07-16 12:55:28 +00001945int
1946PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 PyFloatObject *p;
1949 PyFloatBlock *list, *next;
1950 int i;
1951 int u; /* remaining unfreed floats per block */
1952 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 list = block_list;
1955 block_list = NULL;
1956 free_list = NULL;
1957 while (list != NULL) {
1958 u = 0;
1959 for (i = 0, p = &list->objects[0];
1960 i < N_FLOATOBJECTS;
1961 i++, p++) {
1962 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1963 u++;
1964 }
1965 next = list->next;
1966 if (u) {
1967 list->next = block_list;
1968 block_list = list;
1969 for (i = 0, p = &list->objects[0];
1970 i < N_FLOATOBJECTS;
1971 i++, p++) {
1972 if (!PyFloat_CheckExact(p) ||
1973 Py_REFCNT(p) == 0) {
1974 Py_TYPE(p) = (struct _typeobject *)
1975 free_list;
1976 free_list = p;
1977 }
1978 }
1979 }
1980 else {
1981 PyMem_FREE(list);
1982 }
1983 freelist_size += u;
1984 list = next;
1985 }
1986 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001987}
1988
1989void
1990PyFloat_Fini(void)
1991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyFloatObject *p;
1993 PyFloatBlock *list;
1994 int i;
1995 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 if (!Py_VerboseFlag)
2000 return;
2001 fprintf(stderr, "# cleanup floats");
2002 if (!u) {
2003 fprintf(stderr, "\n");
2004 }
2005 else {
2006 fprintf(stderr,
2007 ": %d unfreed float%s\n",
2008 u, u == 1 ? "" : "s");
2009 }
2010 if (Py_VerboseFlag > 1) {
2011 list = block_list;
2012 while (list != NULL) {
2013 for (i = 0, p = &list->objects[0];
2014 i < N_FLOATOBJECTS;
2015 i++, p++) {
2016 if (PyFloat_CheckExact(p) &&
2017 Py_REFCNT(p) != 0) {
2018 char *buf = PyOS_double_to_string(
2019 PyFloat_AS_DOUBLE(p), 'r',
2020 0, 0, NULL);
2021 if (buf) {
2022 /* XXX(twouters) cast
2023 refcount to long
2024 until %zd is
2025 universally
2026 available
2027 */
2028 fprintf(stderr,
2029 "# <float at %p, refcnt=%ld, val=%s>\n",
2030 p, (long)Py_REFCNT(p), buf);
2031 PyMem_Free(buf);
2032 }
2033 }
2034 }
2035 list = list->next;
2036 }
2037 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002038}
Tim Peters9905b942003-03-20 20:53:32 +00002039
2040/*----------------------------------------------------------------------------
2041 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002042 */
2043int
2044_PyFloat_Pack4(double x, unsigned char *p, int le)
2045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (float_format == unknown_format) {
2047 unsigned char sign;
2048 int e;
2049 double f;
2050 unsigned int fbits;
2051 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (le) {
2054 p += 3;
2055 incr = -1;
2056 }
Tim Peters9905b942003-03-20 20:53:32 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (x < 0) {
2059 sign = 1;
2060 x = -x;
2061 }
2062 else
2063 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 /* Normalize f to be in the range [1.0, 2.0) */
2068 if (0.5 <= f && f < 1.0) {
2069 f *= 2.0;
2070 e--;
2071 }
2072 else if (f == 0.0)
2073 e = 0;
2074 else {
2075 PyErr_SetString(PyExc_SystemError,
2076 "frexp() result out of range");
2077 return -1;
2078 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (e >= 128)
2081 goto Overflow;
2082 else if (e < -126) {
2083 /* Gradual underflow */
2084 f = ldexp(f, 126 + e);
2085 e = 0;
2086 }
2087 else if (!(e == 0 && f == 0.0)) {
2088 e += 127;
2089 f -= 1.0; /* Get rid of leading 1 */
2090 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 f *= 8388608.0; /* 2**23 */
2093 fbits = (unsigned int)(f + 0.5); /* Round */
2094 assert(fbits <= 8388608);
2095 if (fbits >> 23) {
2096 /* The carry propagated out of a string of 23 1 bits. */
2097 fbits = 0;
2098 ++e;
2099 if (e >= 255)
2100 goto Overflow;
2101 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* First byte */
2104 *p = (sign << 7) | (e >> 1);
2105 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 /* Second byte */
2108 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2109 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 /* Third byte */
2112 *p = (fbits >> 8) & 0xFF;
2113 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 /* Fourth byte */
2116 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* Done */
2119 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
2122 else {
2123 float y = (float)x;
2124 const char *s = (char*)&y;
2125 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2128 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if ((float_format == ieee_little_endian_format && !le)
2131 || (float_format == ieee_big_endian_format && le)) {
2132 p += 3;
2133 incr = -1;
2134 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 for (i = 0; i < 4; i++) {
2137 *p = *s++;
2138 p += incr;
2139 }
2140 return 0;
2141 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002142 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 PyErr_SetString(PyExc_OverflowError,
2144 "float too large to pack with f format");
2145 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002146}
2147
2148int
2149_PyFloat_Pack8(double x, unsigned char *p, int le)
2150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (double_format == unknown_format) {
2152 unsigned char sign;
2153 int e;
2154 double f;
2155 unsigned int fhi, flo;
2156 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (le) {
2159 p += 7;
2160 incr = -1;
2161 }
Tim Peters9905b942003-03-20 20:53:32 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (x < 0) {
2164 sign = 1;
2165 x = -x;
2166 }
2167 else
2168 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 /* Normalize f to be in the range [1.0, 2.0) */
2173 if (0.5 <= f && f < 1.0) {
2174 f *= 2.0;
2175 e--;
2176 }
2177 else if (f == 0.0)
2178 e = 0;
2179 else {
2180 PyErr_SetString(PyExc_SystemError,
2181 "frexp() result out of range");
2182 return -1;
2183 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (e >= 1024)
2186 goto Overflow;
2187 else if (e < -1022) {
2188 /* Gradual underflow */
2189 f = ldexp(f, 1022 + e);
2190 e = 0;
2191 }
2192 else if (!(e == 0 && f == 0.0)) {
2193 e += 1023;
2194 f -= 1.0; /* Get rid of leading 1 */
2195 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2198 f *= 268435456.0; /* 2**28 */
2199 fhi = (unsigned int)f; /* Truncate */
2200 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 f -= (double)fhi;
2203 f *= 16777216.0; /* 2**24 */
2204 flo = (unsigned int)(f + 0.5); /* Round */
2205 assert(flo <= 16777216);
2206 if (flo >> 24) {
2207 /* The carry propagated out of a string of 24 1 bits. */
2208 flo = 0;
2209 ++fhi;
2210 if (fhi >> 28) {
2211 /* And it also progagated out of the next 28 bits. */
2212 fhi = 0;
2213 ++e;
2214 if (e >= 2047)
2215 goto Overflow;
2216 }
2217 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* First byte */
2220 *p = (sign << 7) | (e >> 4);
2221 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Second byte */
2224 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2225 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Third byte */
2228 *p = (fhi >> 16) & 0xFF;
2229 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Fourth byte */
2232 *p = (fhi >> 8) & 0xFF;
2233 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* Fifth byte */
2236 *p = fhi & 0xFF;
2237 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* Sixth byte */
2240 *p = (flo >> 16) & 0xFF;
2241 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* Seventh byte */
2244 *p = (flo >> 8) & 0xFF;
2245 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* Eighth byte */
2248 *p = flo & 0xFF;
2249 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* Done */
2252 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 Overflow:
2255 PyErr_SetString(PyExc_OverflowError,
2256 "float too large to pack with d format");
2257 return -1;
2258 }
2259 else {
2260 const char *s = (char*)&x;
2261 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if ((double_format == ieee_little_endian_format && !le)
2264 || (double_format == ieee_big_endian_format && le)) {
2265 p += 7;
2266 incr = -1;
2267 }
2268
2269 for (i = 0; i < 8; i++) {
2270 *p = *s++;
2271 p += incr;
2272 }
2273 return 0;
2274 }
Tim Peters9905b942003-03-20 20:53:32 +00002275}
2276
2277double
2278_PyFloat_Unpack4(const unsigned char *p, int le)
2279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 if (float_format == unknown_format) {
2281 unsigned char sign;
2282 int e;
2283 unsigned int f;
2284 double x;
2285 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (le) {
2288 p += 3;
2289 incr = -1;
2290 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 /* First byte */
2293 sign = (*p >> 7) & 1;
2294 e = (*p & 0x7F) << 1;
2295 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Second byte */
2298 e |= (*p >> 7) & 1;
2299 f = (*p & 0x7F) << 16;
2300 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (e == 255) {
2303 PyErr_SetString(
2304 PyExc_ValueError,
2305 "can't unpack IEEE 754 special value "
2306 "on non-IEEE platform");
2307 return -1;
2308 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Third byte */
2311 f |= *p << 8;
2312 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Fourth byte */
2315 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* XXX This sadly ignores Inf/NaN issues */
2320 if (e == 0)
2321 e = -126;
2322 else {
2323 x += 1.0;
2324 e -= 127;
2325 }
2326 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (sign)
2329 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 return x;
2332 }
2333 else {
2334 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if ((float_format == ieee_little_endian_format && !le)
2337 || (float_format == ieee_big_endian_format && le)) {
2338 char buf[4];
2339 char *d = &buf[3];
2340 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 for (i = 0; i < 4; i++) {
2343 *d-- = *p++;
2344 }
2345 memcpy(&x, buf, 4);
2346 }
2347 else {
2348 memcpy(&x, p, 4);
2349 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 return x;
2352 }
Tim Peters9905b942003-03-20 20:53:32 +00002353}
2354
2355double
2356_PyFloat_Unpack8(const unsigned char *p, int le)
2357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 if (double_format == unknown_format) {
2359 unsigned char sign;
2360 int e;
2361 unsigned int fhi, flo;
2362 double x;
2363 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 if (le) {
2366 p += 7;
2367 incr = -1;
2368 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* First byte */
2371 sign = (*p >> 7) & 1;
2372 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* Second byte */
2377 e |= (*p >> 4) & 0xF;
2378 fhi = (*p & 0xF) << 24;
2379 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 if (e == 2047) {
2382 PyErr_SetString(
2383 PyExc_ValueError,
2384 "can't unpack IEEE 754 special value "
2385 "on non-IEEE platform");
2386 return -1.0;
2387 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 /* Third byte */
2390 fhi |= *p << 16;
2391 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* Fourth byte */
2394 fhi |= *p << 8;
2395 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* Fifth byte */
2398 fhi |= *p;
2399 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 /* Sixth byte */
2402 flo = *p << 16;
2403 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* Seventh byte */
2406 flo |= *p << 8;
2407 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* Eighth byte */
2410 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2413 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 if (e == 0)
2416 e = -1022;
2417 else {
2418 x += 1.0;
2419 e -= 1023;
2420 }
2421 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 if (sign)
2424 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return x;
2427 }
2428 else {
2429 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 if ((double_format == ieee_little_endian_format && !le)
2432 || (double_format == ieee_big_endian_format && le)) {
2433 char buf[8];
2434 char *d = &buf[7];
2435 int i;
2436
2437 for (i = 0; i < 8; i++) {
2438 *d-- = *p++;
2439 }
2440 memcpy(&x, buf, 8);
2441 }
2442 else {
2443 memcpy(&x, p, 8);
2444 }
2445
2446 return x;
2447 }
Tim Peters9905b942003-03-20 20:53:32 +00002448}