blob: a2c281eaf8b5336836c954d170726d7aa8a1c27f [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"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Christian Heimes969fe572008-01-25 11:23:10 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Mark Dickinsond19052c2010-06-27 18:19:09 +000024/* Special free list
25
26 Since some Python programs can spend much of their time allocating
27 and deallocating floats, these operations should be very fast.
28 Therefore we use a dedicated allocation scheme with a much lower
29 overhead (in space and time) than straight malloc(): a simple
30 dedicated free list, filled when necessary with memory from malloc().
31
32 block_list is a singly-linked list of all PyFloatBlocks ever allocated,
33 linked via their next members. PyFloatBlocks are never returned to the
34 system before shutdown (PyFloat_Fini).
35
36 free_list is a singly-linked list of available PyFloatObjects, linked
37 via abuse of their ob_type members.
38*/
39
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
41#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
42#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000043
Guido van Rossum3fce8831999-03-12 19:43:17 +000044struct _floatblock {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 struct _floatblock *next;
46 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000047};
48
49typedef struct _floatblock PyFloatBlock;
50
51static PyFloatBlock *block_list = NULL;
52static PyFloatObject *free_list = NULL;
53
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000055fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 PyFloatObject *p, *q;
58 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
59 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
60 if (p == NULL)
61 return (PyFloatObject *) PyErr_NoMemory();
62 ((PyFloatBlock *)p)->next = block_list;
63 block_list = (PyFloatBlock *)p;
64 p = &((PyFloatBlock *)p)->objects[0];
65 q = p + N_FLOATOBJECTS;
66 while (--q > p)
67 Py_TYPE(q) = (struct _typeobject *)(q-1);
68 Py_TYPE(q) = NULL;
69 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000070}
71
Christian Heimes93852662007-12-01 12:22:32 +000072double
73PyFloat_GetMax(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000076}
77
78double
79PyFloat_GetMin(void)
80{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000082}
83
Christian Heimesd32ed6f2008-01-14 18:49:24 +000084static PyTypeObject FloatInfoType;
85
86PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000087"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000088\n\
89A structseq holding information about the float type. It contains low level\n\
90information about the precision and internal representation. Please study\n\
91your system's :file:`float.h` for more information.");
92
93static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 {"max", "DBL_MAX -- maximum representable finite float"},
95 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
96 "is representable"},
97 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
98 "is representable"},
99 {"min", "DBL_MIN -- Minimum positive normalizer float"},
100 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
101 "is a normalized float"},
102 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
103 "a normalized"},
104 {"dig", "DBL_DIG -- digits"},
105 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
106 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
107 "representable float"},
108 {"radix", "FLT_RADIX -- radix of exponent"},
109 {"rounds", "FLT_ROUNDS -- addition rounds"},
110 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000111};
112
113static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 "sys.float_info", /* name */
115 floatinfo__doc__, /* doc */
116 floatinfo_fields, /* fields */
117 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000118};
119
Christian Heimes93852662007-12-01 12:22:32 +0000120PyObject *
121PyFloat_GetInfo(void)
122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject* floatinfo;
124 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 floatinfo = PyStructSequence_New(&FloatInfoType);
127 if (floatinfo == NULL) {
128 return NULL;
129 }
Christian Heimes93852662007-12-01 12:22:32 +0000130
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000131#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000133#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 SetDblFlag(DBL_MAX);
137 SetIntFlag(DBL_MAX_EXP);
138 SetIntFlag(DBL_MAX_10_EXP);
139 SetDblFlag(DBL_MIN);
140 SetIntFlag(DBL_MIN_EXP);
141 SetIntFlag(DBL_MIN_10_EXP);
142 SetIntFlag(DBL_DIG);
143 SetIntFlag(DBL_MANT_DIG);
144 SetDblFlag(DBL_EPSILON);
145 SetIntFlag(FLT_RADIX);
146 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000147#undef SetIntFlag
148#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149
150 if (PyErr_Occurred()) {
151 Py_CLEAR(floatinfo);
152 return NULL;
153 }
154 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000155}
156
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 register PyFloatObject *op;
161 if (free_list == NULL) {
162 if ((free_list = fill_free_list()) == NULL)
163 return NULL;
164 }
165 /* Inline PyObject_New */
166 op = free_list;
167 free_list = (PyFloatObject *)Py_TYPE(op);
168 PyObject_INIT(op, &PyFloat_Type);
169 op->ob_fval = fval;
170 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171}
172
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000174PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 const char *s, *last, *end;
177 double x;
178 char buffer[256]; /* for errors */
179 char *s_buffer = NULL;
180 Py_ssize_t len;
181 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 if (PyUnicode_Check(v)) {
184 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
185 if (s_buffer == NULL)
186 return PyErr_NoMemory();
187 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
188 PyUnicode_GET_SIZE(v),
189 s_buffer,
190 NULL))
191 goto error;
192 s = s_buffer;
193 len = strlen(s);
194 }
195 else if (PyObject_AsCharBuffer(v, &s, &len)) {
196 PyErr_SetString(PyExc_TypeError,
197 "float() argument must be a string or a number");
198 return NULL;
199 }
200 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 while (Py_ISSPACE(*s))
203 s++;
204 /* We don't care about overflow or underflow. If the platform
205 * supports them, infinities and signed zeroes (on underflow) are
206 * fine. */
207 x = PyOS_string_to_double(s, (char **)&end, NULL);
208 if (x == -1.0 && PyErr_Occurred())
209 goto error;
210 while (Py_ISSPACE(*end))
211 end++;
212 if (end == last)
213 result = PyFloat_FromDouble(x);
214 else {
215 PyOS_snprintf(buffer, sizeof(buffer),
216 "invalid literal for float(): %.200s", s);
217 PyErr_SetString(PyExc_ValueError, buffer);
218 result = NULL;
219 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000220
Guido van Rossum2be161d2007-05-15 20:43:51 +0000221 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (s_buffer)
223 PyMem_FREE(s_buffer);
224 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000225}
226
Guido van Rossum234f9421993-06-17 12:35:49 +0000227static void
Fred Drakefd99de62000-07-09 05:02:18 +0000228float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (PyFloat_CheckExact(op)) {
231 Py_TYPE(op) = (struct _typeobject *)free_list;
232 free_list = op;
233 }
234 else
235 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000236}
237
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238double
Fred Drakefd99de62000-07-09 05:02:18 +0000239PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyNumberMethods *nb;
242 PyFloatObject *fo;
243 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (op && PyFloat_Check(op))
246 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (op == NULL) {
249 PyErr_BadArgument();
250 return -1;
251 }
Tim Petersd2364e82001-11-01 20:09:42 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
254 PyErr_SetString(PyExc_TypeError, "a float is required");
255 return -1;
256 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 fo = (PyFloatObject*) (*nb->nb_float) (op);
259 if (fo == NULL)
260 return -1;
261 if (!PyFloat_Check(fo)) {
262 PyErr_SetString(PyExc_TypeError,
263 "nb_float should return float object");
264 return -1;
265 }
Tim Petersd2364e82001-11-01 20:09:42 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 val = PyFloat_AS_DOUBLE(fo);
268 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271}
272
Neil Schemenauer32117e52001-01-04 01:44:34 +0000273/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000274 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000275 set to NULL, and the function invoking this macro returns NULL. If
276 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
277 stored in obj, and returned from the function invoking this macro.
278*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279#define CONVERT_TO_DOUBLE(obj, dbl) \
280 if (PyFloat_Check(obj)) \
281 dbl = PyFloat_AS_DOUBLE(obj); \
282 else if (convert_to_double(&(obj), &(dbl)) < 0) \
283 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000284
Eric Smith0923d1d2009-04-16 20:16:10 +0000285/* Methods */
286
Neil Schemenauer32117e52001-01-04 01:44:34 +0000287static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000288convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (PyLong_Check(obj)) {
293 *dbl = PyLong_AsDouble(obj);
294 if (*dbl == -1.0 && PyErr_Occurred()) {
295 *v = NULL;
296 return -1;
297 }
298 }
299 else {
300 Py_INCREF(Py_NotImplemented);
301 *v = Py_NotImplemented;
302 return -1;
303 }
304 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000305}
306
Eric Smith0923d1d2009-04-16 20:16:10 +0000307static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000308float_str_or_repr(PyFloatObject *v, int precision, char format_code)
Eric Smith0923d1d2009-04-16 20:16:10 +0000309{
310 PyObject *result;
311 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Eric Smith63376222009-05-05 14:04:18 +0000312 format_code, precision,
313 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000314 NULL);
315 if (!buf)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000317 result = PyUnicode_FromString(buf);
318 PyMem_Free(buf);
319 return result;
320}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000321
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000323float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324{
Eric Smith63376222009-05-05 14:04:18 +0000325 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000326}
327
328static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000329float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000330{
Eric Smith63376222009-05-05 14:04:18 +0000331 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332}
333
Tim Peters307fa782004-09-23 08:06:40 +0000334/* Comparison is pretty much a nightmare. When comparing float to float,
335 * we do it as straightforwardly (and long-windedly) as conceivable, so
336 * that, e.g., Python x == y delivers the same result as the platform
337 * C x == y when x and/or y is a NaN.
338 * When mixing float with an integer type, there's no good *uniform* approach.
339 * Converting the double to an integer obviously doesn't work, since we
340 * may lose info from fractional bits. Converting the integer to a double
341 * also has two failure modes: (1) a long int may trigger overflow (too
342 * large to fit in the dynamic range of a C double); (2) even a C long may have
343 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
344 * 63 bits of precision, but a C double probably has only 53), and then
345 * we can falsely claim equality when low-order integer bits are lost by
346 * coercion to double. So this part is painful too.
347 */
348
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000349static PyObject*
350float_richcompare(PyObject *v, PyObject *w, int op)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 double i, j;
353 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 assert(PyFloat_Check(v));
356 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 /* Switch on the type of w. Set i and j to doubles to be compared,
359 * and op to the richcomp to use.
360 */
361 if (PyFloat_Check(w))
362 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 else if (!Py_IS_FINITE(i)) {
365 if (PyLong_Check(w))
366 /* If i is an infinity, its magnitude exceeds any
367 * finite integer, so it doesn't matter which int we
368 * compare i with. If i is a NaN, similarly.
369 */
370 j = 0.0;
371 else
372 goto Unimplemented;
373 }
Tim Peters307fa782004-09-23 08:06:40 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 else if (PyLong_Check(w)) {
376 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
377 int wsign = _PyLong_Sign(w);
378 size_t nbits;
379 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (vsign != wsign) {
382 /* Magnitudes are irrelevant -- the signs alone
383 * determine the outcome.
384 */
385 i = (double)vsign;
386 j = (double)wsign;
387 goto Compare;
388 }
389 /* The signs are the same. */
390 /* Convert w to a double if it fits. In particular, 0 fits. */
391 nbits = _PyLong_NumBits(w);
392 if (nbits == (size_t)-1 && PyErr_Occurred()) {
393 /* This long is so large that size_t isn't big enough
394 * to hold the # of bits. Replace with little doubles
395 * that give the same outcome -- w is so large that
396 * its magnitude must exceed the magnitude of any
397 * finite float.
398 */
399 PyErr_Clear();
400 i = (double)vsign;
401 assert(wsign != 0);
402 j = wsign * 2.0;
403 goto Compare;
404 }
405 if (nbits <= 48) {
406 j = PyLong_AsDouble(w);
407 /* It's impossible that <= 48 bits overflowed. */
408 assert(j != -1.0 || ! PyErr_Occurred());
409 goto Compare;
410 }
411 assert(wsign != 0); /* else nbits was 0 */
412 assert(vsign != 0); /* if vsign were 0, then since wsign is
413 * not 0, we would have taken the
414 * vsign != wsign branch at the start */
415 /* We want to work with non-negative numbers. */
416 if (vsign < 0) {
417 /* "Multiply both sides" by -1; this also swaps the
418 * comparator.
419 */
420 i = -i;
421 op = _Py_SwappedOp[op];
422 }
423 assert(i > 0.0);
424 (void) frexp(i, &exponent);
425 /* exponent is the # of bits in v before the radix point;
426 * we know that nbits (the # of bits in w) > 48 at this point
427 */
428 if (exponent < 0 || (size_t)exponent < nbits) {
429 i = 1.0;
430 j = 2.0;
431 goto Compare;
432 }
433 if ((size_t)exponent > nbits) {
434 i = 2.0;
435 j = 1.0;
436 goto Compare;
437 }
438 /* v and w have the same number of bits before the radix
439 * point. Construct two longs that have the same comparison
440 * outcome.
441 */
442 {
443 double fracpart;
444 double intpart;
445 PyObject *result = NULL;
446 PyObject *one = NULL;
447 PyObject *vv = NULL;
448 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (wsign < 0) {
451 ww = PyNumber_Negative(w);
452 if (ww == NULL)
453 goto Error;
454 }
455 else
456 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 fracpart = modf(i, &intpart);
459 vv = PyLong_FromDouble(intpart);
460 if (vv == NULL)
461 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (fracpart != 0.0) {
464 /* Shift left, and or a 1 bit into vv
465 * to represent the lost fraction.
466 */
467 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 one = PyLong_FromLong(1);
470 if (one == NULL)
471 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 temp = PyNumber_Lshift(ww, one);
474 if (temp == NULL)
475 goto Error;
476 Py_DECREF(ww);
477 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 temp = PyNumber_Lshift(vv, one);
480 if (temp == NULL)
481 goto Error;
482 Py_DECREF(vv);
483 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 temp = PyNumber_Or(vv, one);
486 if (temp == NULL)
487 goto Error;
488 Py_DECREF(vv);
489 vv = temp;
490 }
Tim Peters307fa782004-09-23 08:06:40 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 r = PyObject_RichCompareBool(vv, ww, op);
493 if (r < 0)
494 goto Error;
495 result = PyBool_FromLong(r);
496 Error:
497 Py_XDECREF(vv);
498 Py_XDECREF(ww);
499 Py_XDECREF(one);
500 return result;
501 }
502 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 else /* w isn't float, int, or long */
505 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000506
507 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyFPE_START_PROTECT("richcompare", return NULL)
509 switch (op) {
510 case Py_EQ:
511 r = i == j;
512 break;
513 case Py_NE:
514 r = i != j;
515 break;
516 case Py_LE:
517 r = i <= j;
518 break;
519 case Py_GE:
520 r = i >= j;
521 break;
522 case Py_LT:
523 r = i < j;
524 break;
525 case Py_GT:
526 r = i > j;
527 break;
528 }
529 PyFPE_END_PROTECT(r)
530 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000531
532 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 Py_INCREF(Py_NotImplemented);
534 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000535}
536
Guido van Rossum9bfef441993-03-29 10:43:31 +0000537static long
Fred Drakefd99de62000-07-09 05:02:18 +0000538float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000541}
542
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000544float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 double a,b;
547 CONVERT_TO_DOUBLE(v, a);
548 CONVERT_TO_DOUBLE(w, b);
549 PyFPE_START_PROTECT("add", return 0)
550 a = a + b;
551 PyFPE_END_PROTECT(a)
552 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000556float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 double a,b;
559 CONVERT_TO_DOUBLE(v, a);
560 CONVERT_TO_DOUBLE(w, b);
561 PyFPE_START_PROTECT("subtract", return 0)
562 a = a - b;
563 PyFPE_END_PROTECT(a)
564 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565}
566
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000568float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 double a,b;
571 CONVERT_TO_DOUBLE(v, a);
572 CONVERT_TO_DOUBLE(w, b);
573 PyFPE_START_PROTECT("multiply", return 0)
574 a = a * b;
575 PyFPE_END_PROTECT(a)
576 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000577}
578
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000579static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000580float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 double a,b;
583 CONVERT_TO_DOUBLE(v, a);
584 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000585#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (b == 0.0) {
587 PyErr_SetString(PyExc_ZeroDivisionError,
588 "float division by zero");
589 return NULL;
590 }
Christian Heimes53876d92008-04-19 00:31:39 +0000591#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyFPE_START_PROTECT("divide", return 0)
593 a = a / b;
594 PyFPE_END_PROTECT(a)
595 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000596}
597
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000598static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000599float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 double vx, wx;
602 double mod;
603 CONVERT_TO_DOUBLE(v, vx);
604 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000605#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (wx == 0.0) {
607 PyErr_SetString(PyExc_ZeroDivisionError,
608 "float modulo");
609 return NULL;
610 }
Christian Heimes53876d92008-04-19 00:31:39 +0000611#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyFPE_START_PROTECT("modulo", return 0)
613 mod = fmod(vx, wx);
614 /* note: checking mod*wx < 0 is incorrect -- underflows to
615 0 if wx < sqrt(smallest nonzero double) */
616 if (mod && ((wx < 0) != (mod < 0))) {
617 mod += wx;
618 }
619 PyFPE_END_PROTECT(mod)
620 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621}
622
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000624float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 double vx, wx;
627 double div, mod, floordiv;
628 CONVERT_TO_DOUBLE(v, vx);
629 CONVERT_TO_DOUBLE(w, wx);
630 if (wx == 0.0) {
631 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
632 return NULL;
633 }
634 PyFPE_START_PROTECT("divmod", return 0)
635 mod = fmod(vx, wx);
636 /* fmod is typically exact, so vx-mod is *mathematically* an
637 exact multiple of wx. But this is fp arithmetic, and fp
638 vx - mod is an approximation; the result is that div may
639 not be an exact integral value after the division, although
640 it will always be very close to one.
641 */
642 div = (vx - mod) / wx;
643 if (mod) {
644 /* ensure the remainder has the same sign as the denominator */
645 if ((wx < 0) != (mod < 0)) {
646 mod += wx;
647 div -= 1.0;
648 }
649 }
650 else {
651 /* the remainder is zero, and in the presence of signed zeroes
652 fmod returns different results across platforms; ensure
653 it has the same sign as the denominator; we'd like to do
654 "mod = wx * 0.0", but that may get optimized away */
655 mod *= mod; /* hide "mod = +0" from optimizer */
656 if (wx < 0.0)
657 mod = -mod;
658 }
659 /* snap quotient to nearest integral value */
660 if (div) {
661 floordiv = floor(div);
662 if (div - floordiv > 0.5)
663 floordiv += 1.0;
664 }
665 else {
666 /* div is zero - get the same sign as the true quotient */
667 div *= div; /* hide "div = +0" from optimizers */
668 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
669 }
670 PyFPE_END_PROTECT(floordiv)
671 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000672}
673
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000675float_floor_div(PyObject *v, PyObject *w)
676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 t = float_divmod(v, w);
680 if (t == NULL || t == Py_NotImplemented)
681 return t;
682 assert(PyTuple_CheckExact(t));
683 r = PyTuple_GET_ITEM(t, 0);
684 Py_INCREF(r);
685 Py_DECREF(t);
686 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000687}
688
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000689/* determine whether x is an odd integer or not; assumes that
690 x is not an infinity or nan. */
691#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
692
Tim Peters63a35712001-12-11 19:57:24 +0000693static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000694float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 double iv, iw, ix;
697 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 if ((PyObject *)z != Py_None) {
700 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
701 "allowed unless all arguments are integers");
702 return NULL;
703 }
Tim Peters32f453e2001-09-03 08:35:41 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 CONVERT_TO_DOUBLE(v, iv);
706 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 /* Sort out special cases here instead of relying on pow() */
709 if (iw == 0) { /* v**0 is 1, even 0**0 */
710 return PyFloat_FromDouble(1.0);
711 }
712 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
713 return PyFloat_FromDouble(iv);
714 }
715 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
716 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
717 }
718 if (Py_IS_INFINITY(iw)) {
719 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
720 * abs(v) > 1 (including case where v infinite)
721 *
722 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
723 * abs(v) > 1 (including case where v infinite)
724 */
725 iv = fabs(iv);
726 if (iv == 1.0)
727 return PyFloat_FromDouble(1.0);
728 else if ((iw > 0.0) == (iv > 1.0))
729 return PyFloat_FromDouble(fabs(iw)); /* return inf */
730 else
731 return PyFloat_FromDouble(0.0);
732 }
733 if (Py_IS_INFINITY(iv)) {
734 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
735 * both cases, we need to add the appropriate sign if w is
736 * an odd integer.
737 */
738 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
739 if (iw > 0.0)
740 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
741 else
742 return PyFloat_FromDouble(iw_is_odd ?
743 copysign(0.0, iv) : 0.0);
744 }
745 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
746 (already dealt with above), and an error
747 if w is negative. */
748 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
749 if (iw < 0.0) {
750 PyErr_SetString(PyExc_ZeroDivisionError,
751 "0.0 cannot be raised to a "
752 "negative power");
753 return NULL;
754 }
755 /* use correct sign if iw is odd */
756 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
757 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if (iv < 0.0) {
760 /* Whether this is an error is a mess, and bumps into libm
761 * bugs so we have to figure it out ourselves.
762 */
763 if (iw != floor(iw)) {
764 /* Negative numbers raised to fractional powers
765 * become complex.
766 */
767 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
768 }
769 /* iw is an exact integer, albeit perhaps a very large
770 * one. Replace iv by its absolute value and remember
771 * to negate the pow result if iw is odd.
772 */
773 iv = -iv;
774 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
775 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
778 /* (-1) ** large_integer also ends up here. Here's an
779 * extract from the comments for the previous
780 * implementation explaining why this special case is
781 * necessary:
782 *
783 * -1 raised to an exact integer should never be exceptional.
784 * Alas, some libms (chiefly glibc as of early 2003) return
785 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
786 * happen to be representable in a *C* integer. That's a
787 * bug.
788 */
789 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
790 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* Now iv and iw are finite, iw is nonzero, and iv is
793 * positive and not equal to 1.0. We finally allow
794 * the platform pow to step in and do the rest.
795 */
796 errno = 0;
797 PyFPE_START_PROTECT("pow", return NULL)
798 ix = pow(iv, iw);
799 PyFPE_END_PROTECT(ix)
800 Py_ADJUST_ERANGE1(ix);
801 if (negate_result)
802 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 if (errno != 0) {
805 /* We don't expect any errno value other than ERANGE, but
806 * the range of libm bugs appears unbounded.
807 */
808 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
809 PyExc_ValueError);
810 return NULL;
811 }
812 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000815#undef DOUBLE_IS_ODD_INTEGER
816
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000817static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000818float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821}
822
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000823static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000824float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000827}
828
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000829static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000830float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000836float_is_integer(PyObject *v)
837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 double x = PyFloat_AsDouble(v);
839 PyObject *o;
840
841 if (x == -1.0 && PyErr_Occurred())
842 return NULL;
843 if (!Py_IS_FINITE(x))
844 Py_RETURN_FALSE;
845 errno = 0;
846 PyFPE_START_PROTECT("is_integer", return NULL)
847 o = (floor(x) == x) ? Py_True : Py_False;
848 PyFPE_END_PROTECT(x)
849 if (errno != 0) {
850 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
851 PyExc_ValueError);
852 return NULL;
853 }
854 Py_INCREF(o);
855 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000856}
857
858#if 0
859static PyObject *
860float_is_inf(PyObject *v)
861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 double x = PyFloat_AsDouble(v);
863 if (x == -1.0 && PyErr_Occurred())
864 return NULL;
865 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000866}
867
868static PyObject *
869float_is_nan(PyObject *v)
870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 double x = PyFloat_AsDouble(v);
872 if (x == -1.0 && PyErr_Occurred())
873 return NULL;
874 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000875}
876
877static PyObject *
878float_is_finite(PyObject *v)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 double x = PyFloat_AsDouble(v);
881 if (x == -1.0 && PyErr_Occurred())
882 return NULL;
883 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000884}
885#endif
886
887static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000888float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 double x = PyFloat_AsDouble(v);
891 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 (void)modf(x, &wholepart);
894 /* Try to get out cheap if this fits in a Python int. The attempt
895 * to cast to long must be protected, as C doesn't define what
896 * happens if the double is too big to fit in a long. Some rare
897 * systems raise an exception then (RISCOS was mentioned as one,
898 * and someone using a non-default option on Sun also bumped into
899 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
900 * still be vulnerable: if a long has more bits of precision than
901 * a double, casting MIN/MAX to double may yield an approximation,
902 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
903 * yield true from the C expression wholepart<=LONG_MAX, despite
904 * that wholepart is actually greater than LONG_MAX.
905 */
906 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
907 const long aslong = (long)wholepart;
908 return PyLong_FromLong(aslong);
909 }
910 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000911}
912
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000913/* double_round: rounds a finite double to the closest multiple of
914 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
915 ndigits <= 323). Returns a Python float, or sets a Python error and
916 returns NULL on failure (OverflowError and memory errors are possible). */
917
918#ifndef PY_NO_SHORT_FLOAT_REPR
919/* version of double_round that uses the correctly-rounded string<->double
920 conversions from Python/dtoa.c */
921
922static PyObject *
923double_round(double x, int ndigits) {
924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 double rounded;
926 Py_ssize_t buflen, mybuflen=100;
927 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
928 int decpt, sign;
929 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* round to a decimal string */
932 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
933 if (buf == NULL) {
934 PyErr_NoMemory();
935 return NULL;
936 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
939 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
940 buflen = buf_end - buf;
941 if (buflen + 8 > mybuflen) {
942 mybuflen = buflen+8;
943 mybuf = (char *)PyMem_Malloc(mybuflen);
944 if (mybuf == NULL) {
945 PyErr_NoMemory();
946 goto exit;
947 }
948 }
949 /* copy buf to mybuf, adding exponent, sign and leading 0 */
950 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
951 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* and convert the resulting string back to a double */
954 errno = 0;
955 rounded = _Py_dg_strtod(mybuf, NULL);
956 if (errno == ERANGE && fabs(rounded) >= 1.)
957 PyErr_SetString(PyExc_OverflowError,
958 "rounded value too large to represent");
959 else
960 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* done computing value; now clean up */
963 if (mybuf != shortbuf)
964 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000965 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 _Py_dg_freedtoa(buf);
967 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000968}
969
970#else /* PY_NO_SHORT_FLOAT_REPR */
971
972/* fallback version, to be used when correctly rounded binary<->decimal
973 conversions aren't available */
974
975static PyObject *
976double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 double pow1, pow2, y, z;
978 if (ndigits >= 0) {
979 if (ndigits > 22) {
980 /* pow1 and pow2 are each safe from overflow, but
981 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
982 pow1 = pow(10.0, (double)(ndigits-22));
983 pow2 = 1e22;
984 }
985 else {
986 pow1 = pow(10.0, (double)ndigits);
987 pow2 = 1.0;
988 }
989 y = (x*pow1)*pow2;
990 /* if y overflows, then rounded value is exactly x */
991 if (!Py_IS_FINITE(y))
992 return PyFloat_FromDouble(x);
993 }
994 else {
995 pow1 = pow(10.0, (double)-ndigits);
996 pow2 = 1.0; /* unused; silences a gcc compiler warning */
997 y = x / pow1;
998 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 z = round(y);
1001 if (fabs(y-z) == 0.5)
1002 /* halfway between two integers; use round-half-even */
1003 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (ndigits >= 0)
1006 z = (z / pow2) / pow1;
1007 else
1008 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* if computation resulted in overflow, raise OverflowError */
1011 if (!Py_IS_FINITE(z)) {
1012 PyErr_SetString(PyExc_OverflowError,
1013 "overflow occurred during round");
1014 return NULL;
1015 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001018}
1019
1020#endif /* PY_NO_SHORT_FLOAT_REPR */
1021
1022/* round a Python float v to the closest multiple of 10**-ndigits */
1023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001025float_round(PyObject *v, PyObject *args)
1026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 double x, rounded;
1028 PyObject *o_ndigits = NULL;
1029 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 x = PyFloat_AsDouble(v);
1032 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1033 return NULL;
1034 if (o_ndigits == NULL) {
1035 /* single-argument round: round to nearest integer */
1036 rounded = round(x);
1037 if (fabs(x-rounded) == 0.5)
1038 /* halfway case: round to even */
1039 rounded = 2.0*round(x/2.0);
1040 return PyLong_FromDouble(rounded);
1041 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* interpret second argument as a Py_ssize_t; clips on overflow */
1044 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1045 if (ndigits == -1 && PyErr_Occurred())
1046 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* nans and infinities round to themselves */
1049 if (!Py_IS_FINITE(x))
1050 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1053 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1054 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001055#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1056#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (ndigits > NDIGITS_MAX)
1058 /* return x */
1059 return PyFloat_FromDouble(x);
1060 else if (ndigits < NDIGITS_MIN)
1061 /* return 0.0, but with sign of x */
1062 return PyFloat_FromDouble(0.0*x);
1063 else
1064 /* finite x, and ndigits is not unreasonably large */
1065 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001066#undef NDIGITS_MAX
1067#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001068}
1069
1070static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001071float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (PyFloat_CheckExact(v))
1074 Py_INCREF(v);
1075 else
1076 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1077 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001078}
1079
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001080/* turn ASCII hex characters into integer values and vice versa */
1081
1082static char
1083char_from_hex(int x)
1084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 assert(0 <= x && x < 16);
1086 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001087}
1088
1089static int
1090hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 int x;
1092 switch(c) {
1093 case '0':
1094 x = 0;
1095 break;
1096 case '1':
1097 x = 1;
1098 break;
1099 case '2':
1100 x = 2;
1101 break;
1102 case '3':
1103 x = 3;
1104 break;
1105 case '4':
1106 x = 4;
1107 break;
1108 case '5':
1109 x = 5;
1110 break;
1111 case '6':
1112 x = 6;
1113 break;
1114 case '7':
1115 x = 7;
1116 break;
1117 case '8':
1118 x = 8;
1119 break;
1120 case '9':
1121 x = 9;
1122 break;
1123 case 'a':
1124 case 'A':
1125 x = 10;
1126 break;
1127 case 'b':
1128 case 'B':
1129 x = 11;
1130 break;
1131 case 'c':
1132 case 'C':
1133 x = 12;
1134 break;
1135 case 'd':
1136 case 'D':
1137 x = 13;
1138 break;
1139 case 'e':
1140 case 'E':
1141 x = 14;
1142 break;
1143 case 'f':
1144 case 'F':
1145 x = 15;
1146 break;
1147 default:
1148 x = -1;
1149 break;
1150 }
1151 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001152}
1153
1154/* convert a float to a hexadecimal string */
1155
1156/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1157 of the form 4k+1. */
1158#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1159
1160static PyObject *
1161float_hex(PyObject *v)
1162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 double x, m;
1164 int e, shift, i, si, esign;
1165 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1166 trailing NUL byte. */
1167 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1172 return float_str((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (x == 0.0) {
1175 if(copysign(1.0, x) == -1.0)
1176 return PyUnicode_FromString("-0x0.0p+0");
1177 else
1178 return PyUnicode_FromString("0x0.0p+0");
1179 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 m = frexp(fabs(x), &e);
1182 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1183 m = ldexp(m, shift);
1184 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 si = 0;
1187 s[si] = char_from_hex((int)m);
1188 si++;
1189 m -= (int)m;
1190 s[si] = '.';
1191 si++;
1192 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1193 m *= 16.0;
1194 s[si] = char_from_hex((int)m);
1195 si++;
1196 m -= (int)m;
1197 }
1198 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (e < 0) {
1201 esign = (int)'-';
1202 e = -e;
1203 }
1204 else
1205 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (x < 0.0)
1208 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1209 else
1210 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001211}
1212
1213PyDoc_STRVAR(float_hex_doc,
1214"float.hex() -> string\n\
1215\n\
1216Return a hexadecimal representation of a floating-point number.\n\
1217>>> (-0.1).hex()\n\
1218'-0x1.999999999999ap-4'\n\
1219>>> 3.14159.hex()\n\
1220'0x1.921f9f01b866ep+1'");
1221
1222/* Convert a hexadecimal string to a float. */
1223
1224static PyObject *
1225float_fromhex(PyObject *cls, PyObject *arg)
1226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 PyObject *result_as_float, *result;
1228 double x;
1229 long exp, top_exp, lsb, key_digit;
1230 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1231 int half_eps, digit, round_up, negate=0;
1232 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /*
1235 * For the sake of simplicity and correctness, we impose an artificial
1236 * limit on ndigits, the total number of hex digits in the coefficient
1237 * The limit is chosen to ensure that, writing exp for the exponent,
1238 *
1239 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1240 * guaranteed to overflow (provided it's nonzero)
1241 *
1242 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1243 * guaranteed to underflow to 0.
1244 *
1245 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1246 * overflow in the calculation of exp and top_exp below.
1247 *
1248 * More specifically, ndigits is assumed to satisfy the following
1249 * inequalities:
1250 *
1251 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1252 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1253 *
1254 * If either of these inequalities is not satisfied, a ValueError is
1255 * raised. Otherwise, write x for the value of the hex string, and
1256 * assume x is nonzero. Then
1257 *
1258 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1259 *
1260 * Now if exp > LONG_MAX/2 then:
1261 *
1262 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1263 * = DBL_MAX_EXP
1264 *
1265 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1266 * double, so overflows. If exp < LONG_MIN/2, then
1267 *
1268 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1269 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1270 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1271 *
1272 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1273 * when converted to a C double.
1274 *
1275 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1276 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1277 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 s = _PyUnicode_AsStringAndSize(arg, &length);
1280 if (s == NULL)
1281 return NULL;
1282 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /********************
1285 * Parse the string *
1286 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* leading whitespace */
1289 while (Py_ISSPACE(*s))
1290 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* infinities and nans */
1293 x = _Py_parse_inf_or_nan(s, &coeff_end);
1294 if (coeff_end != s) {
1295 s = coeff_end;
1296 goto finished;
1297 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* optional sign */
1300 if (*s == '-') {
1301 s++;
1302 negate = 1;
1303 }
1304 else if (*s == '+')
1305 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* [0x] */
1308 s_store = s;
1309 if (*s == '0') {
1310 s++;
1311 if (*s == 'x' || *s == 'X')
1312 s++;
1313 else
1314 s = s_store;
1315 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /* coefficient: <integer> [. <fraction>] */
1318 coeff_start = s;
1319 while (hex_from_char(*s) >= 0)
1320 s++;
1321 s_store = s;
1322 if (*s == '.') {
1323 s++;
1324 while (hex_from_char(*s) >= 0)
1325 s++;
1326 coeff_end = s-1;
1327 }
1328 else
1329 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* ndigits = total # of hex digits; fdigits = # after point */
1332 ndigits = coeff_end - coeff_start;
1333 fdigits = coeff_end - s_store;
1334 if (ndigits == 0)
1335 goto parse_error;
1336 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1337 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1338 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* [p <exponent>] */
1341 if (*s == 'p' || *s == 'P') {
1342 s++;
1343 exp_start = s;
1344 if (*s == '-' || *s == '+')
1345 s++;
1346 if (!('0' <= *s && *s <= '9'))
1347 goto parse_error;
1348 s++;
1349 while ('0' <= *s && *s <= '9')
1350 s++;
1351 exp = strtol(exp_start, NULL, 10);
1352 }
1353 else
1354 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001355
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001356/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1358 coeff_end-(j) : \
1359 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /*******************************************
1362 * Compute rounded value of the hex string *
1363 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 /* Discard leading zeros, and catch extreme overflow and underflow */
1366 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1367 ndigits--;
1368 if (ndigits == 0 || exp < LONG_MIN/2) {
1369 x = 0.0;
1370 goto finished;
1371 }
1372 if (exp > LONG_MAX/2)
1373 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* Adjust exponent for fractional part. */
1376 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1379 top_exp = exp + 4*((long)ndigits - 1);
1380 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1381 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* catch almost all nonextreme cases of overflow and underflow here */
1384 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1385 x = 0.0;
1386 goto finished;
1387 }
1388 if (top_exp > DBL_MAX_EXP)
1389 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* lsb = exponent of least significant bit of the *rounded* value.
1392 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1393 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 x = 0.0;
1396 if (exp >= lsb) {
1397 /* no rounding required */
1398 for (i = ndigits-1; i >= 0; i--)
1399 x = 16.0*x + HEX_DIGIT(i);
1400 x = ldexp(x, (int)(exp));
1401 goto finished;
1402 }
1403 /* rounding required. key_digit is the index of the hex digit
1404 containing the first bit to be rounded away. */
1405 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1406 key_digit = (lsb - exp - 1) / 4;
1407 for (i = ndigits-1; i > key_digit; i--)
1408 x = 16.0*x + HEX_DIGIT(i);
1409 digit = HEX_DIGIT(key_digit);
1410 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1413 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1414 if ((digit & half_eps) != 0) {
1415 round_up = 0;
1416 if ((digit & (3*half_eps-1)) != 0 ||
1417 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1418 round_up = 1;
1419 else
1420 for (i = key_digit-1; i >= 0; i--)
1421 if (HEX_DIGIT(i) != 0) {
1422 round_up = 1;
1423 break;
1424 }
1425 if (round_up == 1) {
1426 x += 2*half_eps;
1427 if (top_exp == DBL_MAX_EXP &&
1428 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1429 /* overflow corner case: pre-rounded value <
1430 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1431 goto overflow_error;
1432 }
1433 }
1434 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001435
1436 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 /* optional trailing whitespace leading to the end of the string */
1438 while (Py_ISSPACE(*s))
1439 s++;
1440 if (s != s_end)
1441 goto parse_error;
1442 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1443 if (result_as_float == NULL)
1444 return NULL;
1445 result = PyObject_CallObject(cls, result_as_float);
1446 Py_DECREF(result_as_float);
1447 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001448
1449 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyErr_SetString(PyExc_OverflowError,
1451 "hexadecimal value too large to represent as a float");
1452 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001453
1454 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyErr_SetString(PyExc_ValueError,
1456 "invalid hexadecimal floating-point string");
1457 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001458
1459 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 PyErr_SetString(PyExc_ValueError,
1461 "hexadecimal string too long to convert");
1462 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001463}
1464
1465PyDoc_STRVAR(float_fromhex_doc,
1466"float.fromhex(string) -> float\n\
1467\n\
1468Create a floating-point number from a hexadecimal string.\n\
1469>>> float.fromhex('0x1.ffffp10')\n\
14702047.984375\n\
1471>>> float.fromhex('-0x1p-1074')\n\
1472-4.9406564584124654e-324");
1473
1474
Christian Heimes26855632008-01-27 23:50:43 +00001475static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001476float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 double self;
1479 double float_part;
1480 int exponent;
1481 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyObject *prev;
1484 PyObject *py_exponent = NULL;
1485 PyObject *numerator = NULL;
1486 PyObject *denominator = NULL;
1487 PyObject *result_pair = NULL;
1488 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001489
1490#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 prev = obj; \
1492 obj = call; \
1493 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (Py_IS_INFINITY(self)) {
1498 PyErr_SetString(PyExc_OverflowError,
1499 "Cannot pass infinity to float.as_integer_ratio.");
1500 return NULL;
1501 }
Christian Heimes26855632008-01-27 23:50:43 +00001502#ifdef Py_NAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (Py_IS_NAN(self)) {
1504 PyErr_SetString(PyExc_ValueError,
1505 "Cannot pass NaN to float.as_integer_ratio.");
1506 return NULL;
1507 }
Christian Heimes26855632008-01-27 23:50:43 +00001508#endif
1509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1511 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1512 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1515 float_part *= 2.0;
1516 exponent--;
1517 }
1518 /* self == float_part * 2**exponent exactly and float_part is integral.
1519 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1520 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 numerator = PyLong_FromDouble(float_part);
1523 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 /* fold in 2**exponent */
1526 denominator = PyLong_FromLong(1);
1527 py_exponent = PyLong_FromLong(labs((long)exponent));
1528 if (py_exponent == NULL) goto error;
1529 INPLACE_UPDATE(py_exponent,
1530 long_methods->nb_lshift(denominator, py_exponent));
1531 if (py_exponent == NULL) goto error;
1532 if (exponent > 0) {
1533 INPLACE_UPDATE(numerator,
1534 long_methods->nb_multiply(numerator, py_exponent));
1535 if (numerator == NULL) goto error;
1536 }
1537 else {
1538 Py_DECREF(denominator);
1539 denominator = py_exponent;
1540 py_exponent = NULL;
1541 }
1542
1543 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001544
1545#undef INPLACE_UPDATE
1546error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 Py_XDECREF(py_exponent);
1548 Py_XDECREF(denominator);
1549 Py_XDECREF(numerator);
1550 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001551}
1552
1553PyDoc_STRVAR(float_as_integer_ratio_doc,
1554"float.as_integer_ratio() -> (int, int)\n"
1555"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001556"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1557"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001558"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001559"\n"
1560">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001561"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001562">>> (0.0).as_integer_ratio()\n"
1563"(0, 1)\n"
1564">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001565"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001566
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001567
Jeremy Hylton938ace62002-07-17 16:30:39 +00001568static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001569float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1570
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571static PyObject *
1572float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyObject *x = Py_False; /* Integer zero */
1575 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (type != &PyFloat_Type)
1578 return float_subtype_new(type, args, kwds); /* Wimp out */
1579 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1580 return NULL;
1581 /* If it's a string, but not a string subclass, use
1582 PyFloat_FromString. */
1583 if (PyUnicode_CheckExact(x))
1584 return PyFloat_FromString(x);
1585 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586}
1587
Guido van Rossumbef14172001-08-29 15:47:46 +00001588/* Wimpy, slow approach to tp_new calls for subtypes of float:
1589 first create a regular float from whatever arguments we got,
1590 then allocate a subtype instance and initialize its ob_fval
1591 from the regular float. The regular float is then thrown away.
1592*/
1593static PyObject *
1594float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 assert(PyType_IsSubtype(type, &PyFloat_Type));
1599 tmp = float_new(&PyFloat_Type, args, kwds);
1600 if (tmp == NULL)
1601 return NULL;
1602 assert(PyFloat_CheckExact(tmp));
1603 newobj = type->tp_alloc(type, 0);
1604 if (newobj == NULL) {
1605 Py_DECREF(tmp);
1606 return NULL;
1607 }
1608 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1609 Py_DECREF(tmp);
1610 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001611}
1612
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001613static PyObject *
1614float_getnewargs(PyFloatObject *v)
1615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001617}
1618
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001619/* this is for the benefit of the pack/unpack routines below */
1620
1621typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001623} float_format_type;
1624
1625static float_format_type double_format, float_format;
1626static float_format_type detected_double_format, detected_float_format;
1627
1628static PyObject *
1629float_getformat(PyTypeObject *v, PyObject* arg)
1630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 char* s;
1632 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (!PyUnicode_Check(arg)) {
1635 PyErr_Format(PyExc_TypeError,
1636 "__getformat__() argument must be string, not %.500s",
1637 Py_TYPE(arg)->tp_name);
1638 return NULL;
1639 }
1640 s = _PyUnicode_AsString(arg);
1641 if (s == NULL)
1642 return NULL;
1643 if (strcmp(s, "double") == 0) {
1644 r = double_format;
1645 }
1646 else if (strcmp(s, "float") == 0) {
1647 r = float_format;
1648 }
1649 else {
1650 PyErr_SetString(PyExc_ValueError,
1651 "__getformat__() argument 1 must be "
1652 "'double' or 'float'");
1653 return NULL;
1654 }
1655
1656 switch (r) {
1657 case unknown_format:
1658 return PyUnicode_FromString("unknown");
1659 case ieee_little_endian_format:
1660 return PyUnicode_FromString("IEEE, little-endian");
1661 case ieee_big_endian_format:
1662 return PyUnicode_FromString("IEEE, big-endian");
1663 default:
1664 Py_FatalError("insane float_format or double_format");
1665 return NULL;
1666 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001667}
1668
1669PyDoc_STRVAR(float_getformat_doc,
1670"float.__getformat__(typestr) -> string\n"
1671"\n"
1672"You probably don't want to use this function. It exists mainly to be\n"
1673"used in Python's test suite.\n"
1674"\n"
1675"typestr must be 'double' or 'float'. This function returns whichever of\n"
1676"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1677"format of floating point numbers used by the C type named by typestr.");
1678
1679static PyObject *
1680float_setformat(PyTypeObject *v, PyObject* args)
1681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 char* typestr;
1683 char* format;
1684 float_format_type f;
1685 float_format_type detected;
1686 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1689 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 if (strcmp(typestr, "double") == 0) {
1692 p = &double_format;
1693 detected = detected_double_format;
1694 }
1695 else if (strcmp(typestr, "float") == 0) {
1696 p = &float_format;
1697 detected = detected_float_format;
1698 }
1699 else {
1700 PyErr_SetString(PyExc_ValueError,
1701 "__setformat__() argument 1 must "
1702 "be 'double' or 'float'");
1703 return NULL;
1704 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (strcmp(format, "unknown") == 0) {
1707 f = unknown_format;
1708 }
1709 else if (strcmp(format, "IEEE, little-endian") == 0) {
1710 f = ieee_little_endian_format;
1711 }
1712 else if (strcmp(format, "IEEE, big-endian") == 0) {
1713 f = ieee_big_endian_format;
1714 }
1715 else {
1716 PyErr_SetString(PyExc_ValueError,
1717 "__setformat__() argument 2 must be "
1718 "'unknown', 'IEEE, little-endian' or "
1719 "'IEEE, big-endian'");
1720 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (f != unknown_format && f != detected) {
1725 PyErr_Format(PyExc_ValueError,
1726 "can only set %s format to 'unknown' or the "
1727 "detected platform value", typestr);
1728 return NULL;
1729 }
1730
1731 *p = f;
1732 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001733}
1734
1735PyDoc_STRVAR(float_setformat_doc,
1736"float.__setformat__(typestr, fmt) -> None\n"
1737"\n"
1738"You probably don't want to use this function. It exists mainly to be\n"
1739"used in Python's test suite.\n"
1740"\n"
1741"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1742"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1743"one of the latter two if it appears to match the underlying C reality.\n"
1744"\n"
1745"Overrides the automatic determination of C-level floating point type.\n"
1746"This affects how floats are converted to and from binary strings.");
1747
Guido van Rossumb43daf72007-08-01 18:08:08 +00001748static PyObject *
1749float_getzero(PyObject *v, void *closure)
1750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001752}
1753
Eric Smith8c663262007-08-25 02:26:07 +00001754static PyObject *
1755float__format__(PyObject *self, PyObject *args)
1756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1760 return NULL;
1761 return _PyFloat_FormatAdvanced(self,
1762 PyUnicode_AS_UNICODE(format_spec),
1763 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001764}
1765
1766PyDoc_STRVAR(float__format__doc,
1767"float.__format__(format_spec) -> string\n"
1768"\n"
1769"Formats the float according to format_spec.");
1770
1771
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001772static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1774 "Returns self, the complex conjugate of any float."},
1775 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1776 "Returns the Integral closest to x between 0 and x."},
1777 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1778 "Returns the Integral closest to x, rounding half toward even.\n"
1779 "When an argument is passed, works like built-in round(x, ndigits)."},
1780 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1781 float_as_integer_ratio_doc},
1782 {"fromhex", (PyCFunction)float_fromhex,
1783 METH_O|METH_CLASS, float_fromhex_doc},
1784 {"hex", (PyCFunction)float_hex,
1785 METH_NOARGS, float_hex_doc},
1786 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1787 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001788#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1790 "Returns True if the float is positive or negative infinite."},
1791 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1792 "Returns True if the float is finite, neither infinite nor NaN."},
1793 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1794 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001795#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1797 {"__getformat__", (PyCFunction)float_getformat,
1798 METH_O|METH_CLASS, float_getformat_doc},
1799 {"__setformat__", (PyCFunction)float_setformat,
1800 METH_VARARGS|METH_CLASS, float_setformat_doc},
1801 {"__format__", (PyCFunction)float__format__,
1802 METH_VARARGS, float__format__doc},
1803 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001804};
1805
Guido van Rossumb43daf72007-08-01 18:08:08 +00001806static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001808 (getter)float_float, (setter)NULL,
1809 "the real part of a complex number",
1810 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001812 (getter)float_getzero, (setter)NULL,
1813 "the imaginary part of a complex number",
1814 NULL},
1815 {NULL} /* Sentinel */
1816};
1817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001818PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819"float(x) -> floating point number\n\
1820\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001821Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822
1823
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 float_add, /*nb_add*/
1826 float_sub, /*nb_subtract*/
1827 float_mul, /*nb_multiply*/
1828 float_rem, /*nb_remainder*/
1829 float_divmod, /*nb_divmod*/
1830 float_pow, /*nb_power*/
1831 (unaryfunc)float_neg, /*nb_negative*/
1832 (unaryfunc)float_float, /*nb_positive*/
1833 (unaryfunc)float_abs, /*nb_absolute*/
1834 (inquiry)float_bool, /*nb_bool*/
1835 0, /*nb_invert*/
1836 0, /*nb_lshift*/
1837 0, /*nb_rshift*/
1838 0, /*nb_and*/
1839 0, /*nb_xor*/
1840 0, /*nb_or*/
1841 float_trunc, /*nb_int*/
1842 0, /*nb_reserved*/
1843 float_float, /*nb_float*/
1844 0, /* nb_inplace_add */
1845 0, /* nb_inplace_subtract */
1846 0, /* nb_inplace_multiply */
1847 0, /* nb_inplace_remainder */
1848 0, /* nb_inplace_power */
1849 0, /* nb_inplace_lshift */
1850 0, /* nb_inplace_rshift */
1851 0, /* nb_inplace_and */
1852 0, /* nb_inplace_xor */
1853 0, /* nb_inplace_or */
1854 float_floor_div, /* nb_floor_divide */
1855 float_div, /* nb_true_divide */
1856 0, /* nb_inplace_floor_divide */
1857 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858};
1859
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001860PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1862 "float",
1863 sizeof(PyFloatObject),
1864 0,
1865 (destructor)float_dealloc, /* tp_dealloc */
1866 0, /* tp_print */
1867 0, /* tp_getattr */
1868 0, /* tp_setattr */
1869 0, /* tp_reserved */
1870 (reprfunc)float_repr, /* tp_repr */
1871 &float_as_number, /* tp_as_number */
1872 0, /* tp_as_sequence */
1873 0, /* tp_as_mapping */
1874 (hashfunc)float_hash, /* tp_hash */
1875 0, /* tp_call */
1876 (reprfunc)float_str, /* tp_str */
1877 PyObject_GenericGetAttr, /* tp_getattro */
1878 0, /* tp_setattro */
1879 0, /* tp_as_buffer */
1880 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1881 float_doc, /* tp_doc */
1882 0, /* tp_traverse */
1883 0, /* tp_clear */
1884 float_richcompare, /* tp_richcompare */
1885 0, /* tp_weaklistoffset */
1886 0, /* tp_iter */
1887 0, /* tp_iternext */
1888 float_methods, /* tp_methods */
1889 0, /* tp_members */
1890 float_getset, /* tp_getset */
1891 0, /* tp_base */
1892 0, /* tp_dict */
1893 0, /* tp_descr_get */
1894 0, /* tp_descr_set */
1895 0, /* tp_dictoffset */
1896 0, /* tp_init */
1897 0, /* tp_alloc */
1898 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001899};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001900
1901void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001902_PyFloat_Init(void)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* We attempt to determine if this machine is using IEEE
1905 floating point formats by peering at the bits of some
1906 carefully chosen values. If it looks like we are on an
1907 IEEE platform, the float packing/unpacking routines can
1908 just copy bits, if not they resort to arithmetic & shifts
1909 and masks. The shifts & masks approach works on all finite
1910 values, but what happens to infinities, NaNs and signed
1911 zeroes on packing is an accident, and attempting to unpack
1912 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 Note that if we're on some whacked-out platform which uses
1915 IEEE formats but isn't strictly little-endian or big-
1916 endian, we will fall back to the portable shifts & masks
1917 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001918
1919#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 {
1921 double x = 9006104071832581.0;
1922 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1923 detected_double_format = ieee_big_endian_format;
1924 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1925 detected_double_format = ieee_little_endian_format;
1926 else
1927 detected_double_format = unknown_format;
1928 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001929#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931#endif
1932
1933#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 {
1935 float y = 16711938.0;
1936 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1937 detected_float_format = ieee_big_endian_format;
1938 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1939 detected_float_format = ieee_little_endian_format;
1940 else
1941 detected_float_format = unknown_format;
1942 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001945#endif
1946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 double_format = detected_double_format;
1948 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 /* Init float info */
1951 if (FloatInfoType.tp_name == 0)
1952 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001953}
1954
Georg Brandl2ee470f2008-07-16 12:55:28 +00001955int
1956PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyFloatObject *p;
1959 PyFloatBlock *list, *next;
1960 int i;
1961 int u; /* remaining unfreed floats per block */
1962 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 list = block_list;
1965 block_list = NULL;
1966 free_list = NULL;
1967 while (list != NULL) {
1968 u = 0;
1969 for (i = 0, p = &list->objects[0];
1970 i < N_FLOATOBJECTS;
1971 i++, p++) {
1972 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1973 u++;
1974 }
1975 next = list->next;
1976 if (u) {
1977 list->next = block_list;
1978 block_list = list;
1979 for (i = 0, p = &list->objects[0];
1980 i < N_FLOATOBJECTS;
1981 i++, p++) {
1982 if (!PyFloat_CheckExact(p) ||
1983 Py_REFCNT(p) == 0) {
1984 Py_TYPE(p) = (struct _typeobject *)
1985 free_list;
1986 free_list = p;
1987 }
1988 }
1989 }
1990 else {
1991 PyMem_FREE(list);
1992 }
1993 freelist_size += u;
1994 list = next;
1995 }
1996 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001997}
1998
1999void
2000PyFloat_Fini(void)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyFloatObject *p;
2003 PyFloatBlock *list;
2004 int i;
2005 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (!Py_VerboseFlag)
2010 return;
2011 fprintf(stderr, "# cleanup floats");
2012 if (!u) {
2013 fprintf(stderr, "\n");
2014 }
2015 else {
2016 fprintf(stderr,
2017 ": %d unfreed float%s\n",
2018 u, u == 1 ? "" : "s");
2019 }
2020 if (Py_VerboseFlag > 1) {
2021 list = block_list;
2022 while (list != NULL) {
2023 for (i = 0, p = &list->objects[0];
2024 i < N_FLOATOBJECTS;
2025 i++, p++) {
2026 if (PyFloat_CheckExact(p) &&
2027 Py_REFCNT(p) != 0) {
2028 char *buf = PyOS_double_to_string(
2029 PyFloat_AS_DOUBLE(p), 'r',
2030 0, 0, NULL);
2031 if (buf) {
2032 /* XXX(twouters) cast
2033 refcount to long
2034 until %zd is
2035 universally
2036 available
2037 */
2038 fprintf(stderr,
2039 "# <float at %p, refcnt=%ld, val=%s>\n",
2040 p, (long)Py_REFCNT(p), buf);
2041 PyMem_Free(buf);
2042 }
2043 }
2044 }
2045 list = list->next;
2046 }
2047 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002048}
Tim Peters9905b942003-03-20 20:53:32 +00002049
2050/*----------------------------------------------------------------------------
2051 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002052 */
2053int
2054_PyFloat_Pack4(double x, unsigned char *p, int le)
2055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (float_format == unknown_format) {
2057 unsigned char sign;
2058 int e;
2059 double f;
2060 unsigned int fbits;
2061 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (le) {
2064 p += 3;
2065 incr = -1;
2066 }
Tim Peters9905b942003-03-20 20:53:32 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (x < 0) {
2069 sign = 1;
2070 x = -x;
2071 }
2072 else
2073 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 /* Normalize f to be in the range [1.0, 2.0) */
2078 if (0.5 <= f && f < 1.0) {
2079 f *= 2.0;
2080 e--;
2081 }
2082 else if (f == 0.0)
2083 e = 0;
2084 else {
2085 PyErr_SetString(PyExc_SystemError,
2086 "frexp() result out of range");
2087 return -1;
2088 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (e >= 128)
2091 goto Overflow;
2092 else if (e < -126) {
2093 /* Gradual underflow */
2094 f = ldexp(f, 126 + e);
2095 e = 0;
2096 }
2097 else if (!(e == 0 && f == 0.0)) {
2098 e += 127;
2099 f -= 1.0; /* Get rid of leading 1 */
2100 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 f *= 8388608.0; /* 2**23 */
2103 fbits = (unsigned int)(f + 0.5); /* Round */
2104 assert(fbits <= 8388608);
2105 if (fbits >> 23) {
2106 /* The carry propagated out of a string of 23 1 bits. */
2107 fbits = 0;
2108 ++e;
2109 if (e >= 255)
2110 goto Overflow;
2111 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 /* First byte */
2114 *p = (sign << 7) | (e >> 1);
2115 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 /* Second byte */
2118 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2119 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* Third byte */
2122 *p = (fbits >> 8) & 0xFF;
2123 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* Fourth byte */
2126 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* Done */
2129 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 }
2132 else {
2133 float y = (float)x;
2134 const char *s = (char*)&y;
2135 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2138 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if ((float_format == ieee_little_endian_format && !le)
2141 || (float_format == ieee_big_endian_format && le)) {
2142 p += 3;
2143 incr = -1;
2144 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 for (i = 0; i < 4; i++) {
2147 *p = *s++;
2148 p += incr;
2149 }
2150 return 0;
2151 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002152 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyErr_SetString(PyExc_OverflowError,
2154 "float too large to pack with f format");
2155 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002156}
2157
2158int
2159_PyFloat_Pack8(double x, unsigned char *p, int le)
2160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (double_format == unknown_format) {
2162 unsigned char sign;
2163 int e;
2164 double f;
2165 unsigned int fhi, flo;
2166 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (le) {
2169 p += 7;
2170 incr = -1;
2171 }
Tim Peters9905b942003-03-20 20:53:32 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 if (x < 0) {
2174 sign = 1;
2175 x = -x;
2176 }
2177 else
2178 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* Normalize f to be in the range [1.0, 2.0) */
2183 if (0.5 <= f && f < 1.0) {
2184 f *= 2.0;
2185 e--;
2186 }
2187 else if (f == 0.0)
2188 e = 0;
2189 else {
2190 PyErr_SetString(PyExc_SystemError,
2191 "frexp() result out of range");
2192 return -1;
2193 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (e >= 1024)
2196 goto Overflow;
2197 else if (e < -1022) {
2198 /* Gradual underflow */
2199 f = ldexp(f, 1022 + e);
2200 e = 0;
2201 }
2202 else if (!(e == 0 && f == 0.0)) {
2203 e += 1023;
2204 f -= 1.0; /* Get rid of leading 1 */
2205 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2208 f *= 268435456.0; /* 2**28 */
2209 fhi = (unsigned int)f; /* Truncate */
2210 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 f -= (double)fhi;
2213 f *= 16777216.0; /* 2**24 */
2214 flo = (unsigned int)(f + 0.5); /* Round */
2215 assert(flo <= 16777216);
2216 if (flo >> 24) {
2217 /* The carry propagated out of a string of 24 1 bits. */
2218 flo = 0;
2219 ++fhi;
2220 if (fhi >> 28) {
2221 /* And it also progagated out of the next 28 bits. */
2222 fhi = 0;
2223 ++e;
2224 if (e >= 2047)
2225 goto Overflow;
2226 }
2227 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* First byte */
2230 *p = (sign << 7) | (e >> 4);
2231 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Second byte */
2234 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2235 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Third byte */
2238 *p = (fhi >> 16) & 0xFF;
2239 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Fourth byte */
2242 *p = (fhi >> 8) & 0xFF;
2243 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* Fifth byte */
2246 *p = fhi & 0xFF;
2247 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* Sixth byte */
2250 *p = (flo >> 16) & 0xFF;
2251 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 /* Seventh byte */
2254 *p = (flo >> 8) & 0xFF;
2255 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 /* Eighth byte */
2258 *p = flo & 0xFF;
2259 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* Done */
2262 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 Overflow:
2265 PyErr_SetString(PyExc_OverflowError,
2266 "float too large to pack with d format");
2267 return -1;
2268 }
2269 else {
2270 const char *s = (char*)&x;
2271 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if ((double_format == ieee_little_endian_format && !le)
2274 || (double_format == ieee_big_endian_format && le)) {
2275 p += 7;
2276 incr = -1;
2277 }
2278
2279 for (i = 0; i < 8; i++) {
2280 *p = *s++;
2281 p += incr;
2282 }
2283 return 0;
2284 }
Tim Peters9905b942003-03-20 20:53:32 +00002285}
2286
2287double
2288_PyFloat_Unpack4(const unsigned char *p, int le)
2289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 if (float_format == unknown_format) {
2291 unsigned char sign;
2292 int e;
2293 unsigned int f;
2294 double x;
2295 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (le) {
2298 p += 3;
2299 incr = -1;
2300 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* First byte */
2303 sign = (*p >> 7) & 1;
2304 e = (*p & 0x7F) << 1;
2305 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Second byte */
2308 e |= (*p >> 7) & 1;
2309 f = (*p & 0x7F) << 16;
2310 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 if (e == 255) {
2313 PyErr_SetString(
2314 PyExc_ValueError,
2315 "can't unpack IEEE 754 special value "
2316 "on non-IEEE platform");
2317 return -1;
2318 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Third byte */
2321 f |= *p << 8;
2322 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Fourth byte */
2325 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* XXX This sadly ignores Inf/NaN issues */
2330 if (e == 0)
2331 e = -126;
2332 else {
2333 x += 1.0;
2334 e -= 127;
2335 }
2336 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 if (sign)
2339 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return x;
2342 }
2343 else {
2344 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 if ((float_format == ieee_little_endian_format && !le)
2347 || (float_format == ieee_big_endian_format && le)) {
2348 char buf[4];
2349 char *d = &buf[3];
2350 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 for (i = 0; i < 4; i++) {
2353 *d-- = *p++;
2354 }
2355 memcpy(&x, buf, 4);
2356 }
2357 else {
2358 memcpy(&x, p, 4);
2359 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 return x;
2362 }
Tim Peters9905b942003-03-20 20:53:32 +00002363}
2364
2365double
2366_PyFloat_Unpack8(const unsigned char *p, int le)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (double_format == unknown_format) {
2369 unsigned char sign;
2370 int e;
2371 unsigned int fhi, flo;
2372 double x;
2373 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 if (le) {
2376 p += 7;
2377 incr = -1;
2378 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* First byte */
2381 sign = (*p >> 7) & 1;
2382 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* Second byte */
2387 e |= (*p >> 4) & 0xF;
2388 fhi = (*p & 0xF) << 24;
2389 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 if (e == 2047) {
2392 PyErr_SetString(
2393 PyExc_ValueError,
2394 "can't unpack IEEE 754 special value "
2395 "on non-IEEE platform");
2396 return -1.0;
2397 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Third byte */
2400 fhi |= *p << 16;
2401 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Fourth byte */
2404 fhi |= *p << 8;
2405 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 /* Fifth byte */
2408 fhi |= *p;
2409 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* Sixth byte */
2412 flo = *p << 16;
2413 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* Seventh byte */
2416 flo |= *p << 8;
2417 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 /* Eighth byte */
2420 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2423 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (e == 0)
2426 e = -1022;
2427 else {
2428 x += 1.0;
2429 e -= 1023;
2430 }
2431 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 if (sign)
2434 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 return x;
2437 }
2438 else {
2439 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if ((double_format == ieee_little_endian_format && !le)
2442 || (double_format == ieee_big_endian_format && le)) {
2443 char buf[8];
2444 char *d = &buf[7];
2445 int i;
2446
2447 for (i = 0; i < 8; i++) {
2448 *d-- = *p++;
2449 }
2450 memcpy(&x, buf, 8);
2451 }
2452 else {
2453 memcpy(&x, p, 8);
2454 }
2455
2456 return x;
2457 }
Tim Peters9905b942003-03-20 20:53:32 +00002458}