blob: 4decb0b6278d70d67c893829ee4937707b7343f1 [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;
177 char buffer[256]; /* for errors */
178 char *s_buffer = NULL;
179 Py_ssize_t len;
180 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (PyUnicode_Check(v)) {
183 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
184 if (s_buffer == NULL)
185 return PyErr_NoMemory();
186 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
187 PyUnicode_GET_SIZE(v),
188 s_buffer,
189 NULL))
190 goto error;
191 s = s_buffer;
192 len = strlen(s);
193 }
194 else if (PyObject_AsCharBuffer(v, &s, &len)) {
195 PyErr_SetString(PyExc_TypeError,
196 "float() argument must be a string or a number");
197 return NULL;
198 }
199 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 while (Py_ISSPACE(*s))
202 s++;
203 /* We don't care about overflow or underflow. If the platform
204 * supports them, infinities and signed zeroes (on underflow) are
205 * fine. */
206 x = PyOS_string_to_double(s, (char **)&end, NULL);
207 if (x == -1.0 && PyErr_Occurred())
208 goto error;
209 while (Py_ISSPACE(*end))
210 end++;
211 if (end == last)
212 result = PyFloat_FromDouble(x);
213 else {
214 PyOS_snprintf(buffer, sizeof(buffer),
215 "invalid literal for float(): %.200s", s);
216 PyErr_SetString(PyExc_ValueError, buffer);
217 result = NULL;
218 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000219
Guido van Rossum2be161d2007-05-15 20:43:51 +0000220 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (s_buffer)
222 PyMem_FREE(s_buffer);
223 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000224}
225
Guido van Rossum234f9421993-06-17 12:35:49 +0000226static void
Fred Drakefd99de62000-07-09 05:02:18 +0000227float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (PyFloat_CheckExact(op)) {
230 Py_TYPE(op) = (struct _typeobject *)free_list;
231 free_list = op;
232 }
233 else
234 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000235}
236
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237double
Fred Drakefd99de62000-07-09 05:02:18 +0000238PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyNumberMethods *nb;
241 PyFloatObject *fo;
242 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (op && PyFloat_Check(op))
245 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (op == NULL) {
248 PyErr_BadArgument();
249 return -1;
250 }
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
253 PyErr_SetString(PyExc_TypeError, "a float is required");
254 return -1;
255 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 fo = (PyFloatObject*) (*nb->nb_float) (op);
258 if (fo == NULL)
259 return -1;
260 if (!PyFloat_Check(fo)) {
261 PyErr_SetString(PyExc_TypeError,
262 "nb_float should return float object");
263 return -1;
264 }
Tim Petersd2364e82001-11-01 20:09:42 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 val = PyFloat_AS_DOUBLE(fo);
267 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270}
271
Neil Schemenauer32117e52001-01-04 01:44:34 +0000272/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000273 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000274 set to NULL, and the function invoking this macro returns NULL. If
275 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
276 stored in obj, and returned from the function invoking this macro.
277*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278#define CONVERT_TO_DOUBLE(obj, dbl) \
279 if (PyFloat_Check(obj)) \
280 dbl = PyFloat_AS_DOUBLE(obj); \
281 else if (convert_to_double(&(obj), &(dbl)) < 0) \
282 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000283
Eric Smith0923d1d2009-04-16 20:16:10 +0000284/* Methods */
285
Neil Schemenauer32117e52001-01-04 01:44:34 +0000286static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000287convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (PyLong_Check(obj)) {
292 *dbl = PyLong_AsDouble(obj);
293 if (*dbl == -1.0 && PyErr_Occurred()) {
294 *v = NULL;
295 return -1;
296 }
297 }
298 else {
299 Py_INCREF(Py_NotImplemented);
300 *v = Py_NotImplemented;
301 return -1;
302 }
303 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000304}
305
Eric Smith0923d1d2009-04-16 20:16:10 +0000306static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000307float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000308{
309 PyObject *result;
310 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000311 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000312 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000313 NULL);
314 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000315 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000316 result = PyUnicode_FromString(buf);
317 PyMem_Free(buf);
318 return result;
319}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000320
Tim Peters307fa782004-09-23 08:06:40 +0000321/* Comparison is pretty much a nightmare. When comparing float to float,
322 * we do it as straightforwardly (and long-windedly) as conceivable, so
323 * that, e.g., Python x == y delivers the same result as the platform
324 * C x == y when x and/or y is a NaN.
325 * When mixing float with an integer type, there's no good *uniform* approach.
326 * Converting the double to an integer obviously doesn't work, since we
327 * may lose info from fractional bits. Converting the integer to a double
328 * also has two failure modes: (1) a long int may trigger overflow (too
329 * large to fit in the dynamic range of a C double); (2) even a C long may have
330 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
331 * 63 bits of precision, but a C double probably has only 53), and then
332 * we can falsely claim equality when low-order integer bits are lost by
333 * coercion to double. So this part is painful too.
334 */
335
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000336static PyObject*
337float_richcompare(PyObject *v, PyObject *w, int op)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 double i, j;
340 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 assert(PyFloat_Check(v));
343 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 /* Switch on the type of w. Set i and j to doubles to be compared,
346 * and op to the richcomp to use.
347 */
348 if (PyFloat_Check(w))
349 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 else if (!Py_IS_FINITE(i)) {
352 if (PyLong_Check(w))
353 /* If i is an infinity, its magnitude exceeds any
354 * finite integer, so it doesn't matter which int we
355 * compare i with. If i is a NaN, similarly.
356 */
357 j = 0.0;
358 else
359 goto Unimplemented;
360 }
Tim Peters307fa782004-09-23 08:06:40 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else if (PyLong_Check(w)) {
363 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
364 int wsign = _PyLong_Sign(w);
365 size_t nbits;
366 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (vsign != wsign) {
369 /* Magnitudes are irrelevant -- the signs alone
370 * determine the outcome.
371 */
372 i = (double)vsign;
373 j = (double)wsign;
374 goto Compare;
375 }
376 /* The signs are the same. */
377 /* Convert w to a double if it fits. In particular, 0 fits. */
378 nbits = _PyLong_NumBits(w);
379 if (nbits == (size_t)-1 && PyErr_Occurred()) {
380 /* This long is so large that size_t isn't big enough
381 * to hold the # of bits. Replace with little doubles
382 * that give the same outcome -- w is so large that
383 * its magnitude must exceed the magnitude of any
384 * finite float.
385 */
386 PyErr_Clear();
387 i = (double)vsign;
388 assert(wsign != 0);
389 j = wsign * 2.0;
390 goto Compare;
391 }
392 if (nbits <= 48) {
393 j = PyLong_AsDouble(w);
394 /* It's impossible that <= 48 bits overflowed. */
395 assert(j != -1.0 || ! PyErr_Occurred());
396 goto Compare;
397 }
398 assert(wsign != 0); /* else nbits was 0 */
399 assert(vsign != 0); /* if vsign were 0, then since wsign is
400 * not 0, we would have taken the
401 * vsign != wsign branch at the start */
402 /* We want to work with non-negative numbers. */
403 if (vsign < 0) {
404 /* "Multiply both sides" by -1; this also swaps the
405 * comparator.
406 */
407 i = -i;
408 op = _Py_SwappedOp[op];
409 }
410 assert(i > 0.0);
411 (void) frexp(i, &exponent);
412 /* exponent is the # of bits in v before the radix point;
413 * we know that nbits (the # of bits in w) > 48 at this point
414 */
415 if (exponent < 0 || (size_t)exponent < nbits) {
416 i = 1.0;
417 j = 2.0;
418 goto Compare;
419 }
420 if ((size_t)exponent > nbits) {
421 i = 2.0;
422 j = 1.0;
423 goto Compare;
424 }
425 /* v and w have the same number of bits before the radix
426 * point. Construct two longs that have the same comparison
427 * outcome.
428 */
429 {
430 double fracpart;
431 double intpart;
432 PyObject *result = NULL;
433 PyObject *one = NULL;
434 PyObject *vv = NULL;
435 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (wsign < 0) {
438 ww = PyNumber_Negative(w);
439 if (ww == NULL)
440 goto Error;
441 }
442 else
443 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 fracpart = modf(i, &intpart);
446 vv = PyLong_FromDouble(intpart);
447 if (vv == NULL)
448 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (fracpart != 0.0) {
451 /* Shift left, and or a 1 bit into vv
452 * to represent the lost fraction.
453 */
454 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 one = PyLong_FromLong(1);
457 if (one == NULL)
458 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 temp = PyNumber_Lshift(ww, one);
461 if (temp == NULL)
462 goto Error;
463 Py_DECREF(ww);
464 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 temp = PyNumber_Lshift(vv, one);
467 if (temp == NULL)
468 goto Error;
469 Py_DECREF(vv);
470 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 temp = PyNumber_Or(vv, one);
473 if (temp == NULL)
474 goto Error;
475 Py_DECREF(vv);
476 vv = temp;
477 }
Tim Peters307fa782004-09-23 08:06:40 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 r = PyObject_RichCompareBool(vv, ww, op);
480 if (r < 0)
481 goto Error;
482 result = PyBool_FromLong(r);
483 Error:
484 Py_XDECREF(vv);
485 Py_XDECREF(ww);
486 Py_XDECREF(one);
487 return result;
488 }
489 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 else /* w isn't float, int, or long */
492 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000493
494 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 PyFPE_START_PROTECT("richcompare", return NULL)
496 switch (op) {
497 case Py_EQ:
498 r = i == j;
499 break;
500 case Py_NE:
501 r = i != j;
502 break;
503 case Py_LE:
504 r = i <= j;
505 break;
506 case Py_GE:
507 r = i >= j;
508 break;
509 case Py_LT:
510 r = i < j;
511 break;
512 case Py_GT:
513 r = i > j;
514 break;
515 }
516 PyFPE_END_PROTECT(r)
517 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000518
519 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_INCREF(Py_NotImplemented);
521 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522}
523
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000524static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000525float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000528}
529
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000531float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 double a,b;
534 CONVERT_TO_DOUBLE(v, a);
535 CONVERT_TO_DOUBLE(w, b);
536 PyFPE_START_PROTECT("add", return 0)
537 a = a + b;
538 PyFPE_END_PROTECT(a)
539 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 double a,b;
546 CONVERT_TO_DOUBLE(v, a);
547 CONVERT_TO_DOUBLE(w, b);
548 PyFPE_START_PROTECT("subtract", return 0)
549 a = a - b;
550 PyFPE_END_PROTECT(a)
551 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552}
553
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000555float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 double a,b;
558 CONVERT_TO_DOUBLE(v, a);
559 CONVERT_TO_DOUBLE(w, b);
560 PyFPE_START_PROTECT("multiply", return 0)
561 a = a * b;
562 PyFPE_END_PROTECT(a)
563 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564}
565
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000567float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 double a,b;
570 CONVERT_TO_DOUBLE(v, a);
571 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000572#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (b == 0.0) {
574 PyErr_SetString(PyExc_ZeroDivisionError,
575 "float division by zero");
576 return NULL;
577 }
Christian Heimes53876d92008-04-19 00:31:39 +0000578#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 PyFPE_START_PROTECT("divide", return 0)
580 a = a / b;
581 PyFPE_END_PROTECT(a)
582 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583}
584
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000586float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 double vx, wx;
589 double mod;
590 CONVERT_TO_DOUBLE(v, vx);
591 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000592#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (wx == 0.0) {
594 PyErr_SetString(PyExc_ZeroDivisionError,
595 "float modulo");
596 return NULL;
597 }
Christian Heimes53876d92008-04-19 00:31:39 +0000598#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 PyFPE_START_PROTECT("modulo", return 0)
600 mod = fmod(vx, wx);
601 /* note: checking mod*wx < 0 is incorrect -- underflows to
602 0 if wx < sqrt(smallest nonzero double) */
603 if (mod && ((wx < 0) != (mod < 0))) {
604 mod += wx;
605 }
606 PyFPE_END_PROTECT(mod)
607 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000608}
609
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000611float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 double vx, wx;
614 double div, mod, floordiv;
615 CONVERT_TO_DOUBLE(v, vx);
616 CONVERT_TO_DOUBLE(w, wx);
617 if (wx == 0.0) {
618 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
619 return NULL;
620 }
621 PyFPE_START_PROTECT("divmod", return 0)
622 mod = fmod(vx, wx);
623 /* fmod is typically exact, so vx-mod is *mathematically* an
624 exact multiple of wx. But this is fp arithmetic, and fp
625 vx - mod is an approximation; the result is that div may
626 not be an exact integral value after the division, although
627 it will always be very close to one.
628 */
629 div = (vx - mod) / wx;
630 if (mod) {
631 /* ensure the remainder has the same sign as the denominator */
632 if ((wx < 0) != (mod < 0)) {
633 mod += wx;
634 div -= 1.0;
635 }
636 }
637 else {
638 /* the remainder is zero, and in the presence of signed zeroes
639 fmod returns different results across platforms; ensure
640 it has the same sign as the denominator; we'd like to do
641 "mod = wx * 0.0", but that may get optimized away */
642 mod *= mod; /* hide "mod = +0" from optimizer */
643 if (wx < 0.0)
644 mod = -mod;
645 }
646 /* snap quotient to nearest integral value */
647 if (div) {
648 floordiv = floor(div);
649 if (div - floordiv > 0.5)
650 floordiv += 1.0;
651 }
652 else {
653 /* div is zero - get the same sign as the true quotient */
654 div *= div; /* hide "div = +0" from optimizers */
655 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
656 }
657 PyFPE_END_PROTECT(floordiv)
658 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000659}
660
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000661static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000662float_floor_div(PyObject *v, PyObject *w)
663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 t = float_divmod(v, w);
667 if (t == NULL || t == Py_NotImplemented)
668 return t;
669 assert(PyTuple_CheckExact(t));
670 r = PyTuple_GET_ITEM(t, 0);
671 Py_INCREF(r);
672 Py_DECREF(t);
673 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000674}
675
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000676/* determine whether x is an odd integer or not; assumes that
677 x is not an infinity or nan. */
678#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
679
Tim Peters63a35712001-12-11 19:57:24 +0000680static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000681float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 double iv, iw, ix;
684 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if ((PyObject *)z != Py_None) {
687 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
688 "allowed unless all arguments are integers");
689 return NULL;
690 }
Tim Peters32f453e2001-09-03 08:35:41 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 CONVERT_TO_DOUBLE(v, iv);
693 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 /* Sort out special cases here instead of relying on pow() */
696 if (iw == 0) { /* v**0 is 1, even 0**0 */
697 return PyFloat_FromDouble(1.0);
698 }
699 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
700 return PyFloat_FromDouble(iv);
701 }
702 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
703 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
704 }
705 if (Py_IS_INFINITY(iw)) {
706 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
707 * abs(v) > 1 (including case where v infinite)
708 *
709 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
710 * abs(v) > 1 (including case where v infinite)
711 */
712 iv = fabs(iv);
713 if (iv == 1.0)
714 return PyFloat_FromDouble(1.0);
715 else if ((iw > 0.0) == (iv > 1.0))
716 return PyFloat_FromDouble(fabs(iw)); /* return inf */
717 else
718 return PyFloat_FromDouble(0.0);
719 }
720 if (Py_IS_INFINITY(iv)) {
721 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
722 * both cases, we need to add the appropriate sign if w is
723 * an odd integer.
724 */
725 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
726 if (iw > 0.0)
727 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
728 else
729 return PyFloat_FromDouble(iw_is_odd ?
730 copysign(0.0, iv) : 0.0);
731 }
732 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
733 (already dealt with above), and an error
734 if w is negative. */
735 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
736 if (iw < 0.0) {
737 PyErr_SetString(PyExc_ZeroDivisionError,
738 "0.0 cannot be raised to a "
739 "negative power");
740 return NULL;
741 }
742 /* use correct sign if iw is odd */
743 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
744 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (iv < 0.0) {
747 /* Whether this is an error is a mess, and bumps into libm
748 * bugs so we have to figure it out ourselves.
749 */
750 if (iw != floor(iw)) {
751 /* Negative numbers raised to fractional powers
752 * become complex.
753 */
754 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
755 }
756 /* iw is an exact integer, albeit perhaps a very large
757 * one. Replace iv by its absolute value and remember
758 * to negate the pow result if iw is odd.
759 */
760 iv = -iv;
761 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
762 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
765 /* (-1) ** large_integer also ends up here. Here's an
766 * extract from the comments for the previous
767 * implementation explaining why this special case is
768 * necessary:
769 *
770 * -1 raised to an exact integer should never be exceptional.
771 * Alas, some libms (chiefly glibc as of early 2003) return
772 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
773 * happen to be representable in a *C* integer. That's a
774 * bug.
775 */
776 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
777 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 /* Now iv and iw are finite, iw is nonzero, and iv is
780 * positive and not equal to 1.0. We finally allow
781 * the platform pow to step in and do the rest.
782 */
783 errno = 0;
784 PyFPE_START_PROTECT("pow", return NULL)
785 ix = pow(iv, iw);
786 PyFPE_END_PROTECT(ix)
787 Py_ADJUST_ERANGE1(ix);
788 if (negate_result)
789 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (errno != 0) {
792 /* We don't expect any errno value other than ERANGE, but
793 * the range of libm bugs appears unbounded.
794 */
795 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
796 PyExc_ValueError);
797 return NULL;
798 }
799 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800}
801
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000802#undef DOUBLE_IS_ODD_INTEGER
803
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000805float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808}
809
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000810static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000811float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000814}
815
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000816static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000817float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000820}
821
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000822static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000823float_is_integer(PyObject *v)
824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 double x = PyFloat_AsDouble(v);
826 PyObject *o;
827
828 if (x == -1.0 && PyErr_Occurred())
829 return NULL;
830 if (!Py_IS_FINITE(x))
831 Py_RETURN_FALSE;
832 errno = 0;
833 PyFPE_START_PROTECT("is_integer", return NULL)
834 o = (floor(x) == x) ? Py_True : Py_False;
835 PyFPE_END_PROTECT(x)
836 if (errno != 0) {
837 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
838 PyExc_ValueError);
839 return NULL;
840 }
841 Py_INCREF(o);
842 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000843}
844
845#if 0
846static PyObject *
847float_is_inf(PyObject *v)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 double x = PyFloat_AsDouble(v);
850 if (x == -1.0 && PyErr_Occurred())
851 return NULL;
852 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000853}
854
855static PyObject *
856float_is_nan(PyObject *v)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 double x = PyFloat_AsDouble(v);
859 if (x == -1.0 && PyErr_Occurred())
860 return NULL;
861 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000862}
863
864static PyObject *
865float_is_finite(PyObject *v)
866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 double x = PyFloat_AsDouble(v);
868 if (x == -1.0 && PyErr_Occurred())
869 return NULL;
870 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000871}
872#endif
873
874static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000875float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 double x = PyFloat_AsDouble(v);
878 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 (void)modf(x, &wholepart);
881 /* Try to get out cheap if this fits in a Python int. The attempt
882 * to cast to long must be protected, as C doesn't define what
883 * happens if the double is too big to fit in a long. Some rare
884 * systems raise an exception then (RISCOS was mentioned as one,
885 * and someone using a non-default option on Sun also bumped into
886 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
887 * still be vulnerable: if a long has more bits of precision than
888 * a double, casting MIN/MAX to double may yield an approximation,
889 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
890 * yield true from the C expression wholepart<=LONG_MAX, despite
891 * that wholepart is actually greater than LONG_MAX.
892 */
893 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
894 const long aslong = (long)wholepart;
895 return PyLong_FromLong(aslong);
896 }
897 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000898}
899
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000900/* double_round: rounds a finite double to the closest multiple of
901 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
902 ndigits <= 323). Returns a Python float, or sets a Python error and
903 returns NULL on failure (OverflowError and memory errors are possible). */
904
905#ifndef PY_NO_SHORT_FLOAT_REPR
906/* version of double_round that uses the correctly-rounded string<->double
907 conversions from Python/dtoa.c */
908
909static PyObject *
910double_round(double x, int ndigits) {
911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 double rounded;
913 Py_ssize_t buflen, mybuflen=100;
914 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
915 int decpt, sign;
916 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* round to a decimal string */
919 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
920 if (buf == NULL) {
921 PyErr_NoMemory();
922 return NULL;
923 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
926 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
927 buflen = buf_end - buf;
928 if (buflen + 8 > mybuflen) {
929 mybuflen = buflen+8;
930 mybuf = (char *)PyMem_Malloc(mybuflen);
931 if (mybuf == NULL) {
932 PyErr_NoMemory();
933 goto exit;
934 }
935 }
936 /* copy buf to mybuf, adding exponent, sign and leading 0 */
937 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
938 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* and convert the resulting string back to a double */
941 errno = 0;
942 rounded = _Py_dg_strtod(mybuf, NULL);
943 if (errno == ERANGE && fabs(rounded) >= 1.)
944 PyErr_SetString(PyExc_OverflowError,
945 "rounded value too large to represent");
946 else
947 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* done computing value; now clean up */
950 if (mybuf != shortbuf)
951 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000952 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 _Py_dg_freedtoa(buf);
954 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000955}
956
957#else /* PY_NO_SHORT_FLOAT_REPR */
958
959/* fallback version, to be used when correctly rounded binary<->decimal
960 conversions aren't available */
961
962static PyObject *
963double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 double pow1, pow2, y, z;
965 if (ndigits >= 0) {
966 if (ndigits > 22) {
967 /* pow1 and pow2 are each safe from overflow, but
968 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
969 pow1 = pow(10.0, (double)(ndigits-22));
970 pow2 = 1e22;
971 }
972 else {
973 pow1 = pow(10.0, (double)ndigits);
974 pow2 = 1.0;
975 }
976 y = (x*pow1)*pow2;
977 /* if y overflows, then rounded value is exactly x */
978 if (!Py_IS_FINITE(y))
979 return PyFloat_FromDouble(x);
980 }
981 else {
982 pow1 = pow(10.0, (double)-ndigits);
983 pow2 = 1.0; /* unused; silences a gcc compiler warning */
984 y = x / pow1;
985 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 z = round(y);
988 if (fabs(y-z) == 0.5)
989 /* halfway between two integers; use round-half-even */
990 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (ndigits >= 0)
993 z = (z / pow2) / pow1;
994 else
995 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* if computation resulted in overflow, raise OverflowError */
998 if (!Py_IS_FINITE(z)) {
999 PyErr_SetString(PyExc_OverflowError,
1000 "overflow occurred during round");
1001 return NULL;
1002 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001005}
1006
1007#endif /* PY_NO_SHORT_FLOAT_REPR */
1008
1009/* round a Python float v to the closest multiple of 10**-ndigits */
1010
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001011static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001012float_round(PyObject *v, PyObject *args)
1013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 double x, rounded;
1015 PyObject *o_ndigits = NULL;
1016 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 x = PyFloat_AsDouble(v);
1019 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1020 return NULL;
1021 if (o_ndigits == NULL) {
1022 /* single-argument round: round to nearest integer */
1023 rounded = round(x);
1024 if (fabs(x-rounded) == 0.5)
1025 /* halfway case: round to even */
1026 rounded = 2.0*round(x/2.0);
1027 return PyLong_FromDouble(rounded);
1028 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 /* interpret second argument as a Py_ssize_t; clips on overflow */
1031 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1032 if (ndigits == -1 && PyErr_Occurred())
1033 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* nans and infinities round to themselves */
1036 if (!Py_IS_FINITE(x))
1037 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1040 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1041 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001042#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1043#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (ndigits > NDIGITS_MAX)
1045 /* return x */
1046 return PyFloat_FromDouble(x);
1047 else if (ndigits < NDIGITS_MIN)
1048 /* return 0.0, but with sign of x */
1049 return PyFloat_FromDouble(0.0*x);
1050 else
1051 /* finite x, and ndigits is not unreasonably large */
1052 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001053#undef NDIGITS_MAX
1054#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001055}
1056
1057static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001058float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (PyFloat_CheckExact(v))
1061 Py_INCREF(v);
1062 else
1063 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1064 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001065}
1066
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001067/* turn ASCII hex characters into integer values and vice versa */
1068
1069static char
1070char_from_hex(int x)
1071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 assert(0 <= x && x < 16);
1073 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001074}
1075
1076static int
1077hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 int x;
1079 switch(c) {
1080 case '0':
1081 x = 0;
1082 break;
1083 case '1':
1084 x = 1;
1085 break;
1086 case '2':
1087 x = 2;
1088 break;
1089 case '3':
1090 x = 3;
1091 break;
1092 case '4':
1093 x = 4;
1094 break;
1095 case '5':
1096 x = 5;
1097 break;
1098 case '6':
1099 x = 6;
1100 break;
1101 case '7':
1102 x = 7;
1103 break;
1104 case '8':
1105 x = 8;
1106 break;
1107 case '9':
1108 x = 9;
1109 break;
1110 case 'a':
1111 case 'A':
1112 x = 10;
1113 break;
1114 case 'b':
1115 case 'B':
1116 x = 11;
1117 break;
1118 case 'c':
1119 case 'C':
1120 x = 12;
1121 break;
1122 case 'd':
1123 case 'D':
1124 x = 13;
1125 break;
1126 case 'e':
1127 case 'E':
1128 x = 14;
1129 break;
1130 case 'f':
1131 case 'F':
1132 x = 15;
1133 break;
1134 default:
1135 x = -1;
1136 break;
1137 }
1138 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001139}
1140
1141/* convert a float to a hexadecimal string */
1142
1143/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1144 of the form 4k+1. */
1145#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1146
1147static PyObject *
1148float_hex(PyObject *v)
1149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 double x, m;
1151 int e, shift, i, si, esign;
1152 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1153 trailing NUL byte. */
1154 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001159 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001162 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return PyUnicode_FromString("-0x0.0p+0");
1164 else
1165 return PyUnicode_FromString("0x0.0p+0");
1166 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 m = frexp(fabs(x), &e);
1169 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1170 m = ldexp(m, shift);
1171 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 si = 0;
1174 s[si] = char_from_hex((int)m);
1175 si++;
1176 m -= (int)m;
1177 s[si] = '.';
1178 si++;
1179 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1180 m *= 16.0;
1181 s[si] = char_from_hex((int)m);
1182 si++;
1183 m -= (int)m;
1184 }
1185 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (e < 0) {
1188 esign = (int)'-';
1189 e = -e;
1190 }
1191 else
1192 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (x < 0.0)
1195 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1196 else
1197 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001198}
1199
1200PyDoc_STRVAR(float_hex_doc,
1201"float.hex() -> string\n\
1202\n\
1203Return a hexadecimal representation of a floating-point number.\n\
1204>>> (-0.1).hex()\n\
1205'-0x1.999999999999ap-4'\n\
1206>>> 3.14159.hex()\n\
1207'0x1.921f9f01b866ep+1'");
1208
1209/* Convert a hexadecimal string to a float. */
1210
1211static PyObject *
1212float_fromhex(PyObject *cls, PyObject *arg)
1213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 PyObject *result_as_float, *result;
1215 double x;
1216 long exp, top_exp, lsb, key_digit;
1217 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1218 int half_eps, digit, round_up, negate=0;
1219 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 /*
1222 * For the sake of simplicity and correctness, we impose an artificial
1223 * limit on ndigits, the total number of hex digits in the coefficient
1224 * The limit is chosen to ensure that, writing exp for the exponent,
1225 *
1226 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1227 * guaranteed to overflow (provided it's nonzero)
1228 *
1229 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1230 * guaranteed to underflow to 0.
1231 *
1232 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1233 * overflow in the calculation of exp and top_exp below.
1234 *
1235 * More specifically, ndigits is assumed to satisfy the following
1236 * inequalities:
1237 *
1238 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1239 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1240 *
1241 * If either of these inequalities is not satisfied, a ValueError is
1242 * raised. Otherwise, write x for the value of the hex string, and
1243 * assume x is nonzero. Then
1244 *
1245 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1246 *
1247 * Now if exp > LONG_MAX/2 then:
1248 *
1249 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1250 * = DBL_MAX_EXP
1251 *
1252 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1253 * double, so overflows. If exp < LONG_MIN/2, then
1254 *
1255 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1256 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1257 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1258 *
1259 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1260 * when converted to a C double.
1261 *
1262 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1263 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1264 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 s = _PyUnicode_AsStringAndSize(arg, &length);
1267 if (s == NULL)
1268 return NULL;
1269 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 /********************
1272 * Parse the string *
1273 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 /* leading whitespace */
1276 while (Py_ISSPACE(*s))
1277 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* infinities and nans */
1280 x = _Py_parse_inf_or_nan(s, &coeff_end);
1281 if (coeff_end != s) {
1282 s = coeff_end;
1283 goto finished;
1284 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /* optional sign */
1287 if (*s == '-') {
1288 s++;
1289 negate = 1;
1290 }
1291 else if (*s == '+')
1292 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 /* [0x] */
1295 s_store = s;
1296 if (*s == '0') {
1297 s++;
1298 if (*s == 'x' || *s == 'X')
1299 s++;
1300 else
1301 s = s_store;
1302 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /* coefficient: <integer> [. <fraction>] */
1305 coeff_start = s;
1306 while (hex_from_char(*s) >= 0)
1307 s++;
1308 s_store = s;
1309 if (*s == '.') {
1310 s++;
1311 while (hex_from_char(*s) >= 0)
1312 s++;
1313 coeff_end = s-1;
1314 }
1315 else
1316 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* ndigits = total # of hex digits; fdigits = # after point */
1319 ndigits = coeff_end - coeff_start;
1320 fdigits = coeff_end - s_store;
1321 if (ndigits == 0)
1322 goto parse_error;
1323 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1324 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1325 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 /* [p <exponent>] */
1328 if (*s == 'p' || *s == 'P') {
1329 s++;
1330 exp_start = s;
1331 if (*s == '-' || *s == '+')
1332 s++;
1333 if (!('0' <= *s && *s <= '9'))
1334 goto parse_error;
1335 s++;
1336 while ('0' <= *s && *s <= '9')
1337 s++;
1338 exp = strtol(exp_start, NULL, 10);
1339 }
1340 else
1341 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001342
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001343/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1345 coeff_end-(j) : \
1346 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /*******************************************
1349 * Compute rounded value of the hex string *
1350 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /* Discard leading zeros, and catch extreme overflow and underflow */
1353 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1354 ndigits--;
1355 if (ndigits == 0 || exp < LONG_MIN/2) {
1356 x = 0.0;
1357 goto finished;
1358 }
1359 if (exp > LONG_MAX/2)
1360 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* Adjust exponent for fractional part. */
1363 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1366 top_exp = exp + 4*((long)ndigits - 1);
1367 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1368 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* catch almost all nonextreme cases of overflow and underflow here */
1371 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1372 x = 0.0;
1373 goto finished;
1374 }
1375 if (top_exp > DBL_MAX_EXP)
1376 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 /* lsb = exponent of least significant bit of the *rounded* value.
1379 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1380 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 x = 0.0;
1383 if (exp >= lsb) {
1384 /* no rounding required */
1385 for (i = ndigits-1; i >= 0; i--)
1386 x = 16.0*x + HEX_DIGIT(i);
1387 x = ldexp(x, (int)(exp));
1388 goto finished;
1389 }
1390 /* rounding required. key_digit is the index of the hex digit
1391 containing the first bit to be rounded away. */
1392 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1393 key_digit = (lsb - exp - 1) / 4;
1394 for (i = ndigits-1; i > key_digit; i--)
1395 x = 16.0*x + HEX_DIGIT(i);
1396 digit = HEX_DIGIT(key_digit);
1397 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1400 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1401 if ((digit & half_eps) != 0) {
1402 round_up = 0;
1403 if ((digit & (3*half_eps-1)) != 0 ||
1404 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1405 round_up = 1;
1406 else
1407 for (i = key_digit-1; i >= 0; i--)
1408 if (HEX_DIGIT(i) != 0) {
1409 round_up = 1;
1410 break;
1411 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001412 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 x += 2*half_eps;
1414 if (top_exp == DBL_MAX_EXP &&
1415 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1416 /* overflow corner case: pre-rounded value <
1417 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1418 goto overflow_error;
1419 }
1420 }
1421 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001422
1423 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* optional trailing whitespace leading to the end of the string */
1425 while (Py_ISSPACE(*s))
1426 s++;
1427 if (s != s_end)
1428 goto parse_error;
1429 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1430 if (result_as_float == NULL)
1431 return NULL;
1432 result = PyObject_CallObject(cls, result_as_float);
1433 Py_DECREF(result_as_float);
1434 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001435
1436 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyErr_SetString(PyExc_OverflowError,
1438 "hexadecimal value too large to represent as a float");
1439 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001440
1441 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyErr_SetString(PyExc_ValueError,
1443 "invalid hexadecimal floating-point string");
1444 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001445
1446 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyErr_SetString(PyExc_ValueError,
1448 "hexadecimal string too long to convert");
1449 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001450}
1451
1452PyDoc_STRVAR(float_fromhex_doc,
1453"float.fromhex(string) -> float\n\
1454\n\
1455Create a floating-point number from a hexadecimal string.\n\
1456>>> float.fromhex('0x1.ffffp10')\n\
14572047.984375\n\
1458>>> float.fromhex('-0x1p-1074')\n\
1459-4.9406564584124654e-324");
1460
1461
Christian Heimes26855632008-01-27 23:50:43 +00001462static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001463float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 double self;
1466 double float_part;
1467 int exponent;
1468 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyObject *prev;
1471 PyObject *py_exponent = NULL;
1472 PyObject *numerator = NULL;
1473 PyObject *denominator = NULL;
1474 PyObject *result_pair = NULL;
1475 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001476
1477#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 prev = obj; \
1479 obj = call; \
1480 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (Py_IS_INFINITY(self)) {
1485 PyErr_SetString(PyExc_OverflowError,
1486 "Cannot pass infinity to float.as_integer_ratio.");
1487 return NULL;
1488 }
Christian Heimes26855632008-01-27 23:50:43 +00001489#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (Py_IS_NAN(self)) {
1491 PyErr_SetString(PyExc_ValueError,
1492 "Cannot pass NaN to float.as_integer_ratio.");
1493 return NULL;
1494 }
Christian Heimes26855632008-01-27 23:50:43 +00001495#endif
1496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1498 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1499 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1502 float_part *= 2.0;
1503 exponent--;
1504 }
1505 /* self == float_part * 2**exponent exactly and float_part is integral.
1506 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1507 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 numerator = PyLong_FromDouble(float_part);
1510 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 /* fold in 2**exponent */
1513 denominator = PyLong_FromLong(1);
1514 py_exponent = PyLong_FromLong(labs((long)exponent));
1515 if (py_exponent == NULL) goto error;
1516 INPLACE_UPDATE(py_exponent,
1517 long_methods->nb_lshift(denominator, py_exponent));
1518 if (py_exponent == NULL) goto error;
1519 if (exponent > 0) {
1520 INPLACE_UPDATE(numerator,
1521 long_methods->nb_multiply(numerator, py_exponent));
1522 if (numerator == NULL) goto error;
1523 }
1524 else {
1525 Py_DECREF(denominator);
1526 denominator = py_exponent;
1527 py_exponent = NULL;
1528 }
1529
1530 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001531
1532#undef INPLACE_UPDATE
1533error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 Py_XDECREF(py_exponent);
1535 Py_XDECREF(denominator);
1536 Py_XDECREF(numerator);
1537 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001538}
1539
1540PyDoc_STRVAR(float_as_integer_ratio_doc,
1541"float.as_integer_ratio() -> (int, int)\n"
1542"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001543"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1544"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001545"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001546"\n"
1547">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001548"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001549">>> (0.0).as_integer_ratio()\n"
1550"(0, 1)\n"
1551">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001552"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001553
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001554
Jeremy Hylton938ace62002-07-17 16:30:39 +00001555static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001556float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1557
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558static PyObject *
1559float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyObject *x = Py_False; /* Integer zero */
1562 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (type != &PyFloat_Type)
1565 return float_subtype_new(type, args, kwds); /* Wimp out */
1566 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1567 return NULL;
1568 /* If it's a string, but not a string subclass, use
1569 PyFloat_FromString. */
1570 if (PyUnicode_CheckExact(x))
1571 return PyFloat_FromString(x);
1572 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573}
1574
Guido van Rossumbef14172001-08-29 15:47:46 +00001575/* Wimpy, slow approach to tp_new calls for subtypes of float:
1576 first create a regular float from whatever arguments we got,
1577 then allocate a subtype instance and initialize its ob_fval
1578 from the regular float. The regular float is then thrown away.
1579*/
1580static PyObject *
1581float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 assert(PyType_IsSubtype(type, &PyFloat_Type));
1586 tmp = float_new(&PyFloat_Type, args, kwds);
1587 if (tmp == NULL)
1588 return NULL;
1589 assert(PyFloat_CheckExact(tmp));
1590 newobj = type->tp_alloc(type, 0);
1591 if (newobj == NULL) {
1592 Py_DECREF(tmp);
1593 return NULL;
1594 }
1595 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1596 Py_DECREF(tmp);
1597 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001598}
1599
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001600static PyObject *
1601float_getnewargs(PyFloatObject *v)
1602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001604}
1605
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001606/* this is for the benefit of the pack/unpack routines below */
1607
1608typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001610} float_format_type;
1611
1612static float_format_type double_format, float_format;
1613static float_format_type detected_double_format, detected_float_format;
1614
1615static PyObject *
1616float_getformat(PyTypeObject *v, PyObject* arg)
1617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 char* s;
1619 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 if (!PyUnicode_Check(arg)) {
1622 PyErr_Format(PyExc_TypeError,
1623 "__getformat__() argument must be string, not %.500s",
1624 Py_TYPE(arg)->tp_name);
1625 return NULL;
1626 }
1627 s = _PyUnicode_AsString(arg);
1628 if (s == NULL)
1629 return NULL;
1630 if (strcmp(s, "double") == 0) {
1631 r = double_format;
1632 }
1633 else if (strcmp(s, "float") == 0) {
1634 r = float_format;
1635 }
1636 else {
1637 PyErr_SetString(PyExc_ValueError,
1638 "__getformat__() argument 1 must be "
1639 "'double' or 'float'");
1640 return NULL;
1641 }
1642
1643 switch (r) {
1644 case unknown_format:
1645 return PyUnicode_FromString("unknown");
1646 case ieee_little_endian_format:
1647 return PyUnicode_FromString("IEEE, little-endian");
1648 case ieee_big_endian_format:
1649 return PyUnicode_FromString("IEEE, big-endian");
1650 default:
1651 Py_FatalError("insane float_format or double_format");
1652 return NULL;
1653 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001654}
1655
1656PyDoc_STRVAR(float_getformat_doc,
1657"float.__getformat__(typestr) -> string\n"
1658"\n"
1659"You probably don't want to use this function. It exists mainly to be\n"
1660"used in Python's test suite.\n"
1661"\n"
1662"typestr must be 'double' or 'float'. This function returns whichever of\n"
1663"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1664"format of floating point numbers used by the C type named by typestr.");
1665
1666static PyObject *
1667float_setformat(PyTypeObject *v, PyObject* args)
1668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 char* typestr;
1670 char* format;
1671 float_format_type f;
1672 float_format_type detected;
1673 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1676 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (strcmp(typestr, "double") == 0) {
1679 p = &double_format;
1680 detected = detected_double_format;
1681 }
1682 else if (strcmp(typestr, "float") == 0) {
1683 p = &float_format;
1684 detected = detected_float_format;
1685 }
1686 else {
1687 PyErr_SetString(PyExc_ValueError,
1688 "__setformat__() argument 1 must "
1689 "be 'double' or 'float'");
1690 return NULL;
1691 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (strcmp(format, "unknown") == 0) {
1694 f = unknown_format;
1695 }
1696 else if (strcmp(format, "IEEE, little-endian") == 0) {
1697 f = ieee_little_endian_format;
1698 }
1699 else if (strcmp(format, "IEEE, big-endian") == 0) {
1700 f = ieee_big_endian_format;
1701 }
1702 else {
1703 PyErr_SetString(PyExc_ValueError,
1704 "__setformat__() argument 2 must be "
1705 "'unknown', 'IEEE, little-endian' or "
1706 "'IEEE, big-endian'");
1707 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (f != unknown_format && f != detected) {
1712 PyErr_Format(PyExc_ValueError,
1713 "can only set %s format to 'unknown' or the "
1714 "detected platform value", typestr);
1715 return NULL;
1716 }
1717
1718 *p = f;
1719 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001720}
1721
1722PyDoc_STRVAR(float_setformat_doc,
1723"float.__setformat__(typestr, fmt) -> None\n"
1724"\n"
1725"You probably don't want to use this function. It exists mainly to be\n"
1726"used in Python's test suite.\n"
1727"\n"
1728"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1729"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1730"one of the latter two if it appears to match the underlying C reality.\n"
1731"\n"
1732"Overrides the automatic determination of C-level floating point type.\n"
1733"This affects how floats are converted to and from binary strings.");
1734
Guido van Rossumb43daf72007-08-01 18:08:08 +00001735static PyObject *
1736float_getzero(PyObject *v, void *closure)
1737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001739}
1740
Eric Smith8c663262007-08-25 02:26:07 +00001741static PyObject *
1742float__format__(PyObject *self, PyObject *args)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1747 return NULL;
1748 return _PyFloat_FormatAdvanced(self,
1749 PyUnicode_AS_UNICODE(format_spec),
1750 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001751}
1752
1753PyDoc_STRVAR(float__format__doc,
1754"float.__format__(format_spec) -> string\n"
1755"\n"
1756"Formats the float according to format_spec.");
1757
1758
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001759static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1761 "Returns self, the complex conjugate of any float."},
1762 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1763 "Returns the Integral closest to x between 0 and x."},
1764 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1765 "Returns the Integral closest to x, rounding half toward even.\n"
1766 "When an argument is passed, works like built-in round(x, ndigits)."},
1767 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1768 float_as_integer_ratio_doc},
1769 {"fromhex", (PyCFunction)float_fromhex,
1770 METH_O|METH_CLASS, float_fromhex_doc},
1771 {"hex", (PyCFunction)float_hex,
1772 METH_NOARGS, float_hex_doc},
1773 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1774 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001775#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1777 "Returns True if the float is positive or negative infinite."},
1778 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1779 "Returns True if the float is finite, neither infinite nor NaN."},
1780 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1781 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001782#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1784 {"__getformat__", (PyCFunction)float_getformat,
1785 METH_O|METH_CLASS, float_getformat_doc},
1786 {"__setformat__", (PyCFunction)float_setformat,
1787 METH_VARARGS|METH_CLASS, float_setformat_doc},
1788 {"__format__", (PyCFunction)float__format__,
1789 METH_VARARGS, float__format__doc},
1790 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001791};
1792
Guido van Rossumb43daf72007-08-01 18:08:08 +00001793static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001795 (getter)float_float, (setter)NULL,
1796 "the real part of a complex number",
1797 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001799 (getter)float_getzero, (setter)NULL,
1800 "the imaginary part of a complex number",
1801 NULL},
1802 {NULL} /* Sentinel */
1803};
1804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001805PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806"float(x) -> floating point number\n\
1807\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001808Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809
1810
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001811static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 float_add, /*nb_add*/
1813 float_sub, /*nb_subtract*/
1814 float_mul, /*nb_multiply*/
1815 float_rem, /*nb_remainder*/
1816 float_divmod, /*nb_divmod*/
1817 float_pow, /*nb_power*/
1818 (unaryfunc)float_neg, /*nb_negative*/
1819 (unaryfunc)float_float, /*nb_positive*/
1820 (unaryfunc)float_abs, /*nb_absolute*/
1821 (inquiry)float_bool, /*nb_bool*/
1822 0, /*nb_invert*/
1823 0, /*nb_lshift*/
1824 0, /*nb_rshift*/
1825 0, /*nb_and*/
1826 0, /*nb_xor*/
1827 0, /*nb_or*/
1828 float_trunc, /*nb_int*/
1829 0, /*nb_reserved*/
1830 float_float, /*nb_float*/
1831 0, /* nb_inplace_add */
1832 0, /* nb_inplace_subtract */
1833 0, /* nb_inplace_multiply */
1834 0, /* nb_inplace_remainder */
1835 0, /* nb_inplace_power */
1836 0, /* nb_inplace_lshift */
1837 0, /* nb_inplace_rshift */
1838 0, /* nb_inplace_and */
1839 0, /* nb_inplace_xor */
1840 0, /* nb_inplace_or */
1841 float_floor_div, /* nb_floor_divide */
1842 float_div, /* nb_true_divide */
1843 0, /* nb_inplace_floor_divide */
1844 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001845};
1846
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001847PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1849 "float",
1850 sizeof(PyFloatObject),
1851 0,
1852 (destructor)float_dealloc, /* tp_dealloc */
1853 0, /* tp_print */
1854 0, /* tp_getattr */
1855 0, /* tp_setattr */
1856 0, /* tp_reserved */
1857 (reprfunc)float_repr, /* tp_repr */
1858 &float_as_number, /* tp_as_number */
1859 0, /* tp_as_sequence */
1860 0, /* tp_as_mapping */
1861 (hashfunc)float_hash, /* tp_hash */
1862 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001863 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 PyObject_GenericGetAttr, /* tp_getattro */
1865 0, /* tp_setattro */
1866 0, /* tp_as_buffer */
1867 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1868 float_doc, /* tp_doc */
1869 0, /* tp_traverse */
1870 0, /* tp_clear */
1871 float_richcompare, /* tp_richcompare */
1872 0, /* tp_weaklistoffset */
1873 0, /* tp_iter */
1874 0, /* tp_iternext */
1875 float_methods, /* tp_methods */
1876 0, /* tp_members */
1877 float_getset, /* tp_getset */
1878 0, /* tp_base */
1879 0, /* tp_dict */
1880 0, /* tp_descr_get */
1881 0, /* tp_descr_set */
1882 0, /* tp_dictoffset */
1883 0, /* tp_init */
1884 0, /* tp_alloc */
1885 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001886};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001887
1888void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001889_PyFloat_Init(void)
1890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* We attempt to determine if this machine is using IEEE
1892 floating point formats by peering at the bits of some
1893 carefully chosen values. If it looks like we are on an
1894 IEEE platform, the float packing/unpacking routines can
1895 just copy bits, if not they resort to arithmetic & shifts
1896 and masks. The shifts & masks approach works on all finite
1897 values, but what happens to infinities, NaNs and signed
1898 zeroes on packing is an accident, and attempting to unpack
1899 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Note that if we're on some whacked-out platform which uses
1902 IEEE formats but isn't strictly little-endian or big-
1903 endian, we will fall back to the portable shifts & masks
1904 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001905
1906#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 {
1908 double x = 9006104071832581.0;
1909 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1910 detected_double_format = ieee_big_endian_format;
1911 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1912 detected_double_format = ieee_little_endian_format;
1913 else
1914 detected_double_format = unknown_format;
1915 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001916#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001918#endif
1919
1920#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 {
1922 float y = 16711938.0;
1923 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1924 detected_float_format = ieee_big_endian_format;
1925 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1926 detected_float_format = ieee_little_endian_format;
1927 else
1928 detected_float_format = unknown_format;
1929 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001932#endif
1933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 double_format = detected_double_format;
1935 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 /* Init float info */
1938 if (FloatInfoType.tp_name == 0)
1939 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940}
1941
Georg Brandl2ee470f2008-07-16 12:55:28 +00001942int
1943PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyFloatObject *p;
1946 PyFloatBlock *list, *next;
1947 int i;
1948 int u; /* remaining unfreed floats per block */
1949 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 list = block_list;
1952 block_list = NULL;
1953 free_list = NULL;
1954 while (list != NULL) {
1955 u = 0;
1956 for (i = 0, p = &list->objects[0];
1957 i < N_FLOATOBJECTS;
1958 i++, p++) {
1959 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1960 u++;
1961 }
1962 next = list->next;
1963 if (u) {
1964 list->next = block_list;
1965 block_list = list;
1966 for (i = 0, p = &list->objects[0];
1967 i < N_FLOATOBJECTS;
1968 i++, p++) {
1969 if (!PyFloat_CheckExact(p) ||
1970 Py_REFCNT(p) == 0) {
1971 Py_TYPE(p) = (struct _typeobject *)
1972 free_list;
1973 free_list = p;
1974 }
1975 }
1976 }
1977 else {
1978 PyMem_FREE(list);
1979 }
1980 freelist_size += u;
1981 list = next;
1982 }
1983 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001984}
1985
1986void
1987PyFloat_Fini(void)
1988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyFloatObject *p;
1990 PyFloatBlock *list;
1991 int i;
1992 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (!Py_VerboseFlag)
1997 return;
1998 fprintf(stderr, "# cleanup floats");
1999 if (!u) {
2000 fprintf(stderr, "\n");
2001 }
2002 else {
2003 fprintf(stderr,
2004 ": %d unfreed float%s\n",
2005 u, u == 1 ? "" : "s");
2006 }
2007 if (Py_VerboseFlag > 1) {
2008 list = block_list;
2009 while (list != NULL) {
2010 for (i = 0, p = &list->objects[0];
2011 i < N_FLOATOBJECTS;
2012 i++, p++) {
2013 if (PyFloat_CheckExact(p) &&
2014 Py_REFCNT(p) != 0) {
2015 char *buf = PyOS_double_to_string(
2016 PyFloat_AS_DOUBLE(p), 'r',
2017 0, 0, NULL);
2018 if (buf) {
2019 /* XXX(twouters) cast
2020 refcount to long
2021 until %zd is
2022 universally
2023 available
2024 */
2025 fprintf(stderr,
2026 "# <float at %p, refcnt=%ld, val=%s>\n",
2027 p, (long)Py_REFCNT(p), buf);
2028 PyMem_Free(buf);
2029 }
2030 }
2031 }
2032 list = list->next;
2033 }
2034 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002035}
Tim Peters9905b942003-03-20 20:53:32 +00002036
2037/*----------------------------------------------------------------------------
2038 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002039 */
2040int
2041_PyFloat_Pack4(double x, unsigned char *p, int le)
2042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if (float_format == unknown_format) {
2044 unsigned char sign;
2045 int e;
2046 double f;
2047 unsigned int fbits;
2048 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (le) {
2051 p += 3;
2052 incr = -1;
2053 }
Tim Peters9905b942003-03-20 20:53:32 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (x < 0) {
2056 sign = 1;
2057 x = -x;
2058 }
2059 else
2060 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Normalize f to be in the range [1.0, 2.0) */
2065 if (0.5 <= f && f < 1.0) {
2066 f *= 2.0;
2067 e--;
2068 }
2069 else if (f == 0.0)
2070 e = 0;
2071 else {
2072 PyErr_SetString(PyExc_SystemError,
2073 "frexp() result out of range");
2074 return -1;
2075 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 if (e >= 128)
2078 goto Overflow;
2079 else if (e < -126) {
2080 /* Gradual underflow */
2081 f = ldexp(f, 126 + e);
2082 e = 0;
2083 }
2084 else if (!(e == 0 && f == 0.0)) {
2085 e += 127;
2086 f -= 1.0; /* Get rid of leading 1 */
2087 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 f *= 8388608.0; /* 2**23 */
2090 fbits = (unsigned int)(f + 0.5); /* Round */
2091 assert(fbits <= 8388608);
2092 if (fbits >> 23) {
2093 /* The carry propagated out of a string of 23 1 bits. */
2094 fbits = 0;
2095 ++e;
2096 if (e >= 255)
2097 goto Overflow;
2098 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* First byte */
2101 *p = (sign << 7) | (e >> 1);
2102 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 /* Second byte */
2105 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2106 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 /* Third byte */
2109 *p = (fbits >> 8) & 0xFF;
2110 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 /* Fourth byte */
2113 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 /* Done */
2116 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 }
2119 else {
2120 float y = (float)x;
2121 const char *s = (char*)&y;
2122 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2125 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if ((float_format == ieee_little_endian_format && !le)
2128 || (float_format == ieee_big_endian_format && le)) {
2129 p += 3;
2130 incr = -1;
2131 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 for (i = 0; i < 4; i++) {
2134 *p = *s++;
2135 p += incr;
2136 }
2137 return 0;
2138 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002139 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyErr_SetString(PyExc_OverflowError,
2141 "float too large to pack with f format");
2142 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002143}
2144
2145int
2146_PyFloat_Pack8(double x, unsigned char *p, int le)
2147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (double_format == unknown_format) {
2149 unsigned char sign;
2150 int e;
2151 double f;
2152 unsigned int fhi, flo;
2153 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (le) {
2156 p += 7;
2157 incr = -1;
2158 }
Tim Peters9905b942003-03-20 20:53:32 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (x < 0) {
2161 sign = 1;
2162 x = -x;
2163 }
2164 else
2165 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* Normalize f to be in the range [1.0, 2.0) */
2170 if (0.5 <= f && f < 1.0) {
2171 f *= 2.0;
2172 e--;
2173 }
2174 else if (f == 0.0)
2175 e = 0;
2176 else {
2177 PyErr_SetString(PyExc_SystemError,
2178 "frexp() result out of range");
2179 return -1;
2180 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (e >= 1024)
2183 goto Overflow;
2184 else if (e < -1022) {
2185 /* Gradual underflow */
2186 f = ldexp(f, 1022 + e);
2187 e = 0;
2188 }
2189 else if (!(e == 0 && f == 0.0)) {
2190 e += 1023;
2191 f -= 1.0; /* Get rid of leading 1 */
2192 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2195 f *= 268435456.0; /* 2**28 */
2196 fhi = (unsigned int)f; /* Truncate */
2197 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 f -= (double)fhi;
2200 f *= 16777216.0; /* 2**24 */
2201 flo = (unsigned int)(f + 0.5); /* Round */
2202 assert(flo <= 16777216);
2203 if (flo >> 24) {
2204 /* The carry propagated out of a string of 24 1 bits. */
2205 flo = 0;
2206 ++fhi;
2207 if (fhi >> 28) {
2208 /* And it also progagated out of the next 28 bits. */
2209 fhi = 0;
2210 ++e;
2211 if (e >= 2047)
2212 goto Overflow;
2213 }
2214 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* First byte */
2217 *p = (sign << 7) | (e >> 4);
2218 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Second byte */
2221 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2222 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Third byte */
2225 *p = (fhi >> 16) & 0xFF;
2226 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Fourth byte */
2229 *p = (fhi >> 8) & 0xFF;
2230 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* Fifth byte */
2233 *p = fhi & 0xFF;
2234 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Sixth byte */
2237 *p = (flo >> 16) & 0xFF;
2238 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Seventh byte */
2241 *p = (flo >> 8) & 0xFF;
2242 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Eighth byte */
2245 *p = flo & 0xFF;
2246 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* Done */
2249 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 Overflow:
2252 PyErr_SetString(PyExc_OverflowError,
2253 "float too large to pack with d format");
2254 return -1;
2255 }
2256 else {
2257 const char *s = (char*)&x;
2258 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if ((double_format == ieee_little_endian_format && !le)
2261 || (double_format == ieee_big_endian_format && le)) {
2262 p += 7;
2263 incr = -1;
2264 }
2265
2266 for (i = 0; i < 8; i++) {
2267 *p = *s++;
2268 p += incr;
2269 }
2270 return 0;
2271 }
Tim Peters9905b942003-03-20 20:53:32 +00002272}
2273
2274double
2275_PyFloat_Unpack4(const unsigned char *p, int le)
2276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (float_format == unknown_format) {
2278 unsigned char sign;
2279 int e;
2280 unsigned int f;
2281 double x;
2282 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (le) {
2285 p += 3;
2286 incr = -1;
2287 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* First byte */
2290 sign = (*p >> 7) & 1;
2291 e = (*p & 0x7F) << 1;
2292 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Second byte */
2295 e |= (*p >> 7) & 1;
2296 f = (*p & 0x7F) << 16;
2297 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (e == 255) {
2300 PyErr_SetString(
2301 PyExc_ValueError,
2302 "can't unpack IEEE 754 special value "
2303 "on non-IEEE platform");
2304 return -1;
2305 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Third byte */
2308 f |= *p << 8;
2309 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Fourth byte */
2312 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* XXX This sadly ignores Inf/NaN issues */
2317 if (e == 0)
2318 e = -126;
2319 else {
2320 x += 1.0;
2321 e -= 127;
2322 }
2323 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 if (sign)
2326 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 return x;
2329 }
2330 else {
2331 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if ((float_format == ieee_little_endian_format && !le)
2334 || (float_format == ieee_big_endian_format && le)) {
2335 char buf[4];
2336 char *d = &buf[3];
2337 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 for (i = 0; i < 4; i++) {
2340 *d-- = *p++;
2341 }
2342 memcpy(&x, buf, 4);
2343 }
2344 else {
2345 memcpy(&x, p, 4);
2346 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return x;
2349 }
Tim Peters9905b942003-03-20 20:53:32 +00002350}
2351
2352double
2353_PyFloat_Unpack8(const unsigned char *p, int le)
2354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 if (double_format == unknown_format) {
2356 unsigned char sign;
2357 int e;
2358 unsigned int fhi, flo;
2359 double x;
2360 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (le) {
2363 p += 7;
2364 incr = -1;
2365 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* First byte */
2368 sign = (*p >> 7) & 1;
2369 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* Second byte */
2374 e |= (*p >> 4) & 0xF;
2375 fhi = (*p & 0xF) << 24;
2376 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 if (e == 2047) {
2379 PyErr_SetString(
2380 PyExc_ValueError,
2381 "can't unpack IEEE 754 special value "
2382 "on non-IEEE platform");
2383 return -1.0;
2384 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* Third byte */
2387 fhi |= *p << 16;
2388 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* Fourth byte */
2391 fhi |= *p << 8;
2392 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* Fifth byte */
2395 fhi |= *p;
2396 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 /* Sixth byte */
2399 flo = *p << 16;
2400 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Seventh byte */
2403 flo |= *p << 8;
2404 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 /* Eighth byte */
2407 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2410 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 if (e == 0)
2413 e = -1022;
2414 else {
2415 x += 1.0;
2416 e -= 1023;
2417 }
2418 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (sign)
2421 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return x;
2424 }
2425 else {
2426 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 if ((double_format == ieee_little_endian_format && !le)
2429 || (double_format == ieee_big_endian_format && le)) {
2430 char buf[8];
2431 char *d = &buf[7];
2432 int i;
2433
2434 for (i = 0; i < 8; i++) {
2435 *d-- = *p++;
2436 }
2437 memcpy(&x, buf, 8);
2438 }
2439 else {
2440 memcpy(&x, p, 8);
2441 }
2442
2443 return x;
2444 }
Tim Peters9905b942003-03-20 20:53:32 +00002445}