blob: 33926148c0aaf59440448839920a37662d8a9113 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Mark Dickinson65fe25e2008-07-16 11:30:51 +000012#undef MAX
13#undef MIN
14#define MAX(x, y) ((x) < (y) ? (y) : (x))
15#define MIN(x, y) ((x) < (y) ? (x) : (y))
16
Guido van Rossum6923e131990-11-02 17:50:43 +000017
Mark Dickinsond19052c2010-06-27 18:19:09 +000018/* Special free list
19
20 Since some Python programs can spend much of their time allocating
21 and deallocating floats, these operations should be very fast.
22 Therefore we use a dedicated allocation scheme with a much lower
23 overhead (in space and time) than straight malloc(): a simple
24 dedicated free list, filled when necessary with memory from malloc().
25
26 block_list is a singly-linked list of all PyFloatBlocks ever allocated,
27 linked via their next members. PyFloatBlocks are never returned to the
28 system before shutdown (PyFloat_Fini).
29
30 free_list is a singly-linked list of available PyFloatObjects, linked
31 via abuse of their ob_type members.
32*/
33
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
35#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
36#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000037
Guido van Rossum3fce8831999-03-12 19:43:17 +000038struct _floatblock {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 struct _floatblock *next;
40 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000041};
42
43typedef struct _floatblock PyFloatBlock;
44
45static PyFloatBlock *block_list = NULL;
46static PyFloatObject *free_list = NULL;
47
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000049fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 PyFloatObject *p, *q;
52 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
53 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
54 if (p == NULL)
55 return (PyFloatObject *) PyErr_NoMemory();
56 ((PyFloatBlock *)p)->next = block_list;
57 block_list = (PyFloatBlock *)p;
58 p = &((PyFloatBlock *)p)->objects[0];
59 q = p + N_FLOATOBJECTS;
60 while (--q > p)
61 Py_TYPE(q) = (struct _typeobject *)(q-1);
62 Py_TYPE(q) = NULL;
63 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000064}
65
Christian Heimes93852662007-12-01 12:22:32 +000066double
67PyFloat_GetMax(void)
68{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000070}
71
72double
73PyFloat_GetMin(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000076}
77
Christian Heimesd32ed6f2008-01-14 18:49:24 +000078static PyTypeObject FloatInfoType;
79
80PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000081"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000082\n\
83A structseq holding information about the float type. It contains low level\n\
84information about the precision and internal representation. Please study\n\
85your system's :file:`float.h` for more information.");
86
87static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 {"max", "DBL_MAX -- maximum representable finite float"},
89 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
90 "is representable"},
91 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
92 "is representable"},
93 {"min", "DBL_MIN -- Minimum positive normalizer float"},
94 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
95 "is a normalized float"},
96 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
97 "a normalized"},
98 {"dig", "DBL_DIG -- digits"},
99 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
100 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
101 "representable float"},
102 {"radix", "FLT_RADIX -- radix of exponent"},
103 {"rounds", "FLT_ROUNDS -- addition rounds"},
104 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000105};
106
107static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 "sys.float_info", /* name */
109 floatinfo__doc__, /* doc */
110 floatinfo_fields, /* fields */
111 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000112};
113
Christian Heimes93852662007-12-01 12:22:32 +0000114PyObject *
115PyFloat_GetInfo(void)
116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 PyObject* floatinfo;
118 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 floatinfo = PyStructSequence_New(&FloatInfoType);
121 if (floatinfo == NULL) {
122 return NULL;
123 }
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000127#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 SetDblFlag(DBL_MAX);
131 SetIntFlag(DBL_MAX_EXP);
132 SetIntFlag(DBL_MAX_10_EXP);
133 SetDblFlag(DBL_MIN);
134 SetIntFlag(DBL_MIN_EXP);
135 SetIntFlag(DBL_MIN_10_EXP);
136 SetIntFlag(DBL_DIG);
137 SetIntFlag(DBL_MANT_DIG);
138 SetDblFlag(DBL_EPSILON);
139 SetIntFlag(FLT_RADIX);
140 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000141#undef SetIntFlag
142#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143
144 if (PyErr_Occurred()) {
145 Py_CLEAR(floatinfo);
146 return NULL;
147 }
148 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000149}
150
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 register PyFloatObject *op;
155 if (free_list == NULL) {
156 if ((free_list = fill_free_list()) == NULL)
157 return NULL;
158 }
159 /* Inline PyObject_New */
160 op = free_list;
161 free_list = (PyFloatObject *)Py_TYPE(op);
162 PyObject_INIT(op, &PyFloat_Type);
163 op->ob_fval = fval;
164 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000168PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 const char *s, *last, *end;
171 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000172 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 Py_ssize_t len;
174 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (PyUnicode_Check(v)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000177 Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
178 Py_UNICODE *bufptr;
179 s_buffer = PyUnicode_TransformDecimalToASCII(
180 PyUnicode_AS_UNICODE(v), buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 return NULL;
183 /* Replace non-ASCII whitespace with ' ' */
184 bufptr = PyUnicode_AS_UNICODE(s_buffer);
185 for (i = 0; i < buflen; i++) {
186 Py_UNICODE ch = bufptr[i];
187 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
188 bufptr[i] = ' ';
189 }
190 s = _PyUnicode_AsStringAndSize(s_buffer, &len);
191 if (s == NULL) {
192 Py_DECREF(s_buffer);
193 return NULL;
194 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 }
196 else if (PyObject_AsCharBuffer(v, &s, &len)) {
197 PyErr_SetString(PyExc_TypeError,
198 "float() argument must be a string or a number");
199 return NULL;
200 }
201 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000202 /* strip space */
203 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000205 while (s < last - 1 && Py_ISSPACE(last[-1]))
206 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* We don't care about overflow or underflow. If the platform
208 * supports them, infinities and signed zeroes (on underflow) are
209 * fine. */
210 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000211 if (end != last) {
212 PyErr_Format(PyExc_ValueError,
213 "could not convert string to float: "
214 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 result = NULL;
216 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000217 else if (x == -1.0 && PyErr_Occurred())
218 result = NULL;
219 else
220 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000221
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000222 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000224}
225
Guido van Rossum234f9421993-06-17 12:35:49 +0000226static void
Fred Drakefd99de62000-07-09 05:02:18 +0000227float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (PyFloat_CheckExact(op)) {
230 Py_TYPE(op) = (struct _typeobject *)free_list;
231 free_list = op;
232 }
233 else
234 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000235}
236
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237double
Fred Drakefd99de62000-07-09 05:02:18 +0000238PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyNumberMethods *nb;
241 PyFloatObject *fo;
242 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (op && PyFloat_Check(op))
245 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (op == NULL) {
248 PyErr_BadArgument();
249 return -1;
250 }
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
253 PyErr_SetString(PyExc_TypeError, "a float is required");
254 return -1;
255 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 fo = (PyFloatObject*) (*nb->nb_float) (op);
258 if (fo == NULL)
259 return -1;
260 if (!PyFloat_Check(fo)) {
261 PyErr_SetString(PyExc_TypeError,
262 "nb_float should return float object");
263 return -1;
264 }
Tim Petersd2364e82001-11-01 20:09:42 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 val = PyFloat_AS_DOUBLE(fo);
267 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270}
271
Neil Schemenauer32117e52001-01-04 01:44:34 +0000272/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000273 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000274 set to NULL, and the function invoking this macro returns NULL. If
275 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
276 stored in obj, and returned from the function invoking this macro.
277*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278#define CONVERT_TO_DOUBLE(obj, dbl) \
279 if (PyFloat_Check(obj)) \
280 dbl = PyFloat_AS_DOUBLE(obj); \
281 else if (convert_to_double(&(obj), &(dbl)) < 0) \
282 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000283
Eric Smith0923d1d2009-04-16 20:16:10 +0000284/* Methods */
285
Neil Schemenauer32117e52001-01-04 01:44:34 +0000286static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000287convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (PyLong_Check(obj)) {
292 *dbl = PyLong_AsDouble(obj);
293 if (*dbl == -1.0 && PyErr_Occurred()) {
294 *v = NULL;
295 return -1;
296 }
297 }
298 else {
299 Py_INCREF(Py_NotImplemented);
300 *v = Py_NotImplemented;
301 return -1;
302 }
303 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000304}
305
Eric Smith0923d1d2009-04-16 20:16:10 +0000306static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000307float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000308{
309 PyObject *result;
310 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000311 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000312 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000313 NULL);
314 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000315 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000316 result = PyUnicode_FromString(buf);
317 PyMem_Free(buf);
318 return result;
319}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000320
Tim Peters307fa782004-09-23 08:06:40 +0000321/* Comparison is pretty much a nightmare. When comparing float to float,
322 * we do it as straightforwardly (and long-windedly) as conceivable, so
323 * that, e.g., Python x == y delivers the same result as the platform
324 * C x == y when x and/or y is a NaN.
325 * When mixing float with an integer type, there's no good *uniform* approach.
326 * Converting the double to an integer obviously doesn't work, since we
327 * may lose info from fractional bits. Converting the integer to a double
328 * also has two failure modes: (1) a long int may trigger overflow (too
329 * large to fit in the dynamic range of a C double); (2) even a C long may have
330 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
331 * 63 bits of precision, but a C double probably has only 53), and then
332 * we can falsely claim equality when low-order integer bits are lost by
333 * coercion to double. So this part is painful too.
334 */
335
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000336static PyObject*
337float_richcompare(PyObject *v, PyObject *w, int op)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 double i, j;
340 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 assert(PyFloat_Check(v));
343 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 /* Switch on the type of w. Set i and j to doubles to be compared,
346 * and op to the richcomp to use.
347 */
348 if (PyFloat_Check(w))
349 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 else if (!Py_IS_FINITE(i)) {
352 if (PyLong_Check(w))
353 /* If i is an infinity, its magnitude exceeds any
354 * finite integer, so it doesn't matter which int we
355 * compare i with. If i is a NaN, similarly.
356 */
357 j = 0.0;
358 else
359 goto Unimplemented;
360 }
Tim Peters307fa782004-09-23 08:06:40 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else if (PyLong_Check(w)) {
363 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
364 int wsign = _PyLong_Sign(w);
365 size_t nbits;
366 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (vsign != wsign) {
369 /* Magnitudes are irrelevant -- the signs alone
370 * determine the outcome.
371 */
372 i = (double)vsign;
373 j = (double)wsign;
374 goto Compare;
375 }
376 /* The signs are the same. */
377 /* Convert w to a double if it fits. In particular, 0 fits. */
378 nbits = _PyLong_NumBits(w);
379 if (nbits == (size_t)-1 && PyErr_Occurred()) {
380 /* This long is so large that size_t isn't big enough
381 * to hold the # of bits. Replace with little doubles
382 * that give the same outcome -- w is so large that
383 * its magnitude must exceed the magnitude of any
384 * finite float.
385 */
386 PyErr_Clear();
387 i = (double)vsign;
388 assert(wsign != 0);
389 j = wsign * 2.0;
390 goto Compare;
391 }
392 if (nbits <= 48) {
393 j = PyLong_AsDouble(w);
394 /* It's impossible that <= 48 bits overflowed. */
395 assert(j != -1.0 || ! PyErr_Occurred());
396 goto Compare;
397 }
398 assert(wsign != 0); /* else nbits was 0 */
399 assert(vsign != 0); /* if vsign were 0, then since wsign is
400 * not 0, we would have taken the
401 * vsign != wsign branch at the start */
402 /* We want to work with non-negative numbers. */
403 if (vsign < 0) {
404 /* "Multiply both sides" by -1; this also swaps the
405 * comparator.
406 */
407 i = -i;
408 op = _Py_SwappedOp[op];
409 }
410 assert(i > 0.0);
411 (void) frexp(i, &exponent);
412 /* exponent is the # of bits in v before the radix point;
413 * we know that nbits (the # of bits in w) > 48 at this point
414 */
415 if (exponent < 0 || (size_t)exponent < nbits) {
416 i = 1.0;
417 j = 2.0;
418 goto Compare;
419 }
420 if ((size_t)exponent > nbits) {
421 i = 2.0;
422 j = 1.0;
423 goto Compare;
424 }
425 /* v and w have the same number of bits before the radix
426 * point. Construct two longs that have the same comparison
427 * outcome.
428 */
429 {
430 double fracpart;
431 double intpart;
432 PyObject *result = NULL;
433 PyObject *one = NULL;
434 PyObject *vv = NULL;
435 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (wsign < 0) {
438 ww = PyNumber_Negative(w);
439 if (ww == NULL)
440 goto Error;
441 }
442 else
443 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 fracpart = modf(i, &intpart);
446 vv = PyLong_FromDouble(intpart);
447 if (vv == NULL)
448 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (fracpart != 0.0) {
451 /* Shift left, and or a 1 bit into vv
452 * to represent the lost fraction.
453 */
454 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 one = PyLong_FromLong(1);
457 if (one == NULL)
458 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 temp = PyNumber_Lshift(ww, one);
461 if (temp == NULL)
462 goto Error;
463 Py_DECREF(ww);
464 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 temp = PyNumber_Lshift(vv, one);
467 if (temp == NULL)
468 goto Error;
469 Py_DECREF(vv);
470 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 temp = PyNumber_Or(vv, one);
473 if (temp == NULL)
474 goto Error;
475 Py_DECREF(vv);
476 vv = temp;
477 }
Tim Peters307fa782004-09-23 08:06:40 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 r = PyObject_RichCompareBool(vv, ww, op);
480 if (r < 0)
481 goto Error;
482 result = PyBool_FromLong(r);
483 Error:
484 Py_XDECREF(vv);
485 Py_XDECREF(ww);
486 Py_XDECREF(one);
487 return result;
488 }
489 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 else /* w isn't float, int, or long */
492 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000493
494 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 PyFPE_START_PROTECT("richcompare", return NULL)
496 switch (op) {
497 case Py_EQ:
498 r = i == j;
499 break;
500 case Py_NE:
501 r = i != j;
502 break;
503 case Py_LE:
504 r = i <= j;
505 break;
506 case Py_GE:
507 r = i >= j;
508 break;
509 case Py_LT:
510 r = i < j;
511 break;
512 case Py_GT:
513 r = i > j;
514 break;
515 }
516 PyFPE_END_PROTECT(r)
517 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000518
519 Unimplemented:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_INCREF(Py_NotImplemented);
521 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522}
523
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000524static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000525float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000528}
529
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000531float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 double a,b;
534 CONVERT_TO_DOUBLE(v, a);
535 CONVERT_TO_DOUBLE(w, b);
536 PyFPE_START_PROTECT("add", return 0)
537 a = a + b;
538 PyFPE_END_PROTECT(a)
539 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 double a,b;
546 CONVERT_TO_DOUBLE(v, a);
547 CONVERT_TO_DOUBLE(w, b);
548 PyFPE_START_PROTECT("subtract", return 0)
549 a = a - b;
550 PyFPE_END_PROTECT(a)
551 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552}
553
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000555float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 double a,b;
558 CONVERT_TO_DOUBLE(v, a);
559 CONVERT_TO_DOUBLE(w, b);
560 PyFPE_START_PROTECT("multiply", return 0)
561 a = a * b;
562 PyFPE_END_PROTECT(a)
563 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564}
565
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000567float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 double a,b;
570 CONVERT_TO_DOUBLE(v, a);
571 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 if (b == 0.0) {
573 PyErr_SetString(PyExc_ZeroDivisionError,
574 "float division by zero");
575 return NULL;
576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 PyFPE_START_PROTECT("divide", return 0)
578 a = a / b;
579 PyFPE_END_PROTECT(a)
580 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 double vx, wx;
587 double mod;
588 CONVERT_TO_DOUBLE(v, vx);
589 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (wx == 0.0) {
591 PyErr_SetString(PyExc_ZeroDivisionError,
592 "float modulo");
593 return NULL;
594 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyFPE_START_PROTECT("modulo", return 0)
596 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000597 if (mod) {
598 /* ensure the remainder has the same sign as the denominator */
599 if ((wx < 0) != (mod < 0)) {
600 mod += wx;
601 }
602 }
603 else {
604 /* the remainder is zero, and in the presence of signed zeroes
605 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000606 it has the same sign as the denominator. */
607 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 }
609 PyFPE_END_PROTECT(mod)
610 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611}
612
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000614float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 double vx, wx;
617 double div, mod, floordiv;
618 CONVERT_TO_DOUBLE(v, vx);
619 CONVERT_TO_DOUBLE(w, wx);
620 if (wx == 0.0) {
621 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
622 return NULL;
623 }
624 PyFPE_START_PROTECT("divmod", return 0)
625 mod = fmod(vx, wx);
626 /* fmod is typically exact, so vx-mod is *mathematically* an
627 exact multiple of wx. But this is fp arithmetic, and fp
628 vx - mod is an approximation; the result is that div may
629 not be an exact integral value after the division, although
630 it will always be very close to one.
631 */
632 div = (vx - mod) / wx;
633 if (mod) {
634 /* ensure the remainder has the same sign as the denominator */
635 if ((wx < 0) != (mod < 0)) {
636 mod += wx;
637 div -= 1.0;
638 }
639 }
640 else {
641 /* the remainder is zero, and in the presence of signed zeroes
642 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000643 it has the same sign as the denominator. */
644 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
646 /* snap quotient to nearest integral value */
647 if (div) {
648 floordiv = floor(div);
649 if (div - floordiv > 0.5)
650 floordiv += 1.0;
651 }
652 else {
653 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000654 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
656 PyFPE_END_PROTECT(floordiv)
657 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000658}
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000661float_floor_div(PyObject *v, PyObject *w)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 t = float_divmod(v, w);
666 if (t == NULL || t == Py_NotImplemented)
667 return t;
668 assert(PyTuple_CheckExact(t));
669 r = PyTuple_GET_ITEM(t, 0);
670 Py_INCREF(r);
671 Py_DECREF(t);
672 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000673}
674
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000675/* determine whether x is an odd integer or not; assumes that
676 x is not an infinity or nan. */
677#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
678
Tim Peters63a35712001-12-11 19:57:24 +0000679static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000680float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 double iv, iw, ix;
683 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if ((PyObject *)z != Py_None) {
686 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
687 "allowed unless all arguments are integers");
688 return NULL;
689 }
Tim Peters32f453e2001-09-03 08:35:41 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 CONVERT_TO_DOUBLE(v, iv);
692 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 /* Sort out special cases here instead of relying on pow() */
695 if (iw == 0) { /* v**0 is 1, even 0**0 */
696 return PyFloat_FromDouble(1.0);
697 }
698 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
699 return PyFloat_FromDouble(iv);
700 }
701 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
702 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
703 }
704 if (Py_IS_INFINITY(iw)) {
705 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
706 * abs(v) > 1 (including case where v infinite)
707 *
708 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
709 * abs(v) > 1 (including case where v infinite)
710 */
711 iv = fabs(iv);
712 if (iv == 1.0)
713 return PyFloat_FromDouble(1.0);
714 else if ((iw > 0.0) == (iv > 1.0))
715 return PyFloat_FromDouble(fabs(iw)); /* return inf */
716 else
717 return PyFloat_FromDouble(0.0);
718 }
719 if (Py_IS_INFINITY(iv)) {
720 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
721 * both cases, we need to add the appropriate sign if w is
722 * an odd integer.
723 */
724 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
725 if (iw > 0.0)
726 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
727 else
728 return PyFloat_FromDouble(iw_is_odd ?
729 copysign(0.0, iv) : 0.0);
730 }
731 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
732 (already dealt with above), and an error
733 if w is negative. */
734 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
735 if (iw < 0.0) {
736 PyErr_SetString(PyExc_ZeroDivisionError,
737 "0.0 cannot be raised to a "
738 "negative power");
739 return NULL;
740 }
741 /* use correct sign if iw is odd */
742 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
743 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (iv < 0.0) {
746 /* Whether this is an error is a mess, and bumps into libm
747 * bugs so we have to figure it out ourselves.
748 */
749 if (iw != floor(iw)) {
750 /* Negative numbers raised to fractional powers
751 * become complex.
752 */
753 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
754 }
755 /* iw is an exact integer, albeit perhaps a very large
756 * one. Replace iv by its absolute value and remember
757 * to negate the pow result if iw is odd.
758 */
759 iv = -iv;
760 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
761 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
764 /* (-1) ** large_integer also ends up here. Here's an
765 * extract from the comments for the previous
766 * implementation explaining why this special case is
767 * necessary:
768 *
769 * -1 raised to an exact integer should never be exceptional.
770 * Alas, some libms (chiefly glibc as of early 2003) return
771 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
772 * happen to be representable in a *C* integer. That's a
773 * bug.
774 */
775 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
776 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 /* Now iv and iw are finite, iw is nonzero, and iv is
779 * positive and not equal to 1.0. We finally allow
780 * the platform pow to step in and do the rest.
781 */
782 errno = 0;
783 PyFPE_START_PROTECT("pow", return NULL)
784 ix = pow(iv, iw);
785 PyFPE_END_PROTECT(ix)
786 Py_ADJUST_ERANGE1(ix);
787 if (negate_result)
788 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (errno != 0) {
791 /* We don't expect any errno value other than ERANGE, but
792 * the range of libm bugs appears unbounded.
793 */
794 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
795 PyExc_ValueError);
796 return NULL;
797 }
798 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799}
800
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000801#undef DOUBLE_IS_ODD_INTEGER
802
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000804float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807}
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000815static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000816float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000819}
820
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000821static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000822float_is_integer(PyObject *v)
823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 double x = PyFloat_AsDouble(v);
825 PyObject *o;
826
827 if (x == -1.0 && PyErr_Occurred())
828 return NULL;
829 if (!Py_IS_FINITE(x))
830 Py_RETURN_FALSE;
831 errno = 0;
832 PyFPE_START_PROTECT("is_integer", return NULL)
833 o = (floor(x) == x) ? Py_True : Py_False;
834 PyFPE_END_PROTECT(x)
835 if (errno != 0) {
836 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
837 PyExc_ValueError);
838 return NULL;
839 }
840 Py_INCREF(o);
841 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000842}
843
844#if 0
845static PyObject *
846float_is_inf(PyObject *v)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 double x = PyFloat_AsDouble(v);
849 if (x == -1.0 && PyErr_Occurred())
850 return NULL;
851 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000852}
853
854static PyObject *
855float_is_nan(PyObject *v)
856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 double x = PyFloat_AsDouble(v);
858 if (x == -1.0 && PyErr_Occurred())
859 return NULL;
860 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000861}
862
863static PyObject *
864float_is_finite(PyObject *v)
865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 double x = PyFloat_AsDouble(v);
867 if (x == -1.0 && PyErr_Occurred())
868 return NULL;
869 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000870}
871#endif
872
873static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000874float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 double x = PyFloat_AsDouble(v);
877 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 (void)modf(x, &wholepart);
880 /* Try to get out cheap if this fits in a Python int. The attempt
881 * to cast to long must be protected, as C doesn't define what
882 * happens if the double is too big to fit in a long. Some rare
883 * systems raise an exception then (RISCOS was mentioned as one,
884 * and someone using a non-default option on Sun also bumped into
885 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
886 * still be vulnerable: if a long has more bits of precision than
887 * a double, casting MIN/MAX to double may yield an approximation,
888 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
889 * yield true from the C expression wholepart<=LONG_MAX, despite
890 * that wholepart is actually greater than LONG_MAX.
891 */
892 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
893 const long aslong = (long)wholepart;
894 return PyLong_FromLong(aslong);
895 }
896 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000897}
898
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000899/* double_round: rounds a finite double to the closest multiple of
900 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
901 ndigits <= 323). Returns a Python float, or sets a Python error and
902 returns NULL on failure (OverflowError and memory errors are possible). */
903
904#ifndef PY_NO_SHORT_FLOAT_REPR
905/* version of double_round that uses the correctly-rounded string<->double
906 conversions from Python/dtoa.c */
907
908static PyObject *
909double_round(double x, int ndigits) {
910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 double rounded;
912 Py_ssize_t buflen, mybuflen=100;
913 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
914 int decpt, sign;
915 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* round to a decimal string */
918 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
919 if (buf == NULL) {
920 PyErr_NoMemory();
921 return NULL;
922 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
925 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
926 buflen = buf_end - buf;
927 if (buflen + 8 > mybuflen) {
928 mybuflen = buflen+8;
929 mybuf = (char *)PyMem_Malloc(mybuflen);
930 if (mybuf == NULL) {
931 PyErr_NoMemory();
932 goto exit;
933 }
934 }
935 /* copy buf to mybuf, adding exponent, sign and leading 0 */
936 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
937 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* and convert the resulting string back to a double */
940 errno = 0;
941 rounded = _Py_dg_strtod(mybuf, NULL);
942 if (errno == ERANGE && fabs(rounded) >= 1.)
943 PyErr_SetString(PyExc_OverflowError,
944 "rounded value too large to represent");
945 else
946 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* done computing value; now clean up */
949 if (mybuf != shortbuf)
950 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000951 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 _Py_dg_freedtoa(buf);
953 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000954}
955
956#else /* PY_NO_SHORT_FLOAT_REPR */
957
958/* fallback version, to be used when correctly rounded binary<->decimal
959 conversions aren't available */
960
961static PyObject *
962double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 double pow1, pow2, y, z;
964 if (ndigits >= 0) {
965 if (ndigits > 22) {
966 /* pow1 and pow2 are each safe from overflow, but
967 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
968 pow1 = pow(10.0, (double)(ndigits-22));
969 pow2 = 1e22;
970 }
971 else {
972 pow1 = pow(10.0, (double)ndigits);
973 pow2 = 1.0;
974 }
975 y = (x*pow1)*pow2;
976 /* if y overflows, then rounded value is exactly x */
977 if (!Py_IS_FINITE(y))
978 return PyFloat_FromDouble(x);
979 }
980 else {
981 pow1 = pow(10.0, (double)-ndigits);
982 pow2 = 1.0; /* unused; silences a gcc compiler warning */
983 y = x / pow1;
984 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 z = round(y);
987 if (fabs(y-z) == 0.5)
988 /* halfway between two integers; use round-half-even */
989 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (ndigits >= 0)
992 z = (z / pow2) / pow1;
993 else
994 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 /* if computation resulted in overflow, raise OverflowError */
997 if (!Py_IS_FINITE(z)) {
998 PyErr_SetString(PyExc_OverflowError,
999 "overflow occurred during round");
1000 return NULL;
1001 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001004}
1005
1006#endif /* PY_NO_SHORT_FLOAT_REPR */
1007
1008/* round a Python float v to the closest multiple of 10**-ndigits */
1009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001010static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001011float_round(PyObject *v, PyObject *args)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 double x, rounded;
1014 PyObject *o_ndigits = NULL;
1015 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 x = PyFloat_AsDouble(v);
1018 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1019 return NULL;
1020 if (o_ndigits == NULL) {
1021 /* single-argument round: round to nearest integer */
1022 rounded = round(x);
1023 if (fabs(x-rounded) == 0.5)
1024 /* halfway case: round to even */
1025 rounded = 2.0*round(x/2.0);
1026 return PyLong_FromDouble(rounded);
1027 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 /* interpret second argument as a Py_ssize_t; clips on overflow */
1030 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1031 if (ndigits == -1 && PyErr_Occurred())
1032 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 /* nans and infinities round to themselves */
1035 if (!Py_IS_FINITE(x))
1036 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1039 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1040 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001041#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1042#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (ndigits > NDIGITS_MAX)
1044 /* return x */
1045 return PyFloat_FromDouble(x);
1046 else if (ndigits < NDIGITS_MIN)
1047 /* return 0.0, but with sign of x */
1048 return PyFloat_FromDouble(0.0*x);
1049 else
1050 /* finite x, and ndigits is not unreasonably large */
1051 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001052#undef NDIGITS_MAX
1053#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001054}
1055
1056static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001057float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (PyFloat_CheckExact(v))
1060 Py_INCREF(v);
1061 else
1062 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1063 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001064}
1065
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001066/* turn ASCII hex characters into integer values and vice versa */
1067
1068static char
1069char_from_hex(int x)
1070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 assert(0 <= x && x < 16);
1072 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001073}
1074
1075static int
1076hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 int x;
1078 switch(c) {
1079 case '0':
1080 x = 0;
1081 break;
1082 case '1':
1083 x = 1;
1084 break;
1085 case '2':
1086 x = 2;
1087 break;
1088 case '3':
1089 x = 3;
1090 break;
1091 case '4':
1092 x = 4;
1093 break;
1094 case '5':
1095 x = 5;
1096 break;
1097 case '6':
1098 x = 6;
1099 break;
1100 case '7':
1101 x = 7;
1102 break;
1103 case '8':
1104 x = 8;
1105 break;
1106 case '9':
1107 x = 9;
1108 break;
1109 case 'a':
1110 case 'A':
1111 x = 10;
1112 break;
1113 case 'b':
1114 case 'B':
1115 x = 11;
1116 break;
1117 case 'c':
1118 case 'C':
1119 x = 12;
1120 break;
1121 case 'd':
1122 case 'D':
1123 x = 13;
1124 break;
1125 case 'e':
1126 case 'E':
1127 x = 14;
1128 break;
1129 case 'f':
1130 case 'F':
1131 x = 15;
1132 break;
1133 default:
1134 x = -1;
1135 break;
1136 }
1137 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001138}
1139
1140/* convert a float to a hexadecimal string */
1141
1142/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1143 of the form 4k+1. */
1144#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1145
1146static PyObject *
1147float_hex(PyObject *v)
1148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 double x, m;
1150 int e, shift, i, si, esign;
1151 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1152 trailing NUL byte. */
1153 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001158 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001161 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 return PyUnicode_FromString("-0x0.0p+0");
1163 else
1164 return PyUnicode_FromString("0x0.0p+0");
1165 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 m = frexp(fabs(x), &e);
1168 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1169 m = ldexp(m, shift);
1170 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 si = 0;
1173 s[si] = char_from_hex((int)m);
1174 si++;
1175 m -= (int)m;
1176 s[si] = '.';
1177 si++;
1178 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1179 m *= 16.0;
1180 s[si] = char_from_hex((int)m);
1181 si++;
1182 m -= (int)m;
1183 }
1184 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (e < 0) {
1187 esign = (int)'-';
1188 e = -e;
1189 }
1190 else
1191 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (x < 0.0)
1194 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1195 else
1196 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001197}
1198
1199PyDoc_STRVAR(float_hex_doc,
1200"float.hex() -> string\n\
1201\n\
1202Return a hexadecimal representation of a floating-point number.\n\
1203>>> (-0.1).hex()\n\
1204'-0x1.999999999999ap-4'\n\
1205>>> 3.14159.hex()\n\
1206'0x1.921f9f01b866ep+1'");
1207
1208/* Convert a hexadecimal string to a float. */
1209
1210static PyObject *
1211float_fromhex(PyObject *cls, PyObject *arg)
1212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 PyObject *result_as_float, *result;
1214 double x;
1215 long exp, top_exp, lsb, key_digit;
1216 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1217 int half_eps, digit, round_up, negate=0;
1218 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /*
1221 * For the sake of simplicity and correctness, we impose an artificial
1222 * limit on ndigits, the total number of hex digits in the coefficient
1223 * The limit is chosen to ensure that, writing exp for the exponent,
1224 *
1225 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1226 * guaranteed to overflow (provided it's nonzero)
1227 *
1228 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1229 * guaranteed to underflow to 0.
1230 *
1231 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1232 * overflow in the calculation of exp and top_exp below.
1233 *
1234 * More specifically, ndigits is assumed to satisfy the following
1235 * inequalities:
1236 *
1237 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1238 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1239 *
1240 * If either of these inequalities is not satisfied, a ValueError is
1241 * raised. Otherwise, write x for the value of the hex string, and
1242 * assume x is nonzero. Then
1243 *
1244 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1245 *
1246 * Now if exp > LONG_MAX/2 then:
1247 *
1248 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1249 * = DBL_MAX_EXP
1250 *
1251 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1252 * double, so overflows. If exp < LONG_MIN/2, then
1253 *
1254 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1255 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1256 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1257 *
1258 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1259 * when converted to a C double.
1260 *
1261 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1262 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1263 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 s = _PyUnicode_AsStringAndSize(arg, &length);
1266 if (s == NULL)
1267 return NULL;
1268 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /********************
1271 * Parse the string *
1272 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 /* leading whitespace */
1275 while (Py_ISSPACE(*s))
1276 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* infinities and nans */
1279 x = _Py_parse_inf_or_nan(s, &coeff_end);
1280 if (coeff_end != s) {
1281 s = coeff_end;
1282 goto finished;
1283 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 /* optional sign */
1286 if (*s == '-') {
1287 s++;
1288 negate = 1;
1289 }
1290 else if (*s == '+')
1291 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 /* [0x] */
1294 s_store = s;
1295 if (*s == '0') {
1296 s++;
1297 if (*s == 'x' || *s == 'X')
1298 s++;
1299 else
1300 s = s_store;
1301 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 /* coefficient: <integer> [. <fraction>] */
1304 coeff_start = s;
1305 while (hex_from_char(*s) >= 0)
1306 s++;
1307 s_store = s;
1308 if (*s == '.') {
1309 s++;
1310 while (hex_from_char(*s) >= 0)
1311 s++;
1312 coeff_end = s-1;
1313 }
1314 else
1315 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /* ndigits = total # of hex digits; fdigits = # after point */
1318 ndigits = coeff_end - coeff_start;
1319 fdigits = coeff_end - s_store;
1320 if (ndigits == 0)
1321 goto parse_error;
1322 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1323 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1324 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* [p <exponent>] */
1327 if (*s == 'p' || *s == 'P') {
1328 s++;
1329 exp_start = s;
1330 if (*s == '-' || *s == '+')
1331 s++;
1332 if (!('0' <= *s && *s <= '9'))
1333 goto parse_error;
1334 s++;
1335 while ('0' <= *s && *s <= '9')
1336 s++;
1337 exp = strtol(exp_start, NULL, 10);
1338 }
1339 else
1340 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001342/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1344 coeff_end-(j) : \
1345 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /*******************************************
1348 * Compute rounded value of the hex string *
1349 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 /* Discard leading zeros, and catch extreme overflow and underflow */
1352 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1353 ndigits--;
1354 if (ndigits == 0 || exp < LONG_MIN/2) {
1355 x = 0.0;
1356 goto finished;
1357 }
1358 if (exp > LONG_MAX/2)
1359 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /* Adjust exponent for fractional part. */
1362 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1365 top_exp = exp + 4*((long)ndigits - 1);
1366 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1367 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* catch almost all nonextreme cases of overflow and underflow here */
1370 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1371 x = 0.0;
1372 goto finished;
1373 }
1374 if (top_exp > DBL_MAX_EXP)
1375 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 /* lsb = exponent of least significant bit of the *rounded* value.
1378 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1379 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 x = 0.0;
1382 if (exp >= lsb) {
1383 /* no rounding required */
1384 for (i = ndigits-1; i >= 0; i--)
1385 x = 16.0*x + HEX_DIGIT(i);
1386 x = ldexp(x, (int)(exp));
1387 goto finished;
1388 }
1389 /* rounding required. key_digit is the index of the hex digit
1390 containing the first bit to be rounded away. */
1391 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1392 key_digit = (lsb - exp - 1) / 4;
1393 for (i = ndigits-1; i > key_digit; i--)
1394 x = 16.0*x + HEX_DIGIT(i);
1395 digit = HEX_DIGIT(key_digit);
1396 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1399 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1400 if ((digit & half_eps) != 0) {
1401 round_up = 0;
1402 if ((digit & (3*half_eps-1)) != 0 ||
1403 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1404 round_up = 1;
1405 else
1406 for (i = key_digit-1; i >= 0; i--)
1407 if (HEX_DIGIT(i) != 0) {
1408 round_up = 1;
1409 break;
1410 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001411 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 x += 2*half_eps;
1413 if (top_exp == DBL_MAX_EXP &&
1414 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1415 /* overflow corner case: pre-rounded value <
1416 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1417 goto overflow_error;
1418 }
1419 }
1420 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001421
1422 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 /* optional trailing whitespace leading to the end of the string */
1424 while (Py_ISSPACE(*s))
1425 s++;
1426 if (s != s_end)
1427 goto parse_error;
1428 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1429 if (result_as_float == NULL)
1430 return NULL;
1431 result = PyObject_CallObject(cls, result_as_float);
1432 Py_DECREF(result_as_float);
1433 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434
1435 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyErr_SetString(PyExc_OverflowError,
1437 "hexadecimal value too large to represent as a float");
1438 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001439
1440 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyErr_SetString(PyExc_ValueError,
1442 "invalid hexadecimal floating-point string");
1443 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
1445 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyErr_SetString(PyExc_ValueError,
1447 "hexadecimal string too long to convert");
1448 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001449}
1450
1451PyDoc_STRVAR(float_fromhex_doc,
1452"float.fromhex(string) -> float\n\
1453\n\
1454Create a floating-point number from a hexadecimal string.\n\
1455>>> float.fromhex('0x1.ffffp10')\n\
14562047.984375\n\
1457>>> float.fromhex('-0x1p-1074')\n\
1458-4.9406564584124654e-324");
1459
1460
Christian Heimes26855632008-01-27 23:50:43 +00001461static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001462float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 double self;
1465 double float_part;
1466 int exponent;
1467 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 PyObject *prev;
1470 PyObject *py_exponent = NULL;
1471 PyObject *numerator = NULL;
1472 PyObject *denominator = NULL;
1473 PyObject *result_pair = NULL;
1474 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001475
1476#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 prev = obj; \
1478 obj = call; \
1479 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (Py_IS_INFINITY(self)) {
1484 PyErr_SetString(PyExc_OverflowError,
1485 "Cannot pass infinity to float.as_integer_ratio.");
1486 return NULL;
1487 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (Py_IS_NAN(self)) {
1489 PyErr_SetString(PyExc_ValueError,
1490 "Cannot pass NaN to float.as_integer_ratio.");
1491 return NULL;
1492 }
Christian Heimes26855632008-01-27 23:50:43 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1495 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1496 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1499 float_part *= 2.0;
1500 exponent--;
1501 }
1502 /* self == float_part * 2**exponent exactly and float_part is integral.
1503 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1504 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 numerator = PyLong_FromDouble(float_part);
1507 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 /* fold in 2**exponent */
1510 denominator = PyLong_FromLong(1);
1511 py_exponent = PyLong_FromLong(labs((long)exponent));
1512 if (py_exponent == NULL) goto error;
1513 INPLACE_UPDATE(py_exponent,
1514 long_methods->nb_lshift(denominator, py_exponent));
1515 if (py_exponent == NULL) goto error;
1516 if (exponent > 0) {
1517 INPLACE_UPDATE(numerator,
1518 long_methods->nb_multiply(numerator, py_exponent));
1519 if (numerator == NULL) goto error;
1520 }
1521 else {
1522 Py_DECREF(denominator);
1523 denominator = py_exponent;
1524 py_exponent = NULL;
1525 }
1526
1527 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001528
1529#undef INPLACE_UPDATE
1530error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 Py_XDECREF(py_exponent);
1532 Py_XDECREF(denominator);
1533 Py_XDECREF(numerator);
1534 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001535}
1536
1537PyDoc_STRVAR(float_as_integer_ratio_doc,
1538"float.as_integer_ratio() -> (int, int)\n"
1539"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001540"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1541"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001542"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001543"\n"
1544">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001545"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001546">>> (0.0).as_integer_ratio()\n"
1547"(0, 1)\n"
1548">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001549"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001550
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001551
Jeremy Hylton938ace62002-07-17 16:30:39 +00001552static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001553float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1554
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555static PyObject *
1556float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyObject *x = Py_False; /* Integer zero */
1559 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (type != &PyFloat_Type)
1562 return float_subtype_new(type, args, kwds); /* Wimp out */
1563 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1564 return NULL;
1565 /* If it's a string, but not a string subclass, use
1566 PyFloat_FromString. */
1567 if (PyUnicode_CheckExact(x))
1568 return PyFloat_FromString(x);
1569 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001570}
1571
Guido van Rossumbef14172001-08-29 15:47:46 +00001572/* Wimpy, slow approach to tp_new calls for subtypes of float:
1573 first create a regular float from whatever arguments we got,
1574 then allocate a subtype instance and initialize its ob_fval
1575 from the regular float. The regular float is then thrown away.
1576*/
1577static PyObject *
1578float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 assert(PyType_IsSubtype(type, &PyFloat_Type));
1583 tmp = float_new(&PyFloat_Type, args, kwds);
1584 if (tmp == NULL)
1585 return NULL;
1586 assert(PyFloat_CheckExact(tmp));
1587 newobj = type->tp_alloc(type, 0);
1588 if (newobj == NULL) {
1589 Py_DECREF(tmp);
1590 return NULL;
1591 }
1592 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1593 Py_DECREF(tmp);
1594 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001595}
1596
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001597static PyObject *
1598float_getnewargs(PyFloatObject *v)
1599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001601}
1602
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001603/* this is for the benefit of the pack/unpack routines below */
1604
1605typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001607} float_format_type;
1608
1609static float_format_type double_format, float_format;
1610static float_format_type detected_double_format, detected_float_format;
1611
1612static PyObject *
1613float_getformat(PyTypeObject *v, PyObject* arg)
1614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 char* s;
1616 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (!PyUnicode_Check(arg)) {
1619 PyErr_Format(PyExc_TypeError,
1620 "__getformat__() argument must be string, not %.500s",
1621 Py_TYPE(arg)->tp_name);
1622 return NULL;
1623 }
1624 s = _PyUnicode_AsString(arg);
1625 if (s == NULL)
1626 return NULL;
1627 if (strcmp(s, "double") == 0) {
1628 r = double_format;
1629 }
1630 else if (strcmp(s, "float") == 0) {
1631 r = float_format;
1632 }
1633 else {
1634 PyErr_SetString(PyExc_ValueError,
1635 "__getformat__() argument 1 must be "
1636 "'double' or 'float'");
1637 return NULL;
1638 }
1639
1640 switch (r) {
1641 case unknown_format:
1642 return PyUnicode_FromString("unknown");
1643 case ieee_little_endian_format:
1644 return PyUnicode_FromString("IEEE, little-endian");
1645 case ieee_big_endian_format:
1646 return PyUnicode_FromString("IEEE, big-endian");
1647 default:
1648 Py_FatalError("insane float_format or double_format");
1649 return NULL;
1650 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651}
1652
1653PyDoc_STRVAR(float_getformat_doc,
1654"float.__getformat__(typestr) -> string\n"
1655"\n"
1656"You probably don't want to use this function. It exists mainly to be\n"
1657"used in Python's test suite.\n"
1658"\n"
1659"typestr must be 'double' or 'float'. This function returns whichever of\n"
1660"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1661"format of floating point numbers used by the C type named by typestr.");
1662
1663static PyObject *
1664float_setformat(PyTypeObject *v, PyObject* args)
1665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 char* typestr;
1667 char* format;
1668 float_format_type f;
1669 float_format_type detected;
1670 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1673 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (strcmp(typestr, "double") == 0) {
1676 p = &double_format;
1677 detected = detected_double_format;
1678 }
1679 else if (strcmp(typestr, "float") == 0) {
1680 p = &float_format;
1681 detected = detected_float_format;
1682 }
1683 else {
1684 PyErr_SetString(PyExc_ValueError,
1685 "__setformat__() argument 1 must "
1686 "be 'double' or 'float'");
1687 return NULL;
1688 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (strcmp(format, "unknown") == 0) {
1691 f = unknown_format;
1692 }
1693 else if (strcmp(format, "IEEE, little-endian") == 0) {
1694 f = ieee_little_endian_format;
1695 }
1696 else if (strcmp(format, "IEEE, big-endian") == 0) {
1697 f = ieee_big_endian_format;
1698 }
1699 else {
1700 PyErr_SetString(PyExc_ValueError,
1701 "__setformat__() argument 2 must be "
1702 "'unknown', 'IEEE, little-endian' or "
1703 "'IEEE, big-endian'");
1704 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (f != unknown_format && f != detected) {
1709 PyErr_Format(PyExc_ValueError,
1710 "can only set %s format to 'unknown' or the "
1711 "detected platform value", typestr);
1712 return NULL;
1713 }
1714
1715 *p = f;
1716 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001717}
1718
1719PyDoc_STRVAR(float_setformat_doc,
1720"float.__setformat__(typestr, fmt) -> None\n"
1721"\n"
1722"You probably don't want to use this function. It exists mainly to be\n"
1723"used in Python's test suite.\n"
1724"\n"
1725"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1726"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1727"one of the latter two if it appears to match the underlying C reality.\n"
1728"\n"
1729"Overrides the automatic determination of C-level floating point type.\n"
1730"This affects how floats are converted to and from binary strings.");
1731
Guido van Rossumb43daf72007-08-01 18:08:08 +00001732static PyObject *
1733float_getzero(PyObject *v, void *closure)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001736}
1737
Eric Smith8c663262007-08-25 02:26:07 +00001738static PyObject *
1739float__format__(PyObject *self, PyObject *args)
1740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1744 return NULL;
1745 return _PyFloat_FormatAdvanced(self,
1746 PyUnicode_AS_UNICODE(format_spec),
1747 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001748}
1749
1750PyDoc_STRVAR(float__format__doc,
1751"float.__format__(format_spec) -> string\n"
1752"\n"
1753"Formats the float according to format_spec.");
1754
1755
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001756static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1758 "Returns self, the complex conjugate of any float."},
1759 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1760 "Returns the Integral closest to x between 0 and x."},
1761 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1762 "Returns the Integral closest to x, rounding half toward even.\n"
1763 "When an argument is passed, works like built-in round(x, ndigits)."},
1764 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1765 float_as_integer_ratio_doc},
1766 {"fromhex", (PyCFunction)float_fromhex,
1767 METH_O|METH_CLASS, float_fromhex_doc},
1768 {"hex", (PyCFunction)float_hex,
1769 METH_NOARGS, float_hex_doc},
1770 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1771 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001772#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1774 "Returns True if the float is positive or negative infinite."},
1775 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1776 "Returns True if the float is finite, neither infinite nor NaN."},
1777 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1778 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001779#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1781 {"__getformat__", (PyCFunction)float_getformat,
1782 METH_O|METH_CLASS, float_getformat_doc},
1783 {"__setformat__", (PyCFunction)float_setformat,
1784 METH_VARARGS|METH_CLASS, float_setformat_doc},
1785 {"__format__", (PyCFunction)float__format__,
1786 METH_VARARGS, float__format__doc},
1787 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001788};
1789
Guido van Rossumb43daf72007-08-01 18:08:08 +00001790static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001792 (getter)float_float, (setter)NULL,
1793 "the real part of a complex number",
1794 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001796 (getter)float_getzero, (setter)NULL,
1797 "the imaginary part of a complex number",
1798 NULL},
1799 {NULL} /* Sentinel */
1800};
1801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803"float(x) -> floating point number\n\
1804\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001805Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806
1807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001808static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 float_add, /*nb_add*/
1810 float_sub, /*nb_subtract*/
1811 float_mul, /*nb_multiply*/
1812 float_rem, /*nb_remainder*/
1813 float_divmod, /*nb_divmod*/
1814 float_pow, /*nb_power*/
1815 (unaryfunc)float_neg, /*nb_negative*/
1816 (unaryfunc)float_float, /*nb_positive*/
1817 (unaryfunc)float_abs, /*nb_absolute*/
1818 (inquiry)float_bool, /*nb_bool*/
1819 0, /*nb_invert*/
1820 0, /*nb_lshift*/
1821 0, /*nb_rshift*/
1822 0, /*nb_and*/
1823 0, /*nb_xor*/
1824 0, /*nb_or*/
1825 float_trunc, /*nb_int*/
1826 0, /*nb_reserved*/
1827 float_float, /*nb_float*/
1828 0, /* nb_inplace_add */
1829 0, /* nb_inplace_subtract */
1830 0, /* nb_inplace_multiply */
1831 0, /* nb_inplace_remainder */
1832 0, /* nb_inplace_power */
1833 0, /* nb_inplace_lshift */
1834 0, /* nb_inplace_rshift */
1835 0, /* nb_inplace_and */
1836 0, /* nb_inplace_xor */
1837 0, /* nb_inplace_or */
1838 float_floor_div, /* nb_floor_divide */
1839 float_div, /* nb_true_divide */
1840 0, /* nb_inplace_floor_divide */
1841 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842};
1843
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001844PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1846 "float",
1847 sizeof(PyFloatObject),
1848 0,
1849 (destructor)float_dealloc, /* tp_dealloc */
1850 0, /* tp_print */
1851 0, /* tp_getattr */
1852 0, /* tp_setattr */
1853 0, /* tp_reserved */
1854 (reprfunc)float_repr, /* tp_repr */
1855 &float_as_number, /* tp_as_number */
1856 0, /* tp_as_sequence */
1857 0, /* tp_as_mapping */
1858 (hashfunc)float_hash, /* tp_hash */
1859 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001860 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyObject_GenericGetAttr, /* tp_getattro */
1862 0, /* tp_setattro */
1863 0, /* tp_as_buffer */
1864 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1865 float_doc, /* tp_doc */
1866 0, /* tp_traverse */
1867 0, /* tp_clear */
1868 float_richcompare, /* tp_richcompare */
1869 0, /* tp_weaklistoffset */
1870 0, /* tp_iter */
1871 0, /* tp_iternext */
1872 float_methods, /* tp_methods */
1873 0, /* tp_members */
1874 float_getset, /* tp_getset */
1875 0, /* tp_base */
1876 0, /* tp_dict */
1877 0, /* tp_descr_get */
1878 0, /* tp_descr_set */
1879 0, /* tp_dictoffset */
1880 0, /* tp_init */
1881 0, /* tp_alloc */
1882 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001883};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001884
1885void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001886_PyFloat_Init(void)
1887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 /* We attempt to determine if this machine is using IEEE
1889 floating point formats by peering at the bits of some
1890 carefully chosen values. If it looks like we are on an
1891 IEEE platform, the float packing/unpacking routines can
1892 just copy bits, if not they resort to arithmetic & shifts
1893 and masks. The shifts & masks approach works on all finite
1894 values, but what happens to infinities, NaNs and signed
1895 zeroes on packing is an accident, and attempting to unpack
1896 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 Note that if we're on some whacked-out platform which uses
1899 IEEE formats but isn't strictly little-endian or big-
1900 endian, we will fall back to the portable shifts & masks
1901 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001902
1903#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 {
1905 double x = 9006104071832581.0;
1906 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1907 detected_double_format = ieee_big_endian_format;
1908 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1909 detected_double_format = ieee_little_endian_format;
1910 else
1911 detected_double_format = unknown_format;
1912 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001913#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001915#endif
1916
1917#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 {
1919 float y = 16711938.0;
1920 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1921 detected_float_format = ieee_big_endian_format;
1922 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1923 detected_float_format = ieee_little_endian_format;
1924 else
1925 detected_float_format = unknown_format;
1926 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001927#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001929#endif
1930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 double_format = detected_double_format;
1932 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* Init float info */
1935 if (FloatInfoType.tp_name == 0)
1936 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001937}
1938
Georg Brandl2ee470f2008-07-16 12:55:28 +00001939int
1940PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 PyFloatObject *p;
1943 PyFloatBlock *list, *next;
1944 int i;
1945 int u; /* remaining unfreed floats per block */
1946 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 list = block_list;
1949 block_list = NULL;
1950 free_list = NULL;
1951 while (list != NULL) {
1952 u = 0;
1953 for (i = 0, p = &list->objects[0];
1954 i < N_FLOATOBJECTS;
1955 i++, p++) {
1956 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1957 u++;
1958 }
1959 next = list->next;
1960 if (u) {
1961 list->next = block_list;
1962 block_list = list;
1963 for (i = 0, p = &list->objects[0];
1964 i < N_FLOATOBJECTS;
1965 i++, p++) {
1966 if (!PyFloat_CheckExact(p) ||
1967 Py_REFCNT(p) == 0) {
1968 Py_TYPE(p) = (struct _typeobject *)
1969 free_list;
1970 free_list = p;
1971 }
1972 }
1973 }
1974 else {
1975 PyMem_FREE(list);
1976 }
1977 freelist_size += u;
1978 list = next;
1979 }
1980 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001981}
1982
1983void
1984PyFloat_Fini(void)
1985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 PyFloatObject *p;
1987 PyFloatBlock *list;
1988 int i;
1989 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (!Py_VerboseFlag)
1994 return;
1995 fprintf(stderr, "# cleanup floats");
1996 if (!u) {
1997 fprintf(stderr, "\n");
1998 }
1999 else {
2000 fprintf(stderr,
2001 ": %d unfreed float%s\n",
2002 u, u == 1 ? "" : "s");
2003 }
2004 if (Py_VerboseFlag > 1) {
2005 list = block_list;
2006 while (list != NULL) {
2007 for (i = 0, p = &list->objects[0];
2008 i < N_FLOATOBJECTS;
2009 i++, p++) {
2010 if (PyFloat_CheckExact(p) &&
2011 Py_REFCNT(p) != 0) {
2012 char *buf = PyOS_double_to_string(
2013 PyFloat_AS_DOUBLE(p), 'r',
2014 0, 0, NULL);
2015 if (buf) {
2016 /* XXX(twouters) cast
2017 refcount to long
2018 until %zd is
2019 universally
2020 available
2021 */
2022 fprintf(stderr,
2023 "# <float at %p, refcnt=%ld, val=%s>\n",
2024 p, (long)Py_REFCNT(p), buf);
2025 PyMem_Free(buf);
2026 }
2027 }
2028 }
2029 list = list->next;
2030 }
2031 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002032}
Tim Peters9905b942003-03-20 20:53:32 +00002033
2034/*----------------------------------------------------------------------------
2035 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002036 */
2037int
2038_PyFloat_Pack4(double x, unsigned char *p, int le)
2039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (float_format == unknown_format) {
2041 unsigned char sign;
2042 int e;
2043 double f;
2044 unsigned int fbits;
2045 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 if (le) {
2048 p += 3;
2049 incr = -1;
2050 }
Tim Peters9905b942003-03-20 20:53:32 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (x < 0) {
2053 sign = 1;
2054 x = -x;
2055 }
2056 else
2057 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* Normalize f to be in the range [1.0, 2.0) */
2062 if (0.5 <= f && f < 1.0) {
2063 f *= 2.0;
2064 e--;
2065 }
2066 else if (f == 0.0)
2067 e = 0;
2068 else {
2069 PyErr_SetString(PyExc_SystemError,
2070 "frexp() result out of range");
2071 return -1;
2072 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 if (e >= 128)
2075 goto Overflow;
2076 else if (e < -126) {
2077 /* Gradual underflow */
2078 f = ldexp(f, 126 + e);
2079 e = 0;
2080 }
2081 else if (!(e == 0 && f == 0.0)) {
2082 e += 127;
2083 f -= 1.0; /* Get rid of leading 1 */
2084 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 f *= 8388608.0; /* 2**23 */
2087 fbits = (unsigned int)(f + 0.5); /* Round */
2088 assert(fbits <= 8388608);
2089 if (fbits >> 23) {
2090 /* The carry propagated out of a string of 23 1 bits. */
2091 fbits = 0;
2092 ++e;
2093 if (e >= 255)
2094 goto Overflow;
2095 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* First byte */
2098 *p = (sign << 7) | (e >> 1);
2099 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 /* Second byte */
2102 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2103 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 /* Third byte */
2106 *p = (fbits >> 8) & 0xFF;
2107 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Fourth byte */
2110 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 /* Done */
2113 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 }
2116 else {
2117 float y = (float)x;
2118 const char *s = (char*)&y;
2119 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2122 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if ((float_format == ieee_little_endian_format && !le)
2125 || (float_format == ieee_big_endian_format && le)) {
2126 p += 3;
2127 incr = -1;
2128 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 for (i = 0; i < 4; i++) {
2131 *p = *s++;
2132 p += incr;
2133 }
2134 return 0;
2135 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002136 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyErr_SetString(PyExc_OverflowError,
2138 "float too large to pack with f format");
2139 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002140}
2141
2142int
2143_PyFloat_Pack8(double x, unsigned char *p, int le)
2144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (double_format == unknown_format) {
2146 unsigned char sign;
2147 int e;
2148 double f;
2149 unsigned int fhi, flo;
2150 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (le) {
2153 p += 7;
2154 incr = -1;
2155 }
Tim Peters9905b942003-03-20 20:53:32 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (x < 0) {
2158 sign = 1;
2159 x = -x;
2160 }
2161 else
2162 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* Normalize f to be in the range [1.0, 2.0) */
2167 if (0.5 <= f && f < 1.0) {
2168 f *= 2.0;
2169 e--;
2170 }
2171 else if (f == 0.0)
2172 e = 0;
2173 else {
2174 PyErr_SetString(PyExc_SystemError,
2175 "frexp() result out of range");
2176 return -1;
2177 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (e >= 1024)
2180 goto Overflow;
2181 else if (e < -1022) {
2182 /* Gradual underflow */
2183 f = ldexp(f, 1022 + e);
2184 e = 0;
2185 }
2186 else if (!(e == 0 && f == 0.0)) {
2187 e += 1023;
2188 f -= 1.0; /* Get rid of leading 1 */
2189 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2192 f *= 268435456.0; /* 2**28 */
2193 fhi = (unsigned int)f; /* Truncate */
2194 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 f -= (double)fhi;
2197 f *= 16777216.0; /* 2**24 */
2198 flo = (unsigned int)(f + 0.5); /* Round */
2199 assert(flo <= 16777216);
2200 if (flo >> 24) {
2201 /* The carry propagated out of a string of 24 1 bits. */
2202 flo = 0;
2203 ++fhi;
2204 if (fhi >> 28) {
2205 /* And it also progagated out of the next 28 bits. */
2206 fhi = 0;
2207 ++e;
2208 if (e >= 2047)
2209 goto Overflow;
2210 }
2211 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* First byte */
2214 *p = (sign << 7) | (e >> 4);
2215 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* Second byte */
2218 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2219 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* Third byte */
2222 *p = (fhi >> 16) & 0xFF;
2223 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Fourth byte */
2226 *p = (fhi >> 8) & 0xFF;
2227 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* Fifth byte */
2230 *p = fhi & 0xFF;
2231 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Sixth byte */
2234 *p = (flo >> 16) & 0xFF;
2235 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Seventh byte */
2238 *p = (flo >> 8) & 0xFF;
2239 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Eighth byte */
2242 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002243 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* Done */
2246 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 Overflow:
2249 PyErr_SetString(PyExc_OverflowError,
2250 "float too large to pack with d format");
2251 return -1;
2252 }
2253 else {
2254 const char *s = (char*)&x;
2255 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if ((double_format == ieee_little_endian_format && !le)
2258 || (double_format == ieee_big_endian_format && le)) {
2259 p += 7;
2260 incr = -1;
2261 }
2262
2263 for (i = 0; i < 8; i++) {
2264 *p = *s++;
2265 p += incr;
2266 }
2267 return 0;
2268 }
Tim Peters9905b942003-03-20 20:53:32 +00002269}
2270
2271double
2272_PyFloat_Unpack4(const unsigned char *p, int le)
2273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (float_format == unknown_format) {
2275 unsigned char sign;
2276 int e;
2277 unsigned int f;
2278 double x;
2279 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (le) {
2282 p += 3;
2283 incr = -1;
2284 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* First byte */
2287 sign = (*p >> 7) & 1;
2288 e = (*p & 0x7F) << 1;
2289 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 /* Second byte */
2292 e |= (*p >> 7) & 1;
2293 f = (*p & 0x7F) << 16;
2294 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 if (e == 255) {
2297 PyErr_SetString(
2298 PyExc_ValueError,
2299 "can't unpack IEEE 754 special value "
2300 "on non-IEEE platform");
2301 return -1;
2302 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* Third byte */
2305 f |= *p << 8;
2306 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Fourth byte */
2309 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* XXX This sadly ignores Inf/NaN issues */
2314 if (e == 0)
2315 e = -126;
2316 else {
2317 x += 1.0;
2318 e -= 127;
2319 }
2320 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (sign)
2323 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 return x;
2326 }
2327 else {
2328 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 if ((float_format == ieee_little_endian_format && !le)
2331 || (float_format == ieee_big_endian_format && le)) {
2332 char buf[4];
2333 char *d = &buf[3];
2334 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 for (i = 0; i < 4; i++) {
2337 *d-- = *p++;
2338 }
2339 memcpy(&x, buf, 4);
2340 }
2341 else {
2342 memcpy(&x, p, 4);
2343 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return x;
2346 }
Tim Peters9905b942003-03-20 20:53:32 +00002347}
2348
2349double
2350_PyFloat_Unpack8(const unsigned char *p, int le)
2351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (double_format == unknown_format) {
2353 unsigned char sign;
2354 int e;
2355 unsigned int fhi, flo;
2356 double x;
2357 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if (le) {
2360 p += 7;
2361 incr = -1;
2362 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* First byte */
2365 sign = (*p >> 7) & 1;
2366 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* Second byte */
2371 e |= (*p >> 4) & 0xF;
2372 fhi = (*p & 0xF) << 24;
2373 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 if (e == 2047) {
2376 PyErr_SetString(
2377 PyExc_ValueError,
2378 "can't unpack IEEE 754 special value "
2379 "on non-IEEE platform");
2380 return -1.0;
2381 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* Third byte */
2384 fhi |= *p << 16;
2385 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* Fourth byte */
2388 fhi |= *p << 8;
2389 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Fifth byte */
2392 fhi |= *p;
2393 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* Sixth byte */
2396 flo = *p << 16;
2397 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Seventh byte */
2400 flo |= *p << 8;
2401 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Eighth byte */
2404 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2407 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 if (e == 0)
2410 e = -1022;
2411 else {
2412 x += 1.0;
2413 e -= 1023;
2414 }
2415 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (sign)
2418 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return x;
2421 }
2422 else {
2423 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if ((double_format == ieee_little_endian_format && !le)
2426 || (double_format == ieee_big_endian_format && le)) {
2427 char buf[8];
2428 char *d = &buf[7];
2429 int i;
2430
2431 for (i = 0; i < 8; i++) {
2432 *d-- = *p++;
2433 }
2434 memcpy(&x, buf, 8);
2435 }
2436 else {
2437 memcpy(&x, p, 8);
2438 }
2439
2440 return x;
2441 }
Tim Peters9905b942003-03-20 20:53:32 +00002442}