blob: a031d1b63bcfd10e26ee9f416a3b0eb042f1e986 [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:
Brian Curtindfc80e32011-08-10 20:28:54 -0500520 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000521}
522
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000523static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000524float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000527}
528
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000529static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000530float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 double a,b;
533 CONVERT_TO_DOUBLE(v, a);
534 CONVERT_TO_DOUBLE(w, b);
535 PyFPE_START_PROTECT("add", return 0)
536 a = a + b;
537 PyFPE_END_PROTECT(a)
538 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000539}
540
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000542float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 double a,b;
545 CONVERT_TO_DOUBLE(v, a);
546 CONVERT_TO_DOUBLE(w, b);
547 PyFPE_START_PROTECT("subtract", return 0)
548 a = a - b;
549 PyFPE_END_PROTECT(a)
550 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000551}
552
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000554float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 double a,b;
557 CONVERT_TO_DOUBLE(v, a);
558 CONVERT_TO_DOUBLE(w, b);
559 PyFPE_START_PROTECT("multiply", return 0)
560 a = a * b;
561 PyFPE_END_PROTECT(a)
562 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563}
564
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000566float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 double a,b;
569 CONVERT_TO_DOUBLE(v, a);
570 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (b == 0.0) {
572 PyErr_SetString(PyExc_ZeroDivisionError,
573 "float division by zero");
574 return NULL;
575 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 PyFPE_START_PROTECT("divide", return 0)
577 a = a / b;
578 PyFPE_END_PROTECT(a)
579 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580}
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000583float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 double vx, wx;
586 double mod;
587 CONVERT_TO_DOUBLE(v, vx);
588 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (wx == 0.0) {
590 PyErr_SetString(PyExc_ZeroDivisionError,
591 "float modulo");
592 return NULL;
593 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 PyFPE_START_PROTECT("modulo", return 0)
595 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000596 if (mod) {
597 /* ensure the remainder has the same sign as the denominator */
598 if ((wx < 0) != (mod < 0)) {
599 mod += wx;
600 }
601 }
602 else {
603 /* the remainder is zero, and in the presence of signed zeroes
604 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000605 it has the same sign as the denominator. */
606 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 }
608 PyFPE_END_PROTECT(mod)
609 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610}
611
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000613float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 double vx, wx;
616 double div, mod, floordiv;
617 CONVERT_TO_DOUBLE(v, vx);
618 CONVERT_TO_DOUBLE(w, wx);
619 if (wx == 0.0) {
620 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
621 return NULL;
622 }
623 PyFPE_START_PROTECT("divmod", return 0)
624 mod = fmod(vx, wx);
625 /* fmod is typically exact, so vx-mod is *mathematically* an
626 exact multiple of wx. But this is fp arithmetic, and fp
627 vx - mod is an approximation; the result is that div may
628 not be an exact integral value after the division, although
629 it will always be very close to one.
630 */
631 div = (vx - mod) / wx;
632 if (mod) {
633 /* ensure the remainder has the same sign as the denominator */
634 if ((wx < 0) != (mod < 0)) {
635 mod += wx;
636 div -= 1.0;
637 }
638 }
639 else {
640 /* the remainder is zero, and in the presence of signed zeroes
641 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000642 it has the same sign as the denominator. */
643 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
645 /* snap quotient to nearest integral value */
646 if (div) {
647 floordiv = floor(div);
648 if (div - floordiv > 0.5)
649 floordiv += 1.0;
650 }
651 else {
652 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000653 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 }
655 PyFPE_END_PROTECT(floordiv)
656 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000660float_floor_div(PyObject *v, PyObject *w)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 t = float_divmod(v, w);
665 if (t == NULL || t == Py_NotImplemented)
666 return t;
667 assert(PyTuple_CheckExact(t));
668 r = PyTuple_GET_ITEM(t, 0);
669 Py_INCREF(r);
670 Py_DECREF(t);
671 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000672}
673
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000674/* determine whether x is an odd integer or not; assumes that
675 x is not an infinity or nan. */
676#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
677
Tim Peters63a35712001-12-11 19:57:24 +0000678static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 double iv, iw, ix;
682 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if ((PyObject *)z != Py_None) {
685 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
686 "allowed unless all arguments are integers");
687 return NULL;
688 }
Tim Peters32f453e2001-09-03 08:35:41 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 CONVERT_TO_DOUBLE(v, iv);
691 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* Sort out special cases here instead of relying on pow() */
694 if (iw == 0) { /* v**0 is 1, even 0**0 */
695 return PyFloat_FromDouble(1.0);
696 }
697 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
698 return PyFloat_FromDouble(iv);
699 }
700 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
701 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
702 }
703 if (Py_IS_INFINITY(iw)) {
704 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
705 * abs(v) > 1 (including case where v infinite)
706 *
707 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
708 * abs(v) > 1 (including case where v infinite)
709 */
710 iv = fabs(iv);
711 if (iv == 1.0)
712 return PyFloat_FromDouble(1.0);
713 else if ((iw > 0.0) == (iv > 1.0))
714 return PyFloat_FromDouble(fabs(iw)); /* return inf */
715 else
716 return PyFloat_FromDouble(0.0);
717 }
718 if (Py_IS_INFINITY(iv)) {
719 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
720 * both cases, we need to add the appropriate sign if w is
721 * an odd integer.
722 */
723 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
724 if (iw > 0.0)
725 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
726 else
727 return PyFloat_FromDouble(iw_is_odd ?
728 copysign(0.0, iv) : 0.0);
729 }
730 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
731 (already dealt with above), and an error
732 if w is negative. */
733 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
734 if (iw < 0.0) {
735 PyErr_SetString(PyExc_ZeroDivisionError,
736 "0.0 cannot be raised to a "
737 "negative power");
738 return NULL;
739 }
740 /* use correct sign if iw is odd */
741 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
742 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (iv < 0.0) {
745 /* Whether this is an error is a mess, and bumps into libm
746 * bugs so we have to figure it out ourselves.
747 */
748 if (iw != floor(iw)) {
749 /* Negative numbers raised to fractional powers
750 * become complex.
751 */
752 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
753 }
754 /* iw is an exact integer, albeit perhaps a very large
755 * one. Replace iv by its absolute value and remember
756 * to negate the pow result if iw is odd.
757 */
758 iv = -iv;
759 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
760 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
763 /* (-1) ** large_integer also ends up here. Here's an
764 * extract from the comments for the previous
765 * implementation explaining why this special case is
766 * necessary:
767 *
768 * -1 raised to an exact integer should never be exceptional.
769 * Alas, some libms (chiefly glibc as of early 2003) return
770 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
771 * happen to be representable in a *C* integer. That's a
772 * bug.
773 */
774 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
775 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* Now iv and iw are finite, iw is nonzero, and iv is
778 * positive and not equal to 1.0. We finally allow
779 * the platform pow to step in and do the rest.
780 */
781 errno = 0;
782 PyFPE_START_PROTECT("pow", return NULL)
783 ix = pow(iv, iw);
784 PyFPE_END_PROTECT(ix)
785 Py_ADJUST_ERANGE1(ix);
786 if (negate_result)
787 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (errno != 0) {
790 /* We don't expect any errno value other than ERANGE, but
791 * the range of libm bugs appears unbounded.
792 */
793 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
794 PyExc_ValueError);
795 return NULL;
796 }
797 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798}
799
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000800#undef DOUBLE_IS_ODD_INTEGER
801
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000802static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000803float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806}
807
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000809float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000814static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000815float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000818}
819
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000820static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000821float_is_integer(PyObject *v)
822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 double x = PyFloat_AsDouble(v);
824 PyObject *o;
825
826 if (x == -1.0 && PyErr_Occurred())
827 return NULL;
828 if (!Py_IS_FINITE(x))
829 Py_RETURN_FALSE;
830 errno = 0;
831 PyFPE_START_PROTECT("is_integer", return NULL)
832 o = (floor(x) == x) ? Py_True : Py_False;
833 PyFPE_END_PROTECT(x)
834 if (errno != 0) {
835 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
836 PyExc_ValueError);
837 return NULL;
838 }
839 Py_INCREF(o);
840 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000841}
842
843#if 0
844static PyObject *
845float_is_inf(PyObject *v)
846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 double x = PyFloat_AsDouble(v);
848 if (x == -1.0 && PyErr_Occurred())
849 return NULL;
850 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000851}
852
853static PyObject *
854float_is_nan(PyObject *v)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 double x = PyFloat_AsDouble(v);
857 if (x == -1.0 && PyErr_Occurred())
858 return NULL;
859 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000860}
861
862static PyObject *
863float_is_finite(PyObject *v)
864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 double x = PyFloat_AsDouble(v);
866 if (x == -1.0 && PyErr_Occurred())
867 return NULL;
868 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000869}
870#endif
871
872static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000873float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 double x = PyFloat_AsDouble(v);
876 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 (void)modf(x, &wholepart);
879 /* Try to get out cheap if this fits in a Python int. The attempt
880 * to cast to long must be protected, as C doesn't define what
881 * happens if the double is too big to fit in a long. Some rare
882 * systems raise an exception then (RISCOS was mentioned as one,
883 * and someone using a non-default option on Sun also bumped into
884 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
885 * still be vulnerable: if a long has more bits of precision than
886 * a double, casting MIN/MAX to double may yield an approximation,
887 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
888 * yield true from the C expression wholepart<=LONG_MAX, despite
889 * that wholepart is actually greater than LONG_MAX.
890 */
891 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
892 const long aslong = (long)wholepart;
893 return PyLong_FromLong(aslong);
894 }
895 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000896}
897
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000898/* double_round: rounds a finite double to the closest multiple of
899 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
900 ndigits <= 323). Returns a Python float, or sets a Python error and
901 returns NULL on failure (OverflowError and memory errors are possible). */
902
903#ifndef PY_NO_SHORT_FLOAT_REPR
904/* version of double_round that uses the correctly-rounded string<->double
905 conversions from Python/dtoa.c */
906
907static PyObject *
908double_round(double x, int ndigits) {
909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 double rounded;
911 Py_ssize_t buflen, mybuflen=100;
912 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
913 int decpt, sign;
914 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* round to a decimal string */
917 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
918 if (buf == NULL) {
919 PyErr_NoMemory();
920 return NULL;
921 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
924 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
925 buflen = buf_end - buf;
926 if (buflen + 8 > mybuflen) {
927 mybuflen = buflen+8;
928 mybuf = (char *)PyMem_Malloc(mybuflen);
929 if (mybuf == NULL) {
930 PyErr_NoMemory();
931 goto exit;
932 }
933 }
934 /* copy buf to mybuf, adding exponent, sign and leading 0 */
935 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
936 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* and convert the resulting string back to a double */
939 errno = 0;
940 rounded = _Py_dg_strtod(mybuf, NULL);
941 if (errno == ERANGE && fabs(rounded) >= 1.)
942 PyErr_SetString(PyExc_OverflowError,
943 "rounded value too large to represent");
944 else
945 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* done computing value; now clean up */
948 if (mybuf != shortbuf)
949 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000950 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 _Py_dg_freedtoa(buf);
952 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953}
954
955#else /* PY_NO_SHORT_FLOAT_REPR */
956
957/* fallback version, to be used when correctly rounded binary<->decimal
958 conversions aren't available */
959
960static PyObject *
961double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 double pow1, pow2, y, z;
963 if (ndigits >= 0) {
964 if (ndigits > 22) {
965 /* pow1 and pow2 are each safe from overflow, but
966 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
967 pow1 = pow(10.0, (double)(ndigits-22));
968 pow2 = 1e22;
969 }
970 else {
971 pow1 = pow(10.0, (double)ndigits);
972 pow2 = 1.0;
973 }
974 y = (x*pow1)*pow2;
975 /* if y overflows, then rounded value is exactly x */
976 if (!Py_IS_FINITE(y))
977 return PyFloat_FromDouble(x);
978 }
979 else {
980 pow1 = pow(10.0, (double)-ndigits);
981 pow2 = 1.0; /* unused; silences a gcc compiler warning */
982 y = x / pow1;
983 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 z = round(y);
986 if (fabs(y-z) == 0.5)
987 /* halfway between two integers; use round-half-even */
988 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (ndigits >= 0)
991 z = (z / pow2) / pow1;
992 else
993 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* if computation resulted in overflow, raise OverflowError */
996 if (!Py_IS_FINITE(z)) {
997 PyErr_SetString(PyExc_OverflowError,
998 "overflow occurred during round");
999 return NULL;
1000 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003}
1004
1005#endif /* PY_NO_SHORT_FLOAT_REPR */
1006
1007/* round a Python float v to the closest multiple of 10**-ndigits */
1008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001009static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001010float_round(PyObject *v, PyObject *args)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 double x, rounded;
1013 PyObject *o_ndigits = NULL;
1014 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 x = PyFloat_AsDouble(v);
1017 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1018 return NULL;
1019 if (o_ndigits == NULL) {
1020 /* single-argument round: round to nearest integer */
1021 rounded = round(x);
1022 if (fabs(x-rounded) == 0.5)
1023 /* halfway case: round to even */
1024 rounded = 2.0*round(x/2.0);
1025 return PyLong_FromDouble(rounded);
1026 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* interpret second argument as a Py_ssize_t; clips on overflow */
1029 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1030 if (ndigits == -1 && PyErr_Occurred())
1031 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 /* nans and infinities round to themselves */
1034 if (!Py_IS_FINITE(x))
1035 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1038 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1039 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001040#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1041#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (ndigits > NDIGITS_MAX)
1043 /* return x */
1044 return PyFloat_FromDouble(x);
1045 else if (ndigits < NDIGITS_MIN)
1046 /* return 0.0, but with sign of x */
1047 return PyFloat_FromDouble(0.0*x);
1048 else
1049 /* finite x, and ndigits is not unreasonably large */
1050 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001051#undef NDIGITS_MAX
1052#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001053}
1054
1055static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001056float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 if (PyFloat_CheckExact(v))
1059 Py_INCREF(v);
1060 else
1061 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1062 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063}
1064
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001065/* turn ASCII hex characters into integer values and vice versa */
1066
1067static char
1068char_from_hex(int x)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 assert(0 <= x && x < 16);
1071 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001072}
1073
1074static int
1075hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 int x;
1077 switch(c) {
1078 case '0':
1079 x = 0;
1080 break;
1081 case '1':
1082 x = 1;
1083 break;
1084 case '2':
1085 x = 2;
1086 break;
1087 case '3':
1088 x = 3;
1089 break;
1090 case '4':
1091 x = 4;
1092 break;
1093 case '5':
1094 x = 5;
1095 break;
1096 case '6':
1097 x = 6;
1098 break;
1099 case '7':
1100 x = 7;
1101 break;
1102 case '8':
1103 x = 8;
1104 break;
1105 case '9':
1106 x = 9;
1107 break;
1108 case 'a':
1109 case 'A':
1110 x = 10;
1111 break;
1112 case 'b':
1113 case 'B':
1114 x = 11;
1115 break;
1116 case 'c':
1117 case 'C':
1118 x = 12;
1119 break;
1120 case 'd':
1121 case 'D':
1122 x = 13;
1123 break;
1124 case 'e':
1125 case 'E':
1126 x = 14;
1127 break;
1128 case 'f':
1129 case 'F':
1130 x = 15;
1131 break;
1132 default:
1133 x = -1;
1134 break;
1135 }
1136 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001137}
1138
1139/* convert a float to a hexadecimal string */
1140
1141/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1142 of the form 4k+1. */
1143#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1144
1145static PyObject *
1146float_hex(PyObject *v)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 double x, m;
1149 int e, shift, i, si, esign;
1150 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1151 trailing NUL byte. */
1152 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001157 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001160 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return PyUnicode_FromString("-0x0.0p+0");
1162 else
1163 return PyUnicode_FromString("0x0.0p+0");
1164 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 m = frexp(fabs(x), &e);
1167 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1168 m = ldexp(m, shift);
1169 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 si = 0;
1172 s[si] = char_from_hex((int)m);
1173 si++;
1174 m -= (int)m;
1175 s[si] = '.';
1176 si++;
1177 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1178 m *= 16.0;
1179 s[si] = char_from_hex((int)m);
1180 si++;
1181 m -= (int)m;
1182 }
1183 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (e < 0) {
1186 esign = (int)'-';
1187 e = -e;
1188 }
1189 else
1190 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (x < 0.0)
1193 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1194 else
1195 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001196}
1197
1198PyDoc_STRVAR(float_hex_doc,
1199"float.hex() -> string\n\
1200\n\
1201Return a hexadecimal representation of a floating-point number.\n\
1202>>> (-0.1).hex()\n\
1203'-0x1.999999999999ap-4'\n\
1204>>> 3.14159.hex()\n\
1205'0x1.921f9f01b866ep+1'");
1206
1207/* Convert a hexadecimal string to a float. */
1208
1209static PyObject *
1210float_fromhex(PyObject *cls, PyObject *arg)
1211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *result_as_float, *result;
1213 double x;
1214 long exp, top_exp, lsb, key_digit;
1215 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1216 int half_eps, digit, round_up, negate=0;
1217 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /*
1220 * For the sake of simplicity and correctness, we impose an artificial
1221 * limit on ndigits, the total number of hex digits in the coefficient
1222 * The limit is chosen to ensure that, writing exp for the exponent,
1223 *
1224 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1225 * guaranteed to overflow (provided it's nonzero)
1226 *
1227 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1228 * guaranteed to underflow to 0.
1229 *
1230 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1231 * overflow in the calculation of exp and top_exp below.
1232 *
1233 * More specifically, ndigits is assumed to satisfy the following
1234 * inequalities:
1235 *
1236 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1237 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1238 *
1239 * If either of these inequalities is not satisfied, a ValueError is
1240 * raised. Otherwise, write x for the value of the hex string, and
1241 * assume x is nonzero. Then
1242 *
1243 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1244 *
1245 * Now if exp > LONG_MAX/2 then:
1246 *
1247 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1248 * = DBL_MAX_EXP
1249 *
1250 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1251 * double, so overflows. If exp < LONG_MIN/2, then
1252 *
1253 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1254 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1255 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1256 *
1257 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1258 * when converted to a C double.
1259 *
1260 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1261 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1262 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 s = _PyUnicode_AsStringAndSize(arg, &length);
1265 if (s == NULL)
1266 return NULL;
1267 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /********************
1270 * Parse the string *
1271 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* leading whitespace */
1274 while (Py_ISSPACE(*s))
1275 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 /* infinities and nans */
1278 x = _Py_parse_inf_or_nan(s, &coeff_end);
1279 if (coeff_end != s) {
1280 s = coeff_end;
1281 goto finished;
1282 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* optional sign */
1285 if (*s == '-') {
1286 s++;
1287 negate = 1;
1288 }
1289 else if (*s == '+')
1290 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* [0x] */
1293 s_store = s;
1294 if (*s == '0') {
1295 s++;
1296 if (*s == 'x' || *s == 'X')
1297 s++;
1298 else
1299 s = s_store;
1300 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* coefficient: <integer> [. <fraction>] */
1303 coeff_start = s;
1304 while (hex_from_char(*s) >= 0)
1305 s++;
1306 s_store = s;
1307 if (*s == '.') {
1308 s++;
1309 while (hex_from_char(*s) >= 0)
1310 s++;
1311 coeff_end = s-1;
1312 }
1313 else
1314 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /* ndigits = total # of hex digits; fdigits = # after point */
1317 ndigits = coeff_end - coeff_start;
1318 fdigits = coeff_end - s_store;
1319 if (ndigits == 0)
1320 goto parse_error;
1321 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1322 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1323 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* [p <exponent>] */
1326 if (*s == 'p' || *s == 'P') {
1327 s++;
1328 exp_start = s;
1329 if (*s == '-' || *s == '+')
1330 s++;
1331 if (!('0' <= *s && *s <= '9'))
1332 goto parse_error;
1333 s++;
1334 while ('0' <= *s && *s <= '9')
1335 s++;
1336 exp = strtol(exp_start, NULL, 10);
1337 }
1338 else
1339 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1343 coeff_end-(j) : \
1344 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /*******************************************
1347 * Compute rounded value of the hex string *
1348 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* Discard leading zeros, and catch extreme overflow and underflow */
1351 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1352 ndigits--;
1353 if (ndigits == 0 || exp < LONG_MIN/2) {
1354 x = 0.0;
1355 goto finished;
1356 }
1357 if (exp > LONG_MAX/2)
1358 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* Adjust exponent for fractional part. */
1361 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1364 top_exp = exp + 4*((long)ndigits - 1);
1365 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1366 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* catch almost all nonextreme cases of overflow and underflow here */
1369 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1370 x = 0.0;
1371 goto finished;
1372 }
1373 if (top_exp > DBL_MAX_EXP)
1374 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* lsb = exponent of least significant bit of the *rounded* value.
1377 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1378 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 x = 0.0;
1381 if (exp >= lsb) {
1382 /* no rounding required */
1383 for (i = ndigits-1; i >= 0; i--)
1384 x = 16.0*x + HEX_DIGIT(i);
1385 x = ldexp(x, (int)(exp));
1386 goto finished;
1387 }
1388 /* rounding required. key_digit is the index of the hex digit
1389 containing the first bit to be rounded away. */
1390 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1391 key_digit = (lsb - exp - 1) / 4;
1392 for (i = ndigits-1; i > key_digit; i--)
1393 x = 16.0*x + HEX_DIGIT(i);
1394 digit = HEX_DIGIT(key_digit);
1395 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1398 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1399 if ((digit & half_eps) != 0) {
1400 round_up = 0;
1401 if ((digit & (3*half_eps-1)) != 0 ||
1402 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1403 round_up = 1;
1404 else
1405 for (i = key_digit-1; i >= 0; i--)
1406 if (HEX_DIGIT(i) != 0) {
1407 round_up = 1;
1408 break;
1409 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001410 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 x += 2*half_eps;
1412 if (top_exp == DBL_MAX_EXP &&
1413 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1414 /* overflow corner case: pre-rounded value <
1415 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1416 goto overflow_error;
1417 }
1418 }
1419 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001420
1421 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* optional trailing whitespace leading to the end of the string */
1423 while (Py_ISSPACE(*s))
1424 s++;
1425 if (s != s_end)
1426 goto parse_error;
1427 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1428 if (result_as_float == NULL)
1429 return NULL;
1430 result = PyObject_CallObject(cls, result_as_float);
1431 Py_DECREF(result_as_float);
1432 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001433
1434 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyErr_SetString(PyExc_OverflowError,
1436 "hexadecimal value too large to represent as a float");
1437 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001438
1439 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 PyErr_SetString(PyExc_ValueError,
1441 "invalid hexadecimal floating-point string");
1442 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443
1444 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyErr_SetString(PyExc_ValueError,
1446 "hexadecimal string too long to convert");
1447 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001448}
1449
1450PyDoc_STRVAR(float_fromhex_doc,
1451"float.fromhex(string) -> float\n\
1452\n\
1453Create a floating-point number from a hexadecimal string.\n\
1454>>> float.fromhex('0x1.ffffp10')\n\
14552047.984375\n\
1456>>> float.fromhex('-0x1p-1074')\n\
1457-4.9406564584124654e-324");
1458
1459
Christian Heimes26855632008-01-27 23:50:43 +00001460static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001461float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 double self;
1464 double float_part;
1465 int exponent;
1466 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *prev;
1469 PyObject *py_exponent = NULL;
1470 PyObject *numerator = NULL;
1471 PyObject *denominator = NULL;
1472 PyObject *result_pair = NULL;
1473 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001474
1475#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 prev = obj; \
1477 obj = call; \
1478 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (Py_IS_INFINITY(self)) {
1483 PyErr_SetString(PyExc_OverflowError,
1484 "Cannot pass infinity to float.as_integer_ratio.");
1485 return NULL;
1486 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (Py_IS_NAN(self)) {
1488 PyErr_SetString(PyExc_ValueError,
1489 "Cannot pass NaN to float.as_integer_ratio.");
1490 return NULL;
1491 }
Christian Heimes26855632008-01-27 23:50:43 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1494 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1495 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1498 float_part *= 2.0;
1499 exponent--;
1500 }
1501 /* self == float_part * 2**exponent exactly and float_part is integral.
1502 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1503 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 numerator = PyLong_FromDouble(float_part);
1506 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /* fold in 2**exponent */
1509 denominator = PyLong_FromLong(1);
1510 py_exponent = PyLong_FromLong(labs((long)exponent));
1511 if (py_exponent == NULL) goto error;
1512 INPLACE_UPDATE(py_exponent,
1513 long_methods->nb_lshift(denominator, py_exponent));
1514 if (py_exponent == NULL) goto error;
1515 if (exponent > 0) {
1516 INPLACE_UPDATE(numerator,
1517 long_methods->nb_multiply(numerator, py_exponent));
1518 if (numerator == NULL) goto error;
1519 }
1520 else {
1521 Py_DECREF(denominator);
1522 denominator = py_exponent;
1523 py_exponent = NULL;
1524 }
1525
1526 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001527
1528#undef INPLACE_UPDATE
1529error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_XDECREF(py_exponent);
1531 Py_XDECREF(denominator);
1532 Py_XDECREF(numerator);
1533 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001534}
1535
1536PyDoc_STRVAR(float_as_integer_ratio_doc,
1537"float.as_integer_ratio() -> (int, int)\n"
1538"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001539"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1540"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001541"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001542"\n"
1543">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001544"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001545">>> (0.0).as_integer_ratio()\n"
1546"(0, 1)\n"
1547">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001548"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001549
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001550
Jeremy Hylton938ace62002-07-17 16:30:39 +00001551static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001552float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1553
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554static PyObject *
1555float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyObject *x = Py_False; /* Integer zero */
1558 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (type != &PyFloat_Type)
1561 return float_subtype_new(type, args, kwds); /* Wimp out */
1562 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1563 return NULL;
1564 /* If it's a string, but not a string subclass, use
1565 PyFloat_FromString. */
1566 if (PyUnicode_CheckExact(x))
1567 return PyFloat_FromString(x);
1568 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569}
1570
Guido van Rossumbef14172001-08-29 15:47:46 +00001571/* Wimpy, slow approach to tp_new calls for subtypes of float:
1572 first create a regular float from whatever arguments we got,
1573 then allocate a subtype instance and initialize its ob_fval
1574 from the regular float. The regular float is then thrown away.
1575*/
1576static PyObject *
1577float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 assert(PyType_IsSubtype(type, &PyFloat_Type));
1582 tmp = float_new(&PyFloat_Type, args, kwds);
1583 if (tmp == NULL)
1584 return NULL;
1585 assert(PyFloat_CheckExact(tmp));
1586 newobj = type->tp_alloc(type, 0);
1587 if (newobj == NULL) {
1588 Py_DECREF(tmp);
1589 return NULL;
1590 }
1591 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1592 Py_DECREF(tmp);
1593 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001594}
1595
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001596static PyObject *
1597float_getnewargs(PyFloatObject *v)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001600}
1601
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001602/* this is for the benefit of the pack/unpack routines below */
1603
1604typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001606} float_format_type;
1607
1608static float_format_type double_format, float_format;
1609static float_format_type detected_double_format, detected_float_format;
1610
1611static PyObject *
1612float_getformat(PyTypeObject *v, PyObject* arg)
1613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 char* s;
1615 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 if (!PyUnicode_Check(arg)) {
1618 PyErr_Format(PyExc_TypeError,
1619 "__getformat__() argument must be string, not %.500s",
1620 Py_TYPE(arg)->tp_name);
1621 return NULL;
1622 }
1623 s = _PyUnicode_AsString(arg);
1624 if (s == NULL)
1625 return NULL;
1626 if (strcmp(s, "double") == 0) {
1627 r = double_format;
1628 }
1629 else if (strcmp(s, "float") == 0) {
1630 r = float_format;
1631 }
1632 else {
1633 PyErr_SetString(PyExc_ValueError,
1634 "__getformat__() argument 1 must be "
1635 "'double' or 'float'");
1636 return NULL;
1637 }
1638
1639 switch (r) {
1640 case unknown_format:
1641 return PyUnicode_FromString("unknown");
1642 case ieee_little_endian_format:
1643 return PyUnicode_FromString("IEEE, little-endian");
1644 case ieee_big_endian_format:
1645 return PyUnicode_FromString("IEEE, big-endian");
1646 default:
1647 Py_FatalError("insane float_format or double_format");
1648 return NULL;
1649 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001650}
1651
1652PyDoc_STRVAR(float_getformat_doc,
1653"float.__getformat__(typestr) -> string\n"
1654"\n"
1655"You probably don't want to use this function. It exists mainly to be\n"
1656"used in Python's test suite.\n"
1657"\n"
1658"typestr must be 'double' or 'float'. This function returns whichever of\n"
1659"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1660"format of floating point numbers used by the C type named by typestr.");
1661
1662static PyObject *
1663float_setformat(PyTypeObject *v, PyObject* args)
1664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 char* typestr;
1666 char* format;
1667 float_format_type f;
1668 float_format_type detected;
1669 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1672 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (strcmp(typestr, "double") == 0) {
1675 p = &double_format;
1676 detected = detected_double_format;
1677 }
1678 else if (strcmp(typestr, "float") == 0) {
1679 p = &float_format;
1680 detected = detected_float_format;
1681 }
1682 else {
1683 PyErr_SetString(PyExc_ValueError,
1684 "__setformat__() argument 1 must "
1685 "be 'double' or 'float'");
1686 return NULL;
1687 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (strcmp(format, "unknown") == 0) {
1690 f = unknown_format;
1691 }
1692 else if (strcmp(format, "IEEE, little-endian") == 0) {
1693 f = ieee_little_endian_format;
1694 }
1695 else if (strcmp(format, "IEEE, big-endian") == 0) {
1696 f = ieee_big_endian_format;
1697 }
1698 else {
1699 PyErr_SetString(PyExc_ValueError,
1700 "__setformat__() argument 2 must be "
1701 "'unknown', 'IEEE, little-endian' or "
1702 "'IEEE, big-endian'");
1703 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (f != unknown_format && f != detected) {
1708 PyErr_Format(PyExc_ValueError,
1709 "can only set %s format to 'unknown' or the "
1710 "detected platform value", typestr);
1711 return NULL;
1712 }
1713
1714 *p = f;
1715 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716}
1717
1718PyDoc_STRVAR(float_setformat_doc,
1719"float.__setformat__(typestr, fmt) -> None\n"
1720"\n"
1721"You probably don't want to use this function. It exists mainly to be\n"
1722"used in Python's test suite.\n"
1723"\n"
1724"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1725"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1726"one of the latter two if it appears to match the underlying C reality.\n"
1727"\n"
1728"Overrides the automatic determination of C-level floating point type.\n"
1729"This affects how floats are converted to and from binary strings.");
1730
Guido van Rossumb43daf72007-08-01 18:08:08 +00001731static PyObject *
1732float_getzero(PyObject *v, void *closure)
1733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001735}
1736
Eric Smith8c663262007-08-25 02:26:07 +00001737static PyObject *
1738float__format__(PyObject *self, PyObject *args)
1739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1743 return NULL;
1744 return _PyFloat_FormatAdvanced(self,
1745 PyUnicode_AS_UNICODE(format_spec),
1746 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001747}
1748
1749PyDoc_STRVAR(float__format__doc,
1750"float.__format__(format_spec) -> string\n"
1751"\n"
1752"Formats the float according to format_spec.");
1753
1754
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001755static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1757 "Returns self, the complex conjugate of any float."},
1758 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1759 "Returns the Integral closest to x between 0 and x."},
1760 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1761 "Returns the Integral closest to x, rounding half toward even.\n"
1762 "When an argument is passed, works like built-in round(x, ndigits)."},
1763 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1764 float_as_integer_ratio_doc},
1765 {"fromhex", (PyCFunction)float_fromhex,
1766 METH_O|METH_CLASS, float_fromhex_doc},
1767 {"hex", (PyCFunction)float_hex,
1768 METH_NOARGS, float_hex_doc},
1769 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1770 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001771#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1773 "Returns True if the float is positive or negative infinite."},
1774 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1775 "Returns True if the float is finite, neither infinite nor NaN."},
1776 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1777 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001778#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1780 {"__getformat__", (PyCFunction)float_getformat,
1781 METH_O|METH_CLASS, float_getformat_doc},
1782 {"__setformat__", (PyCFunction)float_setformat,
1783 METH_VARARGS|METH_CLASS, float_setformat_doc},
1784 {"__format__", (PyCFunction)float__format__,
1785 METH_VARARGS, float__format__doc},
1786 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001787};
1788
Guido van Rossumb43daf72007-08-01 18:08:08 +00001789static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001791 (getter)float_float, (setter)NULL,
1792 "the real part of a complex number",
1793 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001795 (getter)float_getzero, (setter)NULL,
1796 "the imaginary part of a complex number",
1797 NULL},
1798 {NULL} /* Sentinel */
1799};
1800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001801PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802"float(x) -> floating point number\n\
1803\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001804Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805
1806
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001807static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 float_add, /*nb_add*/
1809 float_sub, /*nb_subtract*/
1810 float_mul, /*nb_multiply*/
1811 float_rem, /*nb_remainder*/
1812 float_divmod, /*nb_divmod*/
1813 float_pow, /*nb_power*/
1814 (unaryfunc)float_neg, /*nb_negative*/
1815 (unaryfunc)float_float, /*nb_positive*/
1816 (unaryfunc)float_abs, /*nb_absolute*/
1817 (inquiry)float_bool, /*nb_bool*/
1818 0, /*nb_invert*/
1819 0, /*nb_lshift*/
1820 0, /*nb_rshift*/
1821 0, /*nb_and*/
1822 0, /*nb_xor*/
1823 0, /*nb_or*/
1824 float_trunc, /*nb_int*/
1825 0, /*nb_reserved*/
1826 float_float, /*nb_float*/
1827 0, /* nb_inplace_add */
1828 0, /* nb_inplace_subtract */
1829 0, /* nb_inplace_multiply */
1830 0, /* nb_inplace_remainder */
1831 0, /* nb_inplace_power */
1832 0, /* nb_inplace_lshift */
1833 0, /* nb_inplace_rshift */
1834 0, /* nb_inplace_and */
1835 0, /* nb_inplace_xor */
1836 0, /* nb_inplace_or */
1837 float_floor_div, /* nb_floor_divide */
1838 float_div, /* nb_true_divide */
1839 0, /* nb_inplace_floor_divide */
1840 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001841};
1842
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001843PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1845 "float",
1846 sizeof(PyFloatObject),
1847 0,
1848 (destructor)float_dealloc, /* tp_dealloc */
1849 0, /* tp_print */
1850 0, /* tp_getattr */
1851 0, /* tp_setattr */
1852 0, /* tp_reserved */
1853 (reprfunc)float_repr, /* tp_repr */
1854 &float_as_number, /* tp_as_number */
1855 0, /* tp_as_sequence */
1856 0, /* tp_as_mapping */
1857 (hashfunc)float_hash, /* tp_hash */
1858 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001859 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 PyObject_GenericGetAttr, /* tp_getattro */
1861 0, /* tp_setattro */
1862 0, /* tp_as_buffer */
1863 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1864 float_doc, /* tp_doc */
1865 0, /* tp_traverse */
1866 0, /* tp_clear */
1867 float_richcompare, /* tp_richcompare */
1868 0, /* tp_weaklistoffset */
1869 0, /* tp_iter */
1870 0, /* tp_iternext */
1871 float_methods, /* tp_methods */
1872 0, /* tp_members */
1873 float_getset, /* tp_getset */
1874 0, /* tp_base */
1875 0, /* tp_dict */
1876 0, /* tp_descr_get */
1877 0, /* tp_descr_set */
1878 0, /* tp_dictoffset */
1879 0, /* tp_init */
1880 0, /* tp_alloc */
1881 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001882};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001883
1884void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001885_PyFloat_Init(void)
1886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* We attempt to determine if this machine is using IEEE
1888 floating point formats by peering at the bits of some
1889 carefully chosen values. If it looks like we are on an
1890 IEEE platform, the float packing/unpacking routines can
1891 just copy bits, if not they resort to arithmetic & shifts
1892 and masks. The shifts & masks approach works on all finite
1893 values, but what happens to infinities, NaNs and signed
1894 zeroes on packing is an accident, and attempting to unpack
1895 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 Note that if we're on some whacked-out platform which uses
1898 IEEE formats but isn't strictly little-endian or big-
1899 endian, we will fall back to the portable shifts & masks
1900 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901
1902#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 {
1904 double x = 9006104071832581.0;
1905 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1906 detected_double_format = ieee_big_endian_format;
1907 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1908 detected_double_format = ieee_little_endian_format;
1909 else
1910 detected_double_format = unknown_format;
1911 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001912#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001914#endif
1915
1916#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 {
1918 float y = 16711938.0;
1919 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1920 detected_float_format = ieee_big_endian_format;
1921 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1922 detected_float_format = ieee_little_endian_format;
1923 else
1924 detected_float_format = unknown_format;
1925 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001926#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001928#endif
1929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 double_format = detected_double_format;
1931 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 /* Init float info */
1934 if (FloatInfoType.tp_name == 0)
1935 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936}
1937
Georg Brandl2ee470f2008-07-16 12:55:28 +00001938int
1939PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 PyFloatObject *p;
1942 PyFloatBlock *list, *next;
1943 int i;
1944 int u; /* remaining unfreed floats per block */
1945 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 list = block_list;
1948 block_list = NULL;
1949 free_list = NULL;
1950 while (list != NULL) {
1951 u = 0;
1952 for (i = 0, p = &list->objects[0];
1953 i < N_FLOATOBJECTS;
1954 i++, p++) {
1955 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1956 u++;
1957 }
1958 next = list->next;
1959 if (u) {
1960 list->next = block_list;
1961 block_list = list;
1962 for (i = 0, p = &list->objects[0];
1963 i < N_FLOATOBJECTS;
1964 i++, p++) {
1965 if (!PyFloat_CheckExact(p) ||
1966 Py_REFCNT(p) == 0) {
1967 Py_TYPE(p) = (struct _typeobject *)
1968 free_list;
1969 free_list = p;
1970 }
1971 }
1972 }
1973 else {
1974 PyMem_FREE(list);
1975 }
1976 freelist_size += u;
1977 list = next;
1978 }
1979 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001980}
1981
1982void
1983PyFloat_Fini(void)
1984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 PyFloatObject *p;
1986 PyFloatBlock *list;
1987 int i;
1988 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if (!Py_VerboseFlag)
1993 return;
1994 fprintf(stderr, "# cleanup floats");
1995 if (!u) {
1996 fprintf(stderr, "\n");
1997 }
1998 else {
1999 fprintf(stderr,
2000 ": %d unfreed float%s\n",
2001 u, u == 1 ? "" : "s");
2002 }
2003 if (Py_VerboseFlag > 1) {
2004 list = block_list;
2005 while (list != NULL) {
2006 for (i = 0, p = &list->objects[0];
2007 i < N_FLOATOBJECTS;
2008 i++, p++) {
2009 if (PyFloat_CheckExact(p) &&
2010 Py_REFCNT(p) != 0) {
2011 char *buf = PyOS_double_to_string(
2012 PyFloat_AS_DOUBLE(p), 'r',
2013 0, 0, NULL);
2014 if (buf) {
2015 /* XXX(twouters) cast
2016 refcount to long
2017 until %zd is
2018 universally
2019 available
2020 */
2021 fprintf(stderr,
2022 "# <float at %p, refcnt=%ld, val=%s>\n",
2023 p, (long)Py_REFCNT(p), buf);
2024 PyMem_Free(buf);
2025 }
2026 }
2027 }
2028 list = list->next;
2029 }
2030 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002031}
Tim Peters9905b942003-03-20 20:53:32 +00002032
2033/*----------------------------------------------------------------------------
2034 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002035 */
2036int
2037_PyFloat_Pack4(double x, unsigned char *p, int le)
2038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (float_format == unknown_format) {
2040 unsigned char sign;
2041 int e;
2042 double f;
2043 unsigned int fbits;
2044 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (le) {
2047 p += 3;
2048 incr = -1;
2049 }
Tim Peters9905b942003-03-20 20:53:32 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (x < 0) {
2052 sign = 1;
2053 x = -x;
2054 }
2055 else
2056 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* Normalize f to be in the range [1.0, 2.0) */
2061 if (0.5 <= f && f < 1.0) {
2062 f *= 2.0;
2063 e--;
2064 }
2065 else if (f == 0.0)
2066 e = 0;
2067 else {
2068 PyErr_SetString(PyExc_SystemError,
2069 "frexp() result out of range");
2070 return -1;
2071 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (e >= 128)
2074 goto Overflow;
2075 else if (e < -126) {
2076 /* Gradual underflow */
2077 f = ldexp(f, 126 + e);
2078 e = 0;
2079 }
2080 else if (!(e == 0 && f == 0.0)) {
2081 e += 127;
2082 f -= 1.0; /* Get rid of leading 1 */
2083 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 f *= 8388608.0; /* 2**23 */
2086 fbits = (unsigned int)(f + 0.5); /* Round */
2087 assert(fbits <= 8388608);
2088 if (fbits >> 23) {
2089 /* The carry propagated out of a string of 23 1 bits. */
2090 fbits = 0;
2091 ++e;
2092 if (e >= 255)
2093 goto Overflow;
2094 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 /* First byte */
2097 *p = (sign << 7) | (e >> 1);
2098 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* Second byte */
2101 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2102 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 /* Third byte */
2105 *p = (fbits >> 8) & 0xFF;
2106 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 /* Fourth byte */
2109 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 /* Done */
2112 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
2115 else {
2116 float y = (float)x;
2117 const char *s = (char*)&y;
2118 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2121 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 if ((float_format == ieee_little_endian_format && !le)
2124 || (float_format == ieee_big_endian_format && le)) {
2125 p += 3;
2126 incr = -1;
2127 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 for (i = 0; i < 4; i++) {
2130 *p = *s++;
2131 p += incr;
2132 }
2133 return 0;
2134 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002135 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyErr_SetString(PyExc_OverflowError,
2137 "float too large to pack with f format");
2138 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002139}
2140
2141int
2142_PyFloat_Pack8(double x, unsigned char *p, int le)
2143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (double_format == unknown_format) {
2145 unsigned char sign;
2146 int e;
2147 double f;
2148 unsigned int fhi, flo;
2149 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (le) {
2152 p += 7;
2153 incr = -1;
2154 }
Tim Peters9905b942003-03-20 20:53:32 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (x < 0) {
2157 sign = 1;
2158 x = -x;
2159 }
2160 else
2161 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* Normalize f to be in the range [1.0, 2.0) */
2166 if (0.5 <= f && f < 1.0) {
2167 f *= 2.0;
2168 e--;
2169 }
2170 else if (f == 0.0)
2171 e = 0;
2172 else {
2173 PyErr_SetString(PyExc_SystemError,
2174 "frexp() result out of range");
2175 return -1;
2176 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (e >= 1024)
2179 goto Overflow;
2180 else if (e < -1022) {
2181 /* Gradual underflow */
2182 f = ldexp(f, 1022 + e);
2183 e = 0;
2184 }
2185 else if (!(e == 0 && f == 0.0)) {
2186 e += 1023;
2187 f -= 1.0; /* Get rid of leading 1 */
2188 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2191 f *= 268435456.0; /* 2**28 */
2192 fhi = (unsigned int)f; /* Truncate */
2193 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 f -= (double)fhi;
2196 f *= 16777216.0; /* 2**24 */
2197 flo = (unsigned int)(f + 0.5); /* Round */
2198 assert(flo <= 16777216);
2199 if (flo >> 24) {
2200 /* The carry propagated out of a string of 24 1 bits. */
2201 flo = 0;
2202 ++fhi;
2203 if (fhi >> 28) {
2204 /* And it also progagated out of the next 28 bits. */
2205 fhi = 0;
2206 ++e;
2207 if (e >= 2047)
2208 goto Overflow;
2209 }
2210 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* First byte */
2213 *p = (sign << 7) | (e >> 4);
2214 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* Second byte */
2217 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2218 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Third byte */
2221 *p = (fhi >> 16) & 0xFF;
2222 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Fourth byte */
2225 *p = (fhi >> 8) & 0xFF;
2226 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Fifth byte */
2229 *p = fhi & 0xFF;
2230 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* Sixth byte */
2233 *p = (flo >> 16) & 0xFF;
2234 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Seventh byte */
2237 *p = (flo >> 8) & 0xFF;
2238 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Eighth byte */
2241 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002242 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Done */
2245 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 Overflow:
2248 PyErr_SetString(PyExc_OverflowError,
2249 "float too large to pack with d format");
2250 return -1;
2251 }
2252 else {
2253 const char *s = (char*)&x;
2254 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 if ((double_format == ieee_little_endian_format && !le)
2257 || (double_format == ieee_big_endian_format && le)) {
2258 p += 7;
2259 incr = -1;
2260 }
2261
2262 for (i = 0; i < 8; i++) {
2263 *p = *s++;
2264 p += incr;
2265 }
2266 return 0;
2267 }
Tim Peters9905b942003-03-20 20:53:32 +00002268}
2269
2270double
2271_PyFloat_Unpack4(const unsigned char *p, int le)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (float_format == unknown_format) {
2274 unsigned char sign;
2275 int e;
2276 unsigned int f;
2277 double x;
2278 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 if (le) {
2281 p += 3;
2282 incr = -1;
2283 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* First byte */
2286 sign = (*p >> 7) & 1;
2287 e = (*p & 0x7F) << 1;
2288 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 /* Second byte */
2291 e |= (*p >> 7) & 1;
2292 f = (*p & 0x7F) << 16;
2293 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (e == 255) {
2296 PyErr_SetString(
2297 PyExc_ValueError,
2298 "can't unpack IEEE 754 special value "
2299 "on non-IEEE platform");
2300 return -1;
2301 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* Third byte */
2304 f |= *p << 8;
2305 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Fourth byte */
2308 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* XXX This sadly ignores Inf/NaN issues */
2313 if (e == 0)
2314 e = -126;
2315 else {
2316 x += 1.0;
2317 e -= 127;
2318 }
2319 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 if (sign)
2322 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 return x;
2325 }
2326 else {
2327 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 if ((float_format == ieee_little_endian_format && !le)
2330 || (float_format == ieee_big_endian_format && le)) {
2331 char buf[4];
2332 char *d = &buf[3];
2333 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 for (i = 0; i < 4; i++) {
2336 *d-- = *p++;
2337 }
2338 memcpy(&x, buf, 4);
2339 }
2340 else {
2341 memcpy(&x, p, 4);
2342 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 return x;
2345 }
Tim Peters9905b942003-03-20 20:53:32 +00002346}
2347
2348double
2349_PyFloat_Unpack8(const unsigned char *p, int le)
2350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (double_format == unknown_format) {
2352 unsigned char sign;
2353 int e;
2354 unsigned int fhi, flo;
2355 double x;
2356 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 if (le) {
2359 p += 7;
2360 incr = -1;
2361 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* First byte */
2364 sign = (*p >> 7) & 1;
2365 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* Second byte */
2370 e |= (*p >> 4) & 0xF;
2371 fhi = (*p & 0xF) << 24;
2372 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 if (e == 2047) {
2375 PyErr_SetString(
2376 PyExc_ValueError,
2377 "can't unpack IEEE 754 special value "
2378 "on non-IEEE platform");
2379 return -1.0;
2380 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* Third byte */
2383 fhi |= *p << 16;
2384 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* Fourth byte */
2387 fhi |= *p << 8;
2388 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* Fifth byte */
2391 fhi |= *p;
2392 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* Sixth byte */
2395 flo = *p << 16;
2396 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 /* Seventh byte */
2399 flo |= *p << 8;
2400 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Eighth byte */
2403 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2406 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (e == 0)
2409 e = -1022;
2410 else {
2411 x += 1.0;
2412 e -= 1023;
2413 }
2414 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (sign)
2417 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 return x;
2420 }
2421 else {
2422 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 if ((double_format == ieee_little_endian_format && !le)
2425 || (double_format == ieee_big_endian_format && le)) {
2426 char buf[8];
2427 char *d = &buf[7];
2428 int i;
2429
2430 for (i = 0; i < 8; i++) {
2431 *d-- = *p++;
2432 }
2433 memcpy(&x, buf, 8);
2434 }
2435 else {
2436 memcpy(&x, p, 8);
2437 }
2438
2439 return x;
2440 }
Tim Peters9905b942003-03-20 20:53:32 +00002441}