blob: 6d1745e2c38b1a14be754edad6536ac55af158fa [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 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 }
201 else if (PyObject_AsCharBuffer(v, &s, &len)) {
202 PyErr_SetString(PyExc_TypeError,
203 "float() argument must be a string or a number");
204 return NULL;
205 }
206 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000207 /* strip space */
208 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000210 while (s < last - 1 && Py_ISSPACE(last[-1]))
211 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* We don't care about overflow or underflow. If the platform
213 * supports them, infinities and signed zeroes (on underflow) are
214 * fine. */
215 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000216 if (end != last) {
217 PyErr_Format(PyExc_ValueError,
218 "could not convert string to float: "
219 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 result = NULL;
221 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000222 else if (x == -1.0 && PyErr_Occurred())
223 result = NULL;
224 else
225 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000226
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000227 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000229}
230
Guido van Rossum234f9421993-06-17 12:35:49 +0000231static void
Fred Drakefd99de62000-07-09 05:02:18 +0000232float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (PyFloat_CheckExact(op)) {
235 Py_TYPE(op) = (struct _typeobject *)free_list;
236 free_list = op;
237 }
238 else
239 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000240}
241
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242double
Fred Drakefd99de62000-07-09 05:02:18 +0000243PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyNumberMethods *nb;
246 PyFloatObject *fo;
247 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (op && PyFloat_Check(op))
250 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (op == NULL) {
253 PyErr_BadArgument();
254 return -1;
255 }
Tim Petersd2364e82001-11-01 20:09:42 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
258 PyErr_SetString(PyExc_TypeError, "a float is required");
259 return -1;
260 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 fo = (PyFloatObject*) (*nb->nb_float) (op);
263 if (fo == NULL)
264 return -1;
265 if (!PyFloat_Check(fo)) {
266 PyErr_SetString(PyExc_TypeError,
267 "nb_float should return float object");
268 return -1;
269 }
Tim Petersd2364e82001-11-01 20:09:42 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 val = PyFloat_AS_DOUBLE(fo);
272 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275}
276
Neil Schemenauer32117e52001-01-04 01:44:34 +0000277/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000278 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000279 set to NULL, and the function invoking this macro returns NULL. If
280 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
281 stored in obj, and returned from the function invoking this macro.
282*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283#define CONVERT_TO_DOUBLE(obj, dbl) \
284 if (PyFloat_Check(obj)) \
285 dbl = PyFloat_AS_DOUBLE(obj); \
286 else if (convert_to_double(&(obj), &(dbl)) < 0) \
287 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000288
Eric Smith0923d1d2009-04-16 20:16:10 +0000289/* Methods */
290
Neil Schemenauer32117e52001-01-04 01:44:34 +0000291static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000292convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (PyLong_Check(obj)) {
297 *dbl = PyLong_AsDouble(obj);
298 if (*dbl == -1.0 && PyErr_Occurred()) {
299 *v = NULL;
300 return -1;
301 }
302 }
303 else {
304 Py_INCREF(Py_NotImplemented);
305 *v = Py_NotImplemented;
306 return -1;
307 }
308 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000309}
310
Eric Smith0923d1d2009-04-16 20:16:10 +0000311static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000312float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000313{
314 PyObject *result;
315 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000316 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000317 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000318 NULL);
319 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000320 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000321 result = PyUnicode_FromString(buf);
322 PyMem_Free(buf);
323 return result;
324}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000325
Tim Peters307fa782004-09-23 08:06:40 +0000326/* Comparison is pretty much a nightmare. When comparing float to float,
327 * we do it as straightforwardly (and long-windedly) as conceivable, so
328 * that, e.g., Python x == y delivers the same result as the platform
329 * C x == y when x and/or y is a NaN.
330 * When mixing float with an integer type, there's no good *uniform* approach.
331 * Converting the double to an integer obviously doesn't work, since we
332 * may lose info from fractional bits. Converting the integer to a double
333 * also has two failure modes: (1) a long int may trigger overflow (too
334 * large to fit in the dynamic range of a C double); (2) even a C long may have
335 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
336 * 63 bits of precision, but a C double probably has only 53), and then
337 * we can falsely claim equality when low-order integer bits are lost by
338 * coercion to double. So this part is painful too.
339 */
340
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000341static PyObject*
342float_richcompare(PyObject *v, PyObject *w, int op)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 double i, j;
345 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 assert(PyFloat_Check(v));
348 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 /* Switch on the type of w. Set i and j to doubles to be compared,
351 * and op to the richcomp to use.
352 */
353 if (PyFloat_Check(w))
354 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 else if (!Py_IS_FINITE(i)) {
357 if (PyLong_Check(w))
358 /* If i is an infinity, its magnitude exceeds any
359 * finite integer, so it doesn't matter which int we
360 * compare i with. If i is a NaN, similarly.
361 */
362 j = 0.0;
363 else
364 goto Unimplemented;
365 }
Tim Peters307fa782004-09-23 08:06:40 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 else if (PyLong_Check(w)) {
368 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
369 int wsign = _PyLong_Sign(w);
370 size_t nbits;
371 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (vsign != wsign) {
374 /* Magnitudes are irrelevant -- the signs alone
375 * determine the outcome.
376 */
377 i = (double)vsign;
378 j = (double)wsign;
379 goto Compare;
380 }
381 /* The signs are the same. */
382 /* Convert w to a double if it fits. In particular, 0 fits. */
383 nbits = _PyLong_NumBits(w);
384 if (nbits == (size_t)-1 && PyErr_Occurred()) {
385 /* This long is so large that size_t isn't big enough
386 * to hold the # of bits. Replace with little doubles
387 * that give the same outcome -- w is so large that
388 * its magnitude must exceed the magnitude of any
389 * finite float.
390 */
391 PyErr_Clear();
392 i = (double)vsign;
393 assert(wsign != 0);
394 j = wsign * 2.0;
395 goto Compare;
396 }
397 if (nbits <= 48) {
398 j = PyLong_AsDouble(w);
399 /* It's impossible that <= 48 bits overflowed. */
400 assert(j != -1.0 || ! PyErr_Occurred());
401 goto Compare;
402 }
403 assert(wsign != 0); /* else nbits was 0 */
404 assert(vsign != 0); /* if vsign were 0, then since wsign is
405 * not 0, we would have taken the
406 * vsign != wsign branch at the start */
407 /* We want to work with non-negative numbers. */
408 if (vsign < 0) {
409 /* "Multiply both sides" by -1; this also swaps the
410 * comparator.
411 */
412 i = -i;
413 op = _Py_SwappedOp[op];
414 }
415 assert(i > 0.0);
416 (void) frexp(i, &exponent);
417 /* exponent is the # of bits in v before the radix point;
418 * we know that nbits (the # of bits in w) > 48 at this point
419 */
420 if (exponent < 0 || (size_t)exponent < nbits) {
421 i = 1.0;
422 j = 2.0;
423 goto Compare;
424 }
425 if ((size_t)exponent > nbits) {
426 i = 2.0;
427 j = 1.0;
428 goto Compare;
429 }
430 /* v and w have the same number of bits before the radix
431 * point. Construct two longs that have the same comparison
432 * outcome.
433 */
434 {
435 double fracpart;
436 double intpart;
437 PyObject *result = NULL;
438 PyObject *one = NULL;
439 PyObject *vv = NULL;
440 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (wsign < 0) {
443 ww = PyNumber_Negative(w);
444 if (ww == NULL)
445 goto Error;
446 }
447 else
448 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 fracpart = modf(i, &intpart);
451 vv = PyLong_FromDouble(intpart);
452 if (vv == NULL)
453 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (fracpart != 0.0) {
456 /* Shift left, and or a 1 bit into vv
457 * to represent the lost fraction.
458 */
459 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 one = PyLong_FromLong(1);
462 if (one == NULL)
463 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 temp = PyNumber_Lshift(ww, one);
466 if (temp == NULL)
467 goto Error;
468 Py_DECREF(ww);
469 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 temp = PyNumber_Lshift(vv, one);
472 if (temp == NULL)
473 goto Error;
474 Py_DECREF(vv);
475 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 temp = PyNumber_Or(vv, one);
478 if (temp == NULL)
479 goto Error;
480 Py_DECREF(vv);
481 vv = temp;
482 }
Tim Peters307fa782004-09-23 08:06:40 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 r = PyObject_RichCompareBool(vv, ww, op);
485 if (r < 0)
486 goto Error;
487 result = PyBool_FromLong(r);
488 Error:
489 Py_XDECREF(vv);
490 Py_XDECREF(ww);
491 Py_XDECREF(one);
492 return result;
493 }
494 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 else /* w isn't float, int, or long */
497 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000498
499 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyFPE_START_PROTECT("richcompare", return NULL)
501 switch (op) {
502 case Py_EQ:
503 r = i == j;
504 break;
505 case Py_NE:
506 r = i != j;
507 break;
508 case Py_LE:
509 r = i <= j;
510 break;
511 case Py_GE:
512 r = i >= j;
513 break;
514 case Py_LT:
515 r = i < j;
516 break;
517 case Py_GT:
518 r = i > j;
519 break;
520 }
521 PyFPE_END_PROTECT(r)
522 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000523
524 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 Py_INCREF(Py_NotImplemented);
526 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000527}
528
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000529static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000530float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000533}
534
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000536float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 double a,b;
539 CONVERT_TO_DOUBLE(v, a);
540 CONVERT_TO_DOUBLE(w, b);
541 PyFPE_START_PROTECT("add", return 0)
542 a = a + b;
543 PyFPE_END_PROTECT(a)
544 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545}
546
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000548float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 double a,b;
551 CONVERT_TO_DOUBLE(v, a);
552 CONVERT_TO_DOUBLE(w, b);
553 PyFPE_START_PROTECT("subtract", return 0)
554 a = a - b;
555 PyFPE_END_PROTECT(a)
556 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557}
558
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000560float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 double a,b;
563 CONVERT_TO_DOUBLE(v, a);
564 CONVERT_TO_DOUBLE(w, b);
565 PyFPE_START_PROTECT("multiply", return 0)
566 a = a * b;
567 PyFPE_END_PROTECT(a)
568 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 double a,b;
575 CONVERT_TO_DOUBLE(v, a);
576 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (b == 0.0) {
578 PyErr_SetString(PyExc_ZeroDivisionError,
579 "float division by zero");
580 return NULL;
581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 PyFPE_START_PROTECT("divide", return 0)
583 a = a / b;
584 PyFPE_END_PROTECT(a)
585 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586}
587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000589float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 double vx, wx;
592 double mod;
593 CONVERT_TO_DOUBLE(v, vx);
594 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (wx == 0.0) {
596 PyErr_SetString(PyExc_ZeroDivisionError,
597 "float modulo");
598 return NULL;
599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyFPE_START_PROTECT("modulo", return 0)
601 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000602 if (mod) {
603 /* ensure the remainder has the same sign as the denominator */
604 if ((wx < 0) != (mod < 0)) {
605 mod += wx;
606 }
607 }
608 else {
609 /* the remainder is zero, and in the presence of signed zeroes
610 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000611 it has the same sign as the denominator. */
612 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
614 PyFPE_END_PROTECT(mod)
615 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616}
617
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000619float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 double vx, wx;
622 double div, mod, floordiv;
623 CONVERT_TO_DOUBLE(v, vx);
624 CONVERT_TO_DOUBLE(w, wx);
625 if (wx == 0.0) {
626 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
627 return NULL;
628 }
629 PyFPE_START_PROTECT("divmod", return 0)
630 mod = fmod(vx, wx);
631 /* fmod is typically exact, so vx-mod is *mathematically* an
632 exact multiple of wx. But this is fp arithmetic, and fp
633 vx - mod is an approximation; the result is that div may
634 not be an exact integral value after the division, although
635 it will always be very close to one.
636 */
637 div = (vx - mod) / wx;
638 if (mod) {
639 /* ensure the remainder has the same sign as the denominator */
640 if ((wx < 0) != (mod < 0)) {
641 mod += wx;
642 div -= 1.0;
643 }
644 }
645 else {
646 /* the remainder is zero, and in the presence of signed zeroes
647 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000648 it has the same sign as the denominator. */
649 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
651 /* snap quotient to nearest integral value */
652 if (div) {
653 floordiv = floor(div);
654 if (div - floordiv > 0.5)
655 floordiv += 1.0;
656 }
657 else {
658 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000659 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
661 PyFPE_END_PROTECT(floordiv)
662 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000663}
664
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000666float_floor_div(PyObject *v, PyObject *w)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 t = float_divmod(v, w);
671 if (t == NULL || t == Py_NotImplemented)
672 return t;
673 assert(PyTuple_CheckExact(t));
674 r = PyTuple_GET_ITEM(t, 0);
675 Py_INCREF(r);
676 Py_DECREF(t);
677 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000678}
679
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000680/* determine whether x is an odd integer or not; assumes that
681 x is not an infinity or nan. */
682#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
683
Tim Peters63a35712001-12-11 19:57:24 +0000684static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000685float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 double iv, iw, ix;
688 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if ((PyObject *)z != Py_None) {
691 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
692 "allowed unless all arguments are integers");
693 return NULL;
694 }
Tim Peters32f453e2001-09-03 08:35:41 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 CONVERT_TO_DOUBLE(v, iv);
697 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* Sort out special cases here instead of relying on pow() */
700 if (iw == 0) { /* v**0 is 1, even 0**0 */
701 return PyFloat_FromDouble(1.0);
702 }
703 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
704 return PyFloat_FromDouble(iv);
705 }
706 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
707 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
708 }
709 if (Py_IS_INFINITY(iw)) {
710 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
711 * abs(v) > 1 (including case where v infinite)
712 *
713 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
714 * abs(v) > 1 (including case where v infinite)
715 */
716 iv = fabs(iv);
717 if (iv == 1.0)
718 return PyFloat_FromDouble(1.0);
719 else if ((iw > 0.0) == (iv > 1.0))
720 return PyFloat_FromDouble(fabs(iw)); /* return inf */
721 else
722 return PyFloat_FromDouble(0.0);
723 }
724 if (Py_IS_INFINITY(iv)) {
725 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
726 * both cases, we need to add the appropriate sign if w is
727 * an odd integer.
728 */
729 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
730 if (iw > 0.0)
731 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
732 else
733 return PyFloat_FromDouble(iw_is_odd ?
734 copysign(0.0, iv) : 0.0);
735 }
736 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
737 (already dealt with above), and an error
738 if w is negative. */
739 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
740 if (iw < 0.0) {
741 PyErr_SetString(PyExc_ZeroDivisionError,
742 "0.0 cannot be raised to a "
743 "negative power");
744 return NULL;
745 }
746 /* use correct sign if iw is odd */
747 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
748 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (iv < 0.0) {
751 /* Whether this is an error is a mess, and bumps into libm
752 * bugs so we have to figure it out ourselves.
753 */
754 if (iw != floor(iw)) {
755 /* Negative numbers raised to fractional powers
756 * become complex.
757 */
758 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
759 }
760 /* iw is an exact integer, albeit perhaps a very large
761 * one. Replace iv by its absolute value and remember
762 * to negate the pow result if iw is odd.
763 */
764 iv = -iv;
765 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
766 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
769 /* (-1) ** large_integer also ends up here. Here's an
770 * extract from the comments for the previous
771 * implementation explaining why this special case is
772 * necessary:
773 *
774 * -1 raised to an exact integer should never be exceptional.
775 * Alas, some libms (chiefly glibc as of early 2003) return
776 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
777 * happen to be representable in a *C* integer. That's a
778 * bug.
779 */
780 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
781 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* Now iv and iw are finite, iw is nonzero, and iv is
784 * positive and not equal to 1.0. We finally allow
785 * the platform pow to step in and do the rest.
786 */
787 errno = 0;
788 PyFPE_START_PROTECT("pow", return NULL)
789 ix = pow(iv, iw);
790 PyFPE_END_PROTECT(ix)
791 Py_ADJUST_ERANGE1(ix);
792 if (negate_result)
793 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (errno != 0) {
796 /* We don't expect any errno value other than ERANGE, but
797 * the range of libm bugs appears unbounded.
798 */
799 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
800 PyExc_ValueError);
801 return NULL;
802 }
803 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804}
805
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000806#undef DOUBLE_IS_ODD_INTEGER
807
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000809float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000815float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818}
819
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000820static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000821float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000824}
825
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000826static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000827float_is_integer(PyObject *v)
828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 double x = PyFloat_AsDouble(v);
830 PyObject *o;
831
832 if (x == -1.0 && PyErr_Occurred())
833 return NULL;
834 if (!Py_IS_FINITE(x))
835 Py_RETURN_FALSE;
836 errno = 0;
837 PyFPE_START_PROTECT("is_integer", return NULL)
838 o = (floor(x) == x) ? Py_True : Py_False;
839 PyFPE_END_PROTECT(x)
840 if (errno != 0) {
841 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
842 PyExc_ValueError);
843 return NULL;
844 }
845 Py_INCREF(o);
846 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000847}
848
849#if 0
850static PyObject *
851float_is_inf(PyObject *v)
852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 double x = PyFloat_AsDouble(v);
854 if (x == -1.0 && PyErr_Occurred())
855 return NULL;
856 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000857}
858
859static PyObject *
860float_is_nan(PyObject *v)
861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 double x = PyFloat_AsDouble(v);
863 if (x == -1.0 && PyErr_Occurred())
864 return NULL;
865 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000866}
867
868static PyObject *
869float_is_finite(PyObject *v)
870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 double x = PyFloat_AsDouble(v);
872 if (x == -1.0 && PyErr_Occurred())
873 return NULL;
874 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000875}
876#endif
877
878static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000879float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 double x = PyFloat_AsDouble(v);
882 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 (void)modf(x, &wholepart);
885 /* Try to get out cheap if this fits in a Python int. The attempt
886 * to cast to long must be protected, as C doesn't define what
887 * happens if the double is too big to fit in a long. Some rare
888 * systems raise an exception then (RISCOS was mentioned as one,
889 * and someone using a non-default option on Sun also bumped into
890 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
891 * still be vulnerable: if a long has more bits of precision than
892 * a double, casting MIN/MAX to double may yield an approximation,
893 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
894 * yield true from the C expression wholepart<=LONG_MAX, despite
895 * that wholepart is actually greater than LONG_MAX.
896 */
897 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
898 const long aslong = (long)wholepart;
899 return PyLong_FromLong(aslong);
900 }
901 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000902}
903
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000904/* double_round: rounds a finite double to the closest multiple of
905 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
906 ndigits <= 323). Returns a Python float, or sets a Python error and
907 returns NULL on failure (OverflowError and memory errors are possible). */
908
909#ifndef PY_NO_SHORT_FLOAT_REPR
910/* version of double_round that uses the correctly-rounded string<->double
911 conversions from Python/dtoa.c */
912
913static PyObject *
914double_round(double x, int ndigits) {
915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 double rounded;
917 Py_ssize_t buflen, mybuflen=100;
918 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
919 int decpt, sign;
920 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* round to a decimal string */
923 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
924 if (buf == NULL) {
925 PyErr_NoMemory();
926 return NULL;
927 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
930 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
931 buflen = buf_end - buf;
932 if (buflen + 8 > mybuflen) {
933 mybuflen = buflen+8;
934 mybuf = (char *)PyMem_Malloc(mybuflen);
935 if (mybuf == NULL) {
936 PyErr_NoMemory();
937 goto exit;
938 }
939 }
940 /* copy buf to mybuf, adding exponent, sign and leading 0 */
941 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
942 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* and convert the resulting string back to a double */
945 errno = 0;
946 rounded = _Py_dg_strtod(mybuf, NULL);
947 if (errno == ERANGE && fabs(rounded) >= 1.)
948 PyErr_SetString(PyExc_OverflowError,
949 "rounded value too large to represent");
950 else
951 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* done computing value; now clean up */
954 if (mybuf != shortbuf)
955 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000956 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 _Py_dg_freedtoa(buf);
958 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000959}
960
961#else /* PY_NO_SHORT_FLOAT_REPR */
962
963/* fallback version, to be used when correctly rounded binary<->decimal
964 conversions aren't available */
965
966static PyObject *
967double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 double pow1, pow2, y, z;
969 if (ndigits >= 0) {
970 if (ndigits > 22) {
971 /* pow1 and pow2 are each safe from overflow, but
972 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
973 pow1 = pow(10.0, (double)(ndigits-22));
974 pow2 = 1e22;
975 }
976 else {
977 pow1 = pow(10.0, (double)ndigits);
978 pow2 = 1.0;
979 }
980 y = (x*pow1)*pow2;
981 /* if y overflows, then rounded value is exactly x */
982 if (!Py_IS_FINITE(y))
983 return PyFloat_FromDouble(x);
984 }
985 else {
986 pow1 = pow(10.0, (double)-ndigits);
987 pow2 = 1.0; /* unused; silences a gcc compiler warning */
988 y = x / pow1;
989 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 z = round(y);
992 if (fabs(y-z) == 0.5)
993 /* halfway between two integers; use round-half-even */
994 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (ndigits >= 0)
997 z = (z / pow2) / pow1;
998 else
999 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 /* if computation resulted in overflow, raise OverflowError */
1002 if (!Py_IS_FINITE(z)) {
1003 PyErr_SetString(PyExc_OverflowError,
1004 "overflow occurred during round");
1005 return NULL;
1006 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001009}
1010
1011#endif /* PY_NO_SHORT_FLOAT_REPR */
1012
1013/* round a Python float v to the closest multiple of 10**-ndigits */
1014
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001015static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001016float_round(PyObject *v, PyObject *args)
1017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 double x, rounded;
1019 PyObject *o_ndigits = NULL;
1020 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 x = PyFloat_AsDouble(v);
1023 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1024 return NULL;
1025 if (o_ndigits == NULL) {
1026 /* single-argument round: round to nearest integer */
1027 rounded = round(x);
1028 if (fabs(x-rounded) == 0.5)
1029 /* halfway case: round to even */
1030 rounded = 2.0*round(x/2.0);
1031 return PyLong_FromDouble(rounded);
1032 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 /* interpret second argument as a Py_ssize_t; clips on overflow */
1035 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1036 if (ndigits == -1 && PyErr_Occurred())
1037 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* nans and infinities round to themselves */
1040 if (!Py_IS_FINITE(x))
1041 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1044 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1045 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001046#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1047#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (ndigits > NDIGITS_MAX)
1049 /* return x */
1050 return PyFloat_FromDouble(x);
1051 else if (ndigits < NDIGITS_MIN)
1052 /* return 0.0, but with sign of x */
1053 return PyFloat_FromDouble(0.0*x);
1054 else
1055 /* finite x, and ndigits is not unreasonably large */
1056 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001057#undef NDIGITS_MAX
1058#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001059}
1060
1061static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001062float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (PyFloat_CheckExact(v))
1065 Py_INCREF(v);
1066 else
1067 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1068 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001069}
1070
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001071/* turn ASCII hex characters into integer values and vice versa */
1072
1073static char
1074char_from_hex(int x)
1075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 assert(0 <= x && x < 16);
1077 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001078}
1079
1080static int
1081hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 int x;
1083 switch(c) {
1084 case '0':
1085 x = 0;
1086 break;
1087 case '1':
1088 x = 1;
1089 break;
1090 case '2':
1091 x = 2;
1092 break;
1093 case '3':
1094 x = 3;
1095 break;
1096 case '4':
1097 x = 4;
1098 break;
1099 case '5':
1100 x = 5;
1101 break;
1102 case '6':
1103 x = 6;
1104 break;
1105 case '7':
1106 x = 7;
1107 break;
1108 case '8':
1109 x = 8;
1110 break;
1111 case '9':
1112 x = 9;
1113 break;
1114 case 'a':
1115 case 'A':
1116 x = 10;
1117 break;
1118 case 'b':
1119 case 'B':
1120 x = 11;
1121 break;
1122 case 'c':
1123 case 'C':
1124 x = 12;
1125 break;
1126 case 'd':
1127 case 'D':
1128 x = 13;
1129 break;
1130 case 'e':
1131 case 'E':
1132 x = 14;
1133 break;
1134 case 'f':
1135 case 'F':
1136 x = 15;
1137 break;
1138 default:
1139 x = -1;
1140 break;
1141 }
1142 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001143}
1144
1145/* convert a float to a hexadecimal string */
1146
1147/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1148 of the form 4k+1. */
1149#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1150
1151static PyObject *
1152float_hex(PyObject *v)
1153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 double x, m;
1155 int e, shift, i, si, esign;
1156 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1157 trailing NUL byte. */
1158 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001163 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001166 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 return PyUnicode_FromString("-0x0.0p+0");
1168 else
1169 return PyUnicode_FromString("0x0.0p+0");
1170 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 m = frexp(fabs(x), &e);
1173 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1174 m = ldexp(m, shift);
1175 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 si = 0;
1178 s[si] = char_from_hex((int)m);
1179 si++;
1180 m -= (int)m;
1181 s[si] = '.';
1182 si++;
1183 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1184 m *= 16.0;
1185 s[si] = char_from_hex((int)m);
1186 si++;
1187 m -= (int)m;
1188 }
1189 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (e < 0) {
1192 esign = (int)'-';
1193 e = -e;
1194 }
1195 else
1196 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (x < 0.0)
1199 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1200 else
1201 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001202}
1203
1204PyDoc_STRVAR(float_hex_doc,
1205"float.hex() -> string\n\
1206\n\
1207Return a hexadecimal representation of a floating-point number.\n\
1208>>> (-0.1).hex()\n\
1209'-0x1.999999999999ap-4'\n\
1210>>> 3.14159.hex()\n\
1211'0x1.921f9f01b866ep+1'");
1212
1213/* Convert a hexadecimal string to a float. */
1214
1215static PyObject *
1216float_fromhex(PyObject *cls, PyObject *arg)
1217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyObject *result_as_float, *result;
1219 double x;
1220 long exp, top_exp, lsb, key_digit;
1221 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1222 int half_eps, digit, round_up, negate=0;
1223 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /*
1226 * For the sake of simplicity and correctness, we impose an artificial
1227 * limit on ndigits, the total number of hex digits in the coefficient
1228 * The limit is chosen to ensure that, writing exp for the exponent,
1229 *
1230 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1231 * guaranteed to overflow (provided it's nonzero)
1232 *
1233 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1234 * guaranteed to underflow to 0.
1235 *
1236 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1237 * overflow in the calculation of exp and top_exp below.
1238 *
1239 * More specifically, ndigits is assumed to satisfy the following
1240 * inequalities:
1241 *
1242 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1243 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1244 *
1245 * If either of these inequalities is not satisfied, a ValueError is
1246 * raised. Otherwise, write x for the value of the hex string, and
1247 * assume x is nonzero. Then
1248 *
1249 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1250 *
1251 * Now if exp > LONG_MAX/2 then:
1252 *
1253 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1254 * = DBL_MAX_EXP
1255 *
1256 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1257 * double, so overflows. If exp < LONG_MIN/2, then
1258 *
1259 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1260 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1261 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1262 *
1263 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1264 * when converted to a C double.
1265 *
1266 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1267 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1268 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 s = _PyUnicode_AsStringAndSize(arg, &length);
1271 if (s == NULL)
1272 return NULL;
1273 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 /********************
1276 * Parse the string *
1277 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* leading whitespace */
1280 while (Py_ISSPACE(*s))
1281 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /* infinities and nans */
1284 x = _Py_parse_inf_or_nan(s, &coeff_end);
1285 if (coeff_end != s) {
1286 s = coeff_end;
1287 goto finished;
1288 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 /* optional sign */
1291 if (*s == '-') {
1292 s++;
1293 negate = 1;
1294 }
1295 else if (*s == '+')
1296 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 /* [0x] */
1299 s_store = s;
1300 if (*s == '0') {
1301 s++;
1302 if (*s == 'x' || *s == 'X')
1303 s++;
1304 else
1305 s = s_store;
1306 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 /* coefficient: <integer> [. <fraction>] */
1309 coeff_start = s;
1310 while (hex_from_char(*s) >= 0)
1311 s++;
1312 s_store = s;
1313 if (*s == '.') {
1314 s++;
1315 while (hex_from_char(*s) >= 0)
1316 s++;
1317 coeff_end = s-1;
1318 }
1319 else
1320 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 /* ndigits = total # of hex digits; fdigits = # after point */
1323 ndigits = coeff_end - coeff_start;
1324 fdigits = coeff_end - s_store;
1325 if (ndigits == 0)
1326 goto parse_error;
1327 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1328 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1329 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* [p <exponent>] */
1332 if (*s == 'p' || *s == 'P') {
1333 s++;
1334 exp_start = s;
1335 if (*s == '-' || *s == '+')
1336 s++;
1337 if (!('0' <= *s && *s <= '9'))
1338 goto parse_error;
1339 s++;
1340 while ('0' <= *s && *s <= '9')
1341 s++;
1342 exp = strtol(exp_start, NULL, 10);
1343 }
1344 else
1345 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001346
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1349 coeff_end-(j) : \
1350 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /*******************************************
1353 * Compute rounded value of the hex string *
1354 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 /* Discard leading zeros, and catch extreme overflow and underflow */
1357 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1358 ndigits--;
1359 if (ndigits == 0 || exp < LONG_MIN/2) {
1360 x = 0.0;
1361 goto finished;
1362 }
1363 if (exp > LONG_MAX/2)
1364 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* Adjust exponent for fractional part. */
1367 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1370 top_exp = exp + 4*((long)ndigits - 1);
1371 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1372 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 /* catch almost all nonextreme cases of overflow and underflow here */
1375 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1376 x = 0.0;
1377 goto finished;
1378 }
1379 if (top_exp > DBL_MAX_EXP)
1380 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* lsb = exponent of least significant bit of the *rounded* value.
1383 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1384 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 x = 0.0;
1387 if (exp >= lsb) {
1388 /* no rounding required */
1389 for (i = ndigits-1; i >= 0; i--)
1390 x = 16.0*x + HEX_DIGIT(i);
1391 x = ldexp(x, (int)(exp));
1392 goto finished;
1393 }
1394 /* rounding required. key_digit is the index of the hex digit
1395 containing the first bit to be rounded away. */
1396 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1397 key_digit = (lsb - exp - 1) / 4;
1398 for (i = ndigits-1; i > key_digit; i--)
1399 x = 16.0*x + HEX_DIGIT(i);
1400 digit = HEX_DIGIT(key_digit);
1401 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1404 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1405 if ((digit & half_eps) != 0) {
1406 round_up = 0;
1407 if ((digit & (3*half_eps-1)) != 0 ||
1408 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1409 round_up = 1;
1410 else
1411 for (i = key_digit-1; i >= 0; i--)
1412 if (HEX_DIGIT(i) != 0) {
1413 round_up = 1;
1414 break;
1415 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001416 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 x += 2*half_eps;
1418 if (top_exp == DBL_MAX_EXP &&
1419 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1420 /* overflow corner case: pre-rounded value <
1421 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1422 goto overflow_error;
1423 }
1424 }
1425 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001426
1427 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* optional trailing whitespace leading to the end of the string */
1429 while (Py_ISSPACE(*s))
1430 s++;
1431 if (s != s_end)
1432 goto parse_error;
1433 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1434 if (result_as_float == NULL)
1435 return NULL;
1436 result = PyObject_CallObject(cls, result_as_float);
1437 Py_DECREF(result_as_float);
1438 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001439
1440 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyErr_SetString(PyExc_OverflowError,
1442 "hexadecimal value too large to represent as a float");
1443 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
1445 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyErr_SetString(PyExc_ValueError,
1447 "invalid hexadecimal floating-point string");
1448 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001449
1450 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyErr_SetString(PyExc_ValueError,
1452 "hexadecimal string too long to convert");
1453 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001454}
1455
1456PyDoc_STRVAR(float_fromhex_doc,
1457"float.fromhex(string) -> float\n\
1458\n\
1459Create a floating-point number from a hexadecimal string.\n\
1460>>> float.fromhex('0x1.ffffp10')\n\
14612047.984375\n\
1462>>> float.fromhex('-0x1p-1074')\n\
1463-4.9406564584124654e-324");
1464
1465
Christian Heimes26855632008-01-27 23:50:43 +00001466static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001467float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 double self;
1470 double float_part;
1471 int exponent;
1472 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 PyObject *prev;
1475 PyObject *py_exponent = NULL;
1476 PyObject *numerator = NULL;
1477 PyObject *denominator = NULL;
1478 PyObject *result_pair = NULL;
1479 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001480
1481#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 prev = obj; \
1483 obj = call; \
1484 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (Py_IS_INFINITY(self)) {
1489 PyErr_SetString(PyExc_OverflowError,
1490 "Cannot pass infinity to float.as_integer_ratio.");
1491 return NULL;
1492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (Py_IS_NAN(self)) {
1494 PyErr_SetString(PyExc_ValueError,
1495 "Cannot pass NaN to float.as_integer_ratio.");
1496 return NULL;
1497 }
Christian Heimes26855632008-01-27 23:50:43 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1500 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1501 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1504 float_part *= 2.0;
1505 exponent--;
1506 }
1507 /* self == float_part * 2**exponent exactly and float_part is integral.
1508 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1509 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 numerator = PyLong_FromDouble(float_part);
1512 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* fold in 2**exponent */
1515 denominator = PyLong_FromLong(1);
1516 py_exponent = PyLong_FromLong(labs((long)exponent));
1517 if (py_exponent == NULL) goto error;
1518 INPLACE_UPDATE(py_exponent,
1519 long_methods->nb_lshift(denominator, py_exponent));
1520 if (py_exponent == NULL) goto error;
1521 if (exponent > 0) {
1522 INPLACE_UPDATE(numerator,
1523 long_methods->nb_multiply(numerator, py_exponent));
1524 if (numerator == NULL) goto error;
1525 }
1526 else {
1527 Py_DECREF(denominator);
1528 denominator = py_exponent;
1529 py_exponent = NULL;
1530 }
1531
1532 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001533
1534#undef INPLACE_UPDATE
1535error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 Py_XDECREF(py_exponent);
1537 Py_XDECREF(denominator);
1538 Py_XDECREF(numerator);
1539 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001540}
1541
1542PyDoc_STRVAR(float_as_integer_ratio_doc,
1543"float.as_integer_ratio() -> (int, int)\n"
1544"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001545"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1546"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001547"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001548"\n"
1549">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001550"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001551">>> (0.0).as_integer_ratio()\n"
1552"(0, 1)\n"
1553">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001554"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001555
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001556
Jeremy Hylton938ace62002-07-17 16:30:39 +00001557static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001558float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1559
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560static PyObject *
1561float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 PyObject *x = Py_False; /* Integer zero */
1564 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 if (type != &PyFloat_Type)
1567 return float_subtype_new(type, args, kwds); /* Wimp out */
1568 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1569 return NULL;
1570 /* If it's a string, but not a string subclass, use
1571 PyFloat_FromString. */
1572 if (PyUnicode_CheckExact(x))
1573 return PyFloat_FromString(x);
1574 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575}
1576
Guido van Rossumbef14172001-08-29 15:47:46 +00001577/* Wimpy, slow approach to tp_new calls for subtypes of float:
1578 first create a regular float from whatever arguments we got,
1579 then allocate a subtype instance and initialize its ob_fval
1580 from the regular float. The regular float is then thrown away.
1581*/
1582static PyObject *
1583float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 assert(PyType_IsSubtype(type, &PyFloat_Type));
1588 tmp = float_new(&PyFloat_Type, args, kwds);
1589 if (tmp == NULL)
1590 return NULL;
1591 assert(PyFloat_CheckExact(tmp));
1592 newobj = type->tp_alloc(type, 0);
1593 if (newobj == NULL) {
1594 Py_DECREF(tmp);
1595 return NULL;
1596 }
1597 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1598 Py_DECREF(tmp);
1599 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001600}
1601
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001602static PyObject *
1603float_getnewargs(PyFloatObject *v)
1604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001606}
1607
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001608/* this is for the benefit of the pack/unpack routines below */
1609
1610typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001612} float_format_type;
1613
1614static float_format_type double_format, float_format;
1615static float_format_type detected_double_format, detected_float_format;
1616
1617static PyObject *
1618float_getformat(PyTypeObject *v, PyObject* arg)
1619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 char* s;
1621 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (!PyUnicode_Check(arg)) {
1624 PyErr_Format(PyExc_TypeError,
1625 "__getformat__() argument must be string, not %.500s",
1626 Py_TYPE(arg)->tp_name);
1627 return NULL;
1628 }
1629 s = _PyUnicode_AsString(arg);
1630 if (s == NULL)
1631 return NULL;
1632 if (strcmp(s, "double") == 0) {
1633 r = double_format;
1634 }
1635 else if (strcmp(s, "float") == 0) {
1636 r = float_format;
1637 }
1638 else {
1639 PyErr_SetString(PyExc_ValueError,
1640 "__getformat__() argument 1 must be "
1641 "'double' or 'float'");
1642 return NULL;
1643 }
1644
1645 switch (r) {
1646 case unknown_format:
1647 return PyUnicode_FromString("unknown");
1648 case ieee_little_endian_format:
1649 return PyUnicode_FromString("IEEE, little-endian");
1650 case ieee_big_endian_format:
1651 return PyUnicode_FromString("IEEE, big-endian");
1652 default:
1653 Py_FatalError("insane float_format or double_format");
1654 return NULL;
1655 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001656}
1657
1658PyDoc_STRVAR(float_getformat_doc,
1659"float.__getformat__(typestr) -> string\n"
1660"\n"
1661"You probably don't want to use this function. It exists mainly to be\n"
1662"used in Python's test suite.\n"
1663"\n"
1664"typestr must be 'double' or 'float'. This function returns whichever of\n"
1665"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1666"format of floating point numbers used by the C type named by typestr.");
1667
1668static PyObject *
1669float_setformat(PyTypeObject *v, PyObject* args)
1670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 char* typestr;
1672 char* format;
1673 float_format_type f;
1674 float_format_type detected;
1675 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1678 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (strcmp(typestr, "double") == 0) {
1681 p = &double_format;
1682 detected = detected_double_format;
1683 }
1684 else if (strcmp(typestr, "float") == 0) {
1685 p = &float_format;
1686 detected = detected_float_format;
1687 }
1688 else {
1689 PyErr_SetString(PyExc_ValueError,
1690 "__setformat__() argument 1 must "
1691 "be 'double' or 'float'");
1692 return NULL;
1693 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 if (strcmp(format, "unknown") == 0) {
1696 f = unknown_format;
1697 }
1698 else if (strcmp(format, "IEEE, little-endian") == 0) {
1699 f = ieee_little_endian_format;
1700 }
1701 else if (strcmp(format, "IEEE, big-endian") == 0) {
1702 f = ieee_big_endian_format;
1703 }
1704 else {
1705 PyErr_SetString(PyExc_ValueError,
1706 "__setformat__() argument 2 must be "
1707 "'unknown', 'IEEE, little-endian' or "
1708 "'IEEE, big-endian'");
1709 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (f != unknown_format && f != detected) {
1714 PyErr_Format(PyExc_ValueError,
1715 "can only set %s format to 'unknown' or the "
1716 "detected platform value", typestr);
1717 return NULL;
1718 }
1719
1720 *p = f;
1721 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001722}
1723
1724PyDoc_STRVAR(float_setformat_doc,
1725"float.__setformat__(typestr, fmt) -> None\n"
1726"\n"
1727"You probably don't want to use this function. It exists mainly to be\n"
1728"used in Python's test suite.\n"
1729"\n"
1730"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1731"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1732"one of the latter two if it appears to match the underlying C reality.\n"
1733"\n"
1734"Overrides the automatic determination of C-level floating point type.\n"
1735"This affects how floats are converted to and from binary strings.");
1736
Guido van Rossumb43daf72007-08-01 18:08:08 +00001737static PyObject *
1738float_getzero(PyObject *v, void *closure)
1739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001741}
1742
Eric Smith8c663262007-08-25 02:26:07 +00001743static PyObject *
1744float__format__(PyObject *self, PyObject *args)
1745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1749 return NULL;
1750 return _PyFloat_FormatAdvanced(self,
1751 PyUnicode_AS_UNICODE(format_spec),
1752 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001753}
1754
1755PyDoc_STRVAR(float__format__doc,
1756"float.__format__(format_spec) -> string\n"
1757"\n"
1758"Formats the float according to format_spec.");
1759
1760
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001761static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1763 "Returns self, the complex conjugate of any float."},
1764 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1765 "Returns the Integral closest to x between 0 and x."},
1766 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1767 "Returns the Integral closest to x, rounding half toward even.\n"
1768 "When an argument is passed, works like built-in round(x, ndigits)."},
1769 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1770 float_as_integer_ratio_doc},
1771 {"fromhex", (PyCFunction)float_fromhex,
1772 METH_O|METH_CLASS, float_fromhex_doc},
1773 {"hex", (PyCFunction)float_hex,
1774 METH_NOARGS, float_hex_doc},
1775 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1776 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001777#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1779 "Returns True if the float is positive or negative infinite."},
1780 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1781 "Returns True if the float is finite, neither infinite nor NaN."},
1782 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1783 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001784#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1786 {"__getformat__", (PyCFunction)float_getformat,
1787 METH_O|METH_CLASS, float_getformat_doc},
1788 {"__setformat__", (PyCFunction)float_setformat,
1789 METH_VARARGS|METH_CLASS, float_setformat_doc},
1790 {"__format__", (PyCFunction)float__format__,
1791 METH_VARARGS, float__format__doc},
1792 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001793};
1794
Guido van Rossumb43daf72007-08-01 18:08:08 +00001795static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001797 (getter)float_float, (setter)NULL,
1798 "the real part of a complex number",
1799 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001801 (getter)float_getzero, (setter)NULL,
1802 "the imaginary part of a complex number",
1803 NULL},
1804 {NULL} /* Sentinel */
1805};
1806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001807PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808"float(x) -> floating point number\n\
1809\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001810Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811
1812
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001813static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 float_add, /*nb_add*/
1815 float_sub, /*nb_subtract*/
1816 float_mul, /*nb_multiply*/
1817 float_rem, /*nb_remainder*/
1818 float_divmod, /*nb_divmod*/
1819 float_pow, /*nb_power*/
1820 (unaryfunc)float_neg, /*nb_negative*/
1821 (unaryfunc)float_float, /*nb_positive*/
1822 (unaryfunc)float_abs, /*nb_absolute*/
1823 (inquiry)float_bool, /*nb_bool*/
1824 0, /*nb_invert*/
1825 0, /*nb_lshift*/
1826 0, /*nb_rshift*/
1827 0, /*nb_and*/
1828 0, /*nb_xor*/
1829 0, /*nb_or*/
1830 float_trunc, /*nb_int*/
1831 0, /*nb_reserved*/
1832 float_float, /*nb_float*/
1833 0, /* nb_inplace_add */
1834 0, /* nb_inplace_subtract */
1835 0, /* nb_inplace_multiply */
1836 0, /* nb_inplace_remainder */
1837 0, /* nb_inplace_power */
1838 0, /* nb_inplace_lshift */
1839 0, /* nb_inplace_rshift */
1840 0, /* nb_inplace_and */
1841 0, /* nb_inplace_xor */
1842 0, /* nb_inplace_or */
1843 float_floor_div, /* nb_floor_divide */
1844 float_div, /* nb_true_divide */
1845 0, /* nb_inplace_floor_divide */
1846 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847};
1848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1851 "float",
1852 sizeof(PyFloatObject),
1853 0,
1854 (destructor)float_dealloc, /* tp_dealloc */
1855 0, /* tp_print */
1856 0, /* tp_getattr */
1857 0, /* tp_setattr */
1858 0, /* tp_reserved */
1859 (reprfunc)float_repr, /* tp_repr */
1860 &float_as_number, /* tp_as_number */
1861 0, /* tp_as_sequence */
1862 0, /* tp_as_mapping */
1863 (hashfunc)float_hash, /* tp_hash */
1864 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001865 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 PyObject_GenericGetAttr, /* tp_getattro */
1867 0, /* tp_setattro */
1868 0, /* tp_as_buffer */
1869 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1870 float_doc, /* tp_doc */
1871 0, /* tp_traverse */
1872 0, /* tp_clear */
1873 float_richcompare, /* tp_richcompare */
1874 0, /* tp_weaklistoffset */
1875 0, /* tp_iter */
1876 0, /* tp_iternext */
1877 float_methods, /* tp_methods */
1878 0, /* tp_members */
1879 float_getset, /* tp_getset */
1880 0, /* tp_base */
1881 0, /* tp_dict */
1882 0, /* tp_descr_get */
1883 0, /* tp_descr_set */
1884 0, /* tp_dictoffset */
1885 0, /* tp_init */
1886 0, /* tp_alloc */
1887 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001888};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001889
1890void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001891_PyFloat_Init(void)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 /* We attempt to determine if this machine is using IEEE
1894 floating point formats by peering at the bits of some
1895 carefully chosen values. If it looks like we are on an
1896 IEEE platform, the float packing/unpacking routines can
1897 just copy bits, if not they resort to arithmetic & shifts
1898 and masks. The shifts & masks approach works on all finite
1899 values, but what happens to infinities, NaNs and signed
1900 zeroes on packing is an accident, and attempting to unpack
1901 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 Note that if we're on some whacked-out platform which uses
1904 IEEE formats but isn't strictly little-endian or big-
1905 endian, we will fall back to the portable shifts & masks
1906 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907
1908#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 {
1910 double x = 9006104071832581.0;
1911 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1912 detected_double_format = ieee_big_endian_format;
1913 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1914 detected_double_format = ieee_little_endian_format;
1915 else
1916 detected_double_format = unknown_format;
1917 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001918#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001920#endif
1921
1922#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 {
1924 float y = 16711938.0;
1925 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1926 detected_float_format = ieee_big_endian_format;
1927 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1928 detected_float_format = ieee_little_endian_format;
1929 else
1930 detected_float_format = unknown_format;
1931 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001932#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001934#endif
1935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 double_format = detected_double_format;
1937 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 /* Init float info */
1940 if (FloatInfoType.tp_name == 0)
1941 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001942}
1943
Georg Brandl2ee470f2008-07-16 12:55:28 +00001944int
1945PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyFloatObject *p;
1948 PyFloatBlock *list, *next;
1949 int i;
1950 int u; /* remaining unfreed floats per block */
1951 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 list = block_list;
1954 block_list = NULL;
1955 free_list = NULL;
1956 while (list != NULL) {
1957 u = 0;
1958 for (i = 0, p = &list->objects[0];
1959 i < N_FLOATOBJECTS;
1960 i++, p++) {
1961 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1962 u++;
1963 }
1964 next = list->next;
1965 if (u) {
1966 list->next = block_list;
1967 block_list = list;
1968 for (i = 0, p = &list->objects[0];
1969 i < N_FLOATOBJECTS;
1970 i++, p++) {
1971 if (!PyFloat_CheckExact(p) ||
1972 Py_REFCNT(p) == 0) {
1973 Py_TYPE(p) = (struct _typeobject *)
1974 free_list;
1975 free_list = p;
1976 }
1977 }
1978 }
1979 else {
1980 PyMem_FREE(list);
1981 }
1982 freelist_size += u;
1983 list = next;
1984 }
1985 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001986}
1987
1988void
1989PyFloat_Fini(void)
1990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 PyFloatObject *p;
1992 PyFloatBlock *list;
1993 int i;
1994 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (!Py_VerboseFlag)
1999 return;
2000 fprintf(stderr, "# cleanup floats");
2001 if (!u) {
2002 fprintf(stderr, "\n");
2003 }
2004 else {
2005 fprintf(stderr,
2006 ": %d unfreed float%s\n",
2007 u, u == 1 ? "" : "s");
2008 }
2009 if (Py_VerboseFlag > 1) {
2010 list = block_list;
2011 while (list != NULL) {
2012 for (i = 0, p = &list->objects[0];
2013 i < N_FLOATOBJECTS;
2014 i++, p++) {
2015 if (PyFloat_CheckExact(p) &&
2016 Py_REFCNT(p) != 0) {
2017 char *buf = PyOS_double_to_string(
2018 PyFloat_AS_DOUBLE(p), 'r',
2019 0, 0, NULL);
2020 if (buf) {
2021 /* XXX(twouters) cast
2022 refcount to long
2023 until %zd is
2024 universally
2025 available
2026 */
2027 fprintf(stderr,
2028 "# <float at %p, refcnt=%ld, val=%s>\n",
2029 p, (long)Py_REFCNT(p), buf);
2030 PyMem_Free(buf);
2031 }
2032 }
2033 }
2034 list = list->next;
2035 }
2036 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002037}
Tim Peters9905b942003-03-20 20:53:32 +00002038
2039/*----------------------------------------------------------------------------
2040 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002041 */
2042int
2043_PyFloat_Pack4(double x, unsigned char *p, int le)
2044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 if (float_format == unknown_format) {
2046 unsigned char sign;
2047 int e;
2048 double f;
2049 unsigned int fbits;
2050 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (le) {
2053 p += 3;
2054 incr = -1;
2055 }
Tim Peters9905b942003-03-20 20:53:32 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (x < 0) {
2058 sign = 1;
2059 x = -x;
2060 }
2061 else
2062 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* Normalize f to be in the range [1.0, 2.0) */
2067 if (0.5 <= f && f < 1.0) {
2068 f *= 2.0;
2069 e--;
2070 }
2071 else if (f == 0.0)
2072 e = 0;
2073 else {
2074 PyErr_SetString(PyExc_SystemError,
2075 "frexp() result out of range");
2076 return -1;
2077 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (e >= 128)
2080 goto Overflow;
2081 else if (e < -126) {
2082 /* Gradual underflow */
2083 f = ldexp(f, 126 + e);
2084 e = 0;
2085 }
2086 else if (!(e == 0 && f == 0.0)) {
2087 e += 127;
2088 f -= 1.0; /* Get rid of leading 1 */
2089 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 f *= 8388608.0; /* 2**23 */
2092 fbits = (unsigned int)(f + 0.5); /* Round */
2093 assert(fbits <= 8388608);
2094 if (fbits >> 23) {
2095 /* The carry propagated out of a string of 23 1 bits. */
2096 fbits = 0;
2097 ++e;
2098 if (e >= 255)
2099 goto Overflow;
2100 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* First byte */
2103 *p = (sign << 7) | (e >> 1);
2104 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* Second byte */
2107 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2108 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* Third byte */
2111 *p = (fbits >> 8) & 0xFF;
2112 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Fourth byte */
2115 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 /* Done */
2118 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 }
2121 else {
2122 float y = (float)x;
2123 const char *s = (char*)&y;
2124 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2127 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if ((float_format == ieee_little_endian_format && !le)
2130 || (float_format == ieee_big_endian_format && le)) {
2131 p += 3;
2132 incr = -1;
2133 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 for (i = 0; i < 4; i++) {
2136 *p = *s++;
2137 p += incr;
2138 }
2139 return 0;
2140 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002141 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 PyErr_SetString(PyExc_OverflowError,
2143 "float too large to pack with f format");
2144 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002145}
2146
2147int
2148_PyFloat_Pack8(double x, unsigned char *p, int le)
2149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (double_format == unknown_format) {
2151 unsigned char sign;
2152 int e;
2153 double f;
2154 unsigned int fhi, flo;
2155 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (le) {
2158 p += 7;
2159 incr = -1;
2160 }
Tim Peters9905b942003-03-20 20:53:32 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (x < 0) {
2163 sign = 1;
2164 x = -x;
2165 }
2166 else
2167 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Normalize f to be in the range [1.0, 2.0) */
2172 if (0.5 <= f && f < 1.0) {
2173 f *= 2.0;
2174 e--;
2175 }
2176 else if (f == 0.0)
2177 e = 0;
2178 else {
2179 PyErr_SetString(PyExc_SystemError,
2180 "frexp() result out of range");
2181 return -1;
2182 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (e >= 1024)
2185 goto Overflow;
2186 else if (e < -1022) {
2187 /* Gradual underflow */
2188 f = ldexp(f, 1022 + e);
2189 e = 0;
2190 }
2191 else if (!(e == 0 && f == 0.0)) {
2192 e += 1023;
2193 f -= 1.0; /* Get rid of leading 1 */
2194 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2197 f *= 268435456.0; /* 2**28 */
2198 fhi = (unsigned int)f; /* Truncate */
2199 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 f -= (double)fhi;
2202 f *= 16777216.0; /* 2**24 */
2203 flo = (unsigned int)(f + 0.5); /* Round */
2204 assert(flo <= 16777216);
2205 if (flo >> 24) {
2206 /* The carry propagated out of a string of 24 1 bits. */
2207 flo = 0;
2208 ++fhi;
2209 if (fhi >> 28) {
2210 /* And it also progagated out of the next 28 bits. */
2211 fhi = 0;
2212 ++e;
2213 if (e >= 2047)
2214 goto Overflow;
2215 }
2216 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* First byte */
2219 *p = (sign << 7) | (e >> 4);
2220 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Second byte */
2223 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2224 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Third byte */
2227 *p = (fhi >> 16) & 0xFF;
2228 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Fourth byte */
2231 *p = (fhi >> 8) & 0xFF;
2232 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Fifth byte */
2235 *p = fhi & 0xFF;
2236 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Sixth byte */
2239 *p = (flo >> 16) & 0xFF;
2240 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Seventh byte */
2243 *p = (flo >> 8) & 0xFF;
2244 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Eighth byte */
2247 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002248 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* Done */
2251 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 Overflow:
2254 PyErr_SetString(PyExc_OverflowError,
2255 "float too large to pack with d format");
2256 return -1;
2257 }
2258 else {
2259 const char *s = (char*)&x;
2260 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if ((double_format == ieee_little_endian_format && !le)
2263 || (double_format == ieee_big_endian_format && le)) {
2264 p += 7;
2265 incr = -1;
2266 }
2267
2268 for (i = 0; i < 8; i++) {
2269 *p = *s++;
2270 p += incr;
2271 }
2272 return 0;
2273 }
Tim Peters9905b942003-03-20 20:53:32 +00002274}
2275
2276double
2277_PyFloat_Unpack4(const unsigned char *p, int le)
2278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (float_format == unknown_format) {
2280 unsigned char sign;
2281 int e;
2282 unsigned int f;
2283 double x;
2284 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (le) {
2287 p += 3;
2288 incr = -1;
2289 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 /* First byte */
2292 sign = (*p >> 7) & 1;
2293 e = (*p & 0x7F) << 1;
2294 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Second byte */
2297 e |= (*p >> 7) & 1;
2298 f = (*p & 0x7F) << 16;
2299 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (e == 255) {
2302 PyErr_SetString(
2303 PyExc_ValueError,
2304 "can't unpack IEEE 754 special value "
2305 "on non-IEEE platform");
2306 return -1;
2307 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Third byte */
2310 f |= *p << 8;
2311 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Fourth byte */
2314 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* XXX This sadly ignores Inf/NaN issues */
2319 if (e == 0)
2320 e = -126;
2321 else {
2322 x += 1.0;
2323 e -= 127;
2324 }
2325 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (sign)
2328 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return x;
2331 }
2332 else {
2333 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if ((float_format == ieee_little_endian_format && !le)
2336 || (float_format == ieee_big_endian_format && le)) {
2337 char buf[4];
2338 char *d = &buf[3];
2339 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 for (i = 0; i < 4; i++) {
2342 *d-- = *p++;
2343 }
2344 memcpy(&x, buf, 4);
2345 }
2346 else {
2347 memcpy(&x, p, 4);
2348 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 return x;
2351 }
Tim Peters9905b942003-03-20 20:53:32 +00002352}
2353
2354double
2355_PyFloat_Unpack8(const unsigned char *p, int le)
2356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (double_format == unknown_format) {
2358 unsigned char sign;
2359 int e;
2360 unsigned int fhi, flo;
2361 double x;
2362 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 if (le) {
2365 p += 7;
2366 incr = -1;
2367 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* First byte */
2370 sign = (*p >> 7) & 1;
2371 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Second byte */
2376 e |= (*p >> 4) & 0xF;
2377 fhi = (*p & 0xF) << 24;
2378 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 if (e == 2047) {
2381 PyErr_SetString(
2382 PyExc_ValueError,
2383 "can't unpack IEEE 754 special value "
2384 "on non-IEEE platform");
2385 return -1.0;
2386 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* Third byte */
2389 fhi |= *p << 16;
2390 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Fourth byte */
2393 fhi |= *p << 8;
2394 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* Fifth byte */
2397 fhi |= *p;
2398 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Sixth byte */
2401 flo = *p << 16;
2402 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* Seventh byte */
2405 flo |= *p << 8;
2406 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* Eighth byte */
2409 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2412 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 if (e == 0)
2415 e = -1022;
2416 else {
2417 x += 1.0;
2418 e -= 1023;
2419 }
2420 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (sign)
2423 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return x;
2426 }
2427 else {
2428 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 if ((double_format == ieee_little_endian_format && !le)
2431 || (double_format == ieee_big_endian_format && le)) {
2432 char buf[8];
2433 char *d = &buf[7];
2434 int i;
2435
2436 for (i = 0; i < 8; i++) {
2437 *d-- = *p++;
2438 }
2439 memcpy(&x, buf, 8);
2440 }
2441 else {
2442 memcpy(&x, p, 8);
2443 }
2444
2445 return x;
2446 }
Tim Peters9905b942003-03-20 20:53:32 +00002447}