blob: a7382497908445b731b6c8d65ee009b45463b87a [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)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200177 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000179 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200180 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000181 if (s == NULL) {
182 Py_DECREF(s_buffer);
183 return NULL;
184 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 }
186 else if (PyObject_AsCharBuffer(v, &s, &len)) {
187 PyErr_SetString(PyExc_TypeError,
188 "float() argument must be a string or a number");
189 return NULL;
190 }
191 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000192 /* strip space */
193 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000195 while (s < last - 1 && Py_ISSPACE(last[-1]))
196 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* We don't care about overflow or underflow. If the platform
198 * supports them, infinities and signed zeroes (on underflow) are
199 * fine. */
200 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000201 if (end != last) {
202 PyErr_Format(PyExc_ValueError,
203 "could not convert string to float: "
204 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 result = NULL;
206 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000207 else if (x == -1.0 && PyErr_Occurred())
208 result = NULL;
209 else
210 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000211
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000212 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214}
215
Guido van Rossum234f9421993-06-17 12:35:49 +0000216static void
Fred Drakefd99de62000-07-09 05:02:18 +0000217float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (PyFloat_CheckExact(op)) {
220 Py_TYPE(op) = (struct _typeobject *)free_list;
221 free_list = op;
222 }
223 else
224 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000225}
226
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227double
Fred Drakefd99de62000-07-09 05:02:18 +0000228PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyNumberMethods *nb;
231 PyFloatObject *fo;
232 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (op && PyFloat_Check(op))
235 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (op == NULL) {
238 PyErr_BadArgument();
239 return -1;
240 }
Tim Petersd2364e82001-11-01 20:09:42 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
243 PyErr_SetString(PyExc_TypeError, "a float is required");
244 return -1;
245 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 fo = (PyFloatObject*) (*nb->nb_float) (op);
248 if (fo == NULL)
249 return -1;
250 if (!PyFloat_Check(fo)) {
251 PyErr_SetString(PyExc_TypeError,
252 "nb_float should return float object");
253 return -1;
254 }
Tim Petersd2364e82001-11-01 20:09:42 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 val = PyFloat_AS_DOUBLE(fo);
257 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Neil Schemenauer32117e52001-01-04 01:44:34 +0000262/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000263 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000264 set to NULL, and the function invoking this macro returns NULL. If
265 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
266 stored in obj, and returned from the function invoking this macro.
267*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268#define CONVERT_TO_DOUBLE(obj, dbl) \
269 if (PyFloat_Check(obj)) \
270 dbl = PyFloat_AS_DOUBLE(obj); \
271 else if (convert_to_double(&(obj), &(dbl)) < 0) \
272 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000273
Eric Smith0923d1d2009-04-16 20:16:10 +0000274/* Methods */
275
Neil Schemenauer32117e52001-01-04 01:44:34 +0000276static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000277convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (PyLong_Check(obj)) {
282 *dbl = PyLong_AsDouble(obj);
283 if (*dbl == -1.0 && PyErr_Occurred()) {
284 *v = NULL;
285 return -1;
286 }
287 }
288 else {
289 Py_INCREF(Py_NotImplemented);
290 *v = Py_NotImplemented;
291 return -1;
292 }
293 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000294}
295
Eric Smith0923d1d2009-04-16 20:16:10 +0000296static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000297float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000298{
299 PyObject *result;
300 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000301 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000302 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000303 NULL);
304 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000305 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000306 result = PyUnicode_FromString(buf);
307 PyMem_Free(buf);
308 return result;
309}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000310
Tim Peters307fa782004-09-23 08:06:40 +0000311/* Comparison is pretty much a nightmare. When comparing float to float,
312 * we do it as straightforwardly (and long-windedly) as conceivable, so
313 * that, e.g., Python x == y delivers the same result as the platform
314 * C x == y when x and/or y is a NaN.
315 * When mixing float with an integer type, there's no good *uniform* approach.
316 * Converting the double to an integer obviously doesn't work, since we
317 * may lose info from fractional bits. Converting the integer to a double
318 * also has two failure modes: (1) a long int may trigger overflow (too
319 * large to fit in the dynamic range of a C double); (2) even a C long may have
320 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
321 * 63 bits of precision, but a C double probably has only 53), and then
322 * we can falsely claim equality when low-order integer bits are lost by
323 * coercion to double. So this part is painful too.
324 */
325
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000326static PyObject*
327float_richcompare(PyObject *v, PyObject *w, int op)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 double i, j;
330 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 assert(PyFloat_Check(v));
333 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* Switch on the type of w. Set i and j to doubles to be compared,
336 * and op to the richcomp to use.
337 */
338 if (PyFloat_Check(w))
339 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 else if (!Py_IS_FINITE(i)) {
342 if (PyLong_Check(w))
343 /* If i is an infinity, its magnitude exceeds any
344 * finite integer, so it doesn't matter which int we
345 * compare i with. If i is a NaN, similarly.
346 */
347 j = 0.0;
348 else
349 goto Unimplemented;
350 }
Tim Peters307fa782004-09-23 08:06:40 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 else if (PyLong_Check(w)) {
353 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
354 int wsign = _PyLong_Sign(w);
355 size_t nbits;
356 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (vsign != wsign) {
359 /* Magnitudes are irrelevant -- the signs alone
360 * determine the outcome.
361 */
362 i = (double)vsign;
363 j = (double)wsign;
364 goto Compare;
365 }
366 /* The signs are the same. */
367 /* Convert w to a double if it fits. In particular, 0 fits. */
368 nbits = _PyLong_NumBits(w);
369 if (nbits == (size_t)-1 && PyErr_Occurred()) {
370 /* This long is so large that size_t isn't big enough
371 * to hold the # of bits. Replace with little doubles
372 * that give the same outcome -- w is so large that
373 * its magnitude must exceed the magnitude of any
374 * finite float.
375 */
376 PyErr_Clear();
377 i = (double)vsign;
378 assert(wsign != 0);
379 j = wsign * 2.0;
380 goto Compare;
381 }
382 if (nbits <= 48) {
383 j = PyLong_AsDouble(w);
384 /* It's impossible that <= 48 bits overflowed. */
385 assert(j != -1.0 || ! PyErr_Occurred());
386 goto Compare;
387 }
388 assert(wsign != 0); /* else nbits was 0 */
389 assert(vsign != 0); /* if vsign were 0, then since wsign is
390 * not 0, we would have taken the
391 * vsign != wsign branch at the start */
392 /* We want to work with non-negative numbers. */
393 if (vsign < 0) {
394 /* "Multiply both sides" by -1; this also swaps the
395 * comparator.
396 */
397 i = -i;
398 op = _Py_SwappedOp[op];
399 }
400 assert(i > 0.0);
401 (void) frexp(i, &exponent);
402 /* exponent is the # of bits in v before the radix point;
403 * we know that nbits (the # of bits in w) > 48 at this point
404 */
405 if (exponent < 0 || (size_t)exponent < nbits) {
406 i = 1.0;
407 j = 2.0;
408 goto Compare;
409 }
410 if ((size_t)exponent > nbits) {
411 i = 2.0;
412 j = 1.0;
413 goto Compare;
414 }
415 /* v and w have the same number of bits before the radix
416 * point. Construct two longs that have the same comparison
417 * outcome.
418 */
419 {
420 double fracpart;
421 double intpart;
422 PyObject *result = NULL;
423 PyObject *one = NULL;
424 PyObject *vv = NULL;
425 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (wsign < 0) {
428 ww = PyNumber_Negative(w);
429 if (ww == NULL)
430 goto Error;
431 }
432 else
433 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 fracpart = modf(i, &intpart);
436 vv = PyLong_FromDouble(intpart);
437 if (vv == NULL)
438 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (fracpart != 0.0) {
441 /* Shift left, and or a 1 bit into vv
442 * to represent the lost fraction.
443 */
444 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 one = PyLong_FromLong(1);
447 if (one == NULL)
448 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 temp = PyNumber_Lshift(ww, one);
451 if (temp == NULL)
452 goto Error;
453 Py_DECREF(ww);
454 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 temp = PyNumber_Lshift(vv, one);
457 if (temp == NULL)
458 goto Error;
459 Py_DECREF(vv);
460 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 temp = PyNumber_Or(vv, one);
463 if (temp == NULL)
464 goto Error;
465 Py_DECREF(vv);
466 vv = temp;
467 }
Tim Peters307fa782004-09-23 08:06:40 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 r = PyObject_RichCompareBool(vv, ww, op);
470 if (r < 0)
471 goto Error;
472 result = PyBool_FromLong(r);
473 Error:
474 Py_XDECREF(vv);
475 Py_XDECREF(ww);
476 Py_XDECREF(one);
477 return result;
478 }
479 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 else /* w isn't float, int, or long */
482 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000483
484 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 PyFPE_START_PROTECT("richcompare", return NULL)
486 switch (op) {
487 case Py_EQ:
488 r = i == j;
489 break;
490 case Py_NE:
491 r = i != j;
492 break;
493 case Py_LE:
494 r = i <= j;
495 break;
496 case Py_GE:
497 r = i >= j;
498 break;
499 case Py_LT:
500 r = i < j;
501 break;
502 case Py_GT:
503 r = i > j;
504 break;
505 }
506 PyFPE_END_PROTECT(r)
507 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000508
509 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500510 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000511}
512
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000513static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000514float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000517}
518
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000520float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 double a,b;
523 CONVERT_TO_DOUBLE(v, a);
524 CONVERT_TO_DOUBLE(w, b);
525 PyFPE_START_PROTECT("add", return 0)
526 a = a + b;
527 PyFPE_END_PROTECT(a)
528 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000529}
530
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000531static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000532float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 double a,b;
535 CONVERT_TO_DOUBLE(v, a);
536 CONVERT_TO_DOUBLE(w, b);
537 PyFPE_START_PROTECT("subtract", return 0)
538 a = a - b;
539 PyFPE_END_PROTECT(a)
540 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541}
542
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000544float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 double a,b;
547 CONVERT_TO_DOUBLE(v, a);
548 CONVERT_TO_DOUBLE(w, b);
549 PyFPE_START_PROTECT("multiply", return 0)
550 a = a * b;
551 PyFPE_END_PROTECT(a)
552 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000556float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 double a,b;
559 CONVERT_TO_DOUBLE(v, a);
560 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (b == 0.0) {
562 PyErr_SetString(PyExc_ZeroDivisionError,
563 "float division by zero");
564 return NULL;
565 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 PyFPE_START_PROTECT("divide", return 0)
567 a = a / b;
568 PyFPE_END_PROTECT(a)
569 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double vx, wx;
576 double mod;
577 CONVERT_TO_DOUBLE(v, vx);
578 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (wx == 0.0) {
580 PyErr_SetString(PyExc_ZeroDivisionError,
581 "float modulo");
582 return NULL;
583 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyFPE_START_PROTECT("modulo", return 0)
585 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000586 if (mod) {
587 /* ensure the remainder has the same sign as the denominator */
588 if ((wx < 0) != (mod < 0)) {
589 mod += wx;
590 }
591 }
592 else {
593 /* the remainder is zero, and in the presence of signed zeroes
594 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000595 it has the same sign as the denominator. */
596 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
598 PyFPE_END_PROTECT(mod)
599 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000600}
601
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000602static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000603float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 double vx, wx;
606 double div, mod, floordiv;
607 CONVERT_TO_DOUBLE(v, vx);
608 CONVERT_TO_DOUBLE(w, wx);
609 if (wx == 0.0) {
610 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
611 return NULL;
612 }
613 PyFPE_START_PROTECT("divmod", return 0)
614 mod = fmod(vx, wx);
615 /* fmod is typically exact, so vx-mod is *mathematically* an
616 exact multiple of wx. But this is fp arithmetic, and fp
617 vx - mod is an approximation; the result is that div may
618 not be an exact integral value after the division, although
619 it will always be very close to one.
620 */
621 div = (vx - mod) / wx;
622 if (mod) {
623 /* ensure the remainder has the same sign as the denominator */
624 if ((wx < 0) != (mod < 0)) {
625 mod += wx;
626 div -= 1.0;
627 }
628 }
629 else {
630 /* the remainder is zero, and in the presence of signed zeroes
631 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000632 it has the same sign as the denominator. */
633 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
635 /* snap quotient to nearest integral value */
636 if (div) {
637 floordiv = floor(div);
638 if (div - floordiv > 0.5)
639 floordiv += 1.0;
640 }
641 else {
642 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000643 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
645 PyFPE_END_PROTECT(floordiv)
646 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000650float_floor_div(PyObject *v, PyObject *w)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 t = float_divmod(v, w);
655 if (t == NULL || t == Py_NotImplemented)
656 return t;
657 assert(PyTuple_CheckExact(t));
658 r = PyTuple_GET_ITEM(t, 0);
659 Py_INCREF(r);
660 Py_DECREF(t);
661 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000662}
663
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000664/* determine whether x is an odd integer or not; assumes that
665 x is not an infinity or nan. */
666#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
667
Tim Peters63a35712001-12-11 19:57:24 +0000668static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000669float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 double iv, iw, ix;
672 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if ((PyObject *)z != Py_None) {
675 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
676 "allowed unless all arguments are integers");
677 return NULL;
678 }
Tim Peters32f453e2001-09-03 08:35:41 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 CONVERT_TO_DOUBLE(v, iv);
681 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* Sort out special cases here instead of relying on pow() */
684 if (iw == 0) { /* v**0 is 1, even 0**0 */
685 return PyFloat_FromDouble(1.0);
686 }
687 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
688 return PyFloat_FromDouble(iv);
689 }
690 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
691 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
692 }
693 if (Py_IS_INFINITY(iw)) {
694 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
695 * abs(v) > 1 (including case where v infinite)
696 *
697 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
698 * abs(v) > 1 (including case where v infinite)
699 */
700 iv = fabs(iv);
701 if (iv == 1.0)
702 return PyFloat_FromDouble(1.0);
703 else if ((iw > 0.0) == (iv > 1.0))
704 return PyFloat_FromDouble(fabs(iw)); /* return inf */
705 else
706 return PyFloat_FromDouble(0.0);
707 }
708 if (Py_IS_INFINITY(iv)) {
709 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
710 * both cases, we need to add the appropriate sign if w is
711 * an odd integer.
712 */
713 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
714 if (iw > 0.0)
715 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
716 else
717 return PyFloat_FromDouble(iw_is_odd ?
718 copysign(0.0, iv) : 0.0);
719 }
720 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
721 (already dealt with above), and an error
722 if w is negative. */
723 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
724 if (iw < 0.0) {
725 PyErr_SetString(PyExc_ZeroDivisionError,
726 "0.0 cannot be raised to a "
727 "negative power");
728 return NULL;
729 }
730 /* use correct sign if iw is odd */
731 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
732 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (iv < 0.0) {
735 /* Whether this is an error is a mess, and bumps into libm
736 * bugs so we have to figure it out ourselves.
737 */
738 if (iw != floor(iw)) {
739 /* Negative numbers raised to fractional powers
740 * become complex.
741 */
742 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
743 }
744 /* iw is an exact integer, albeit perhaps a very large
745 * one. Replace iv by its absolute value and remember
746 * to negate the pow result if iw is odd.
747 */
748 iv = -iv;
749 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
750 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
753 /* (-1) ** large_integer also ends up here. Here's an
754 * extract from the comments for the previous
755 * implementation explaining why this special case is
756 * necessary:
757 *
758 * -1 raised to an exact integer should never be exceptional.
759 * Alas, some libms (chiefly glibc as of early 2003) return
760 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
761 * happen to be representable in a *C* integer. That's a
762 * bug.
763 */
764 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
765 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 /* Now iv and iw are finite, iw is nonzero, and iv is
768 * positive and not equal to 1.0. We finally allow
769 * the platform pow to step in and do the rest.
770 */
771 errno = 0;
772 PyFPE_START_PROTECT("pow", return NULL)
773 ix = pow(iv, iw);
774 PyFPE_END_PROTECT(ix)
775 Py_ADJUST_ERANGE1(ix);
776 if (negate_result)
777 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (errno != 0) {
780 /* We don't expect any errno value other than ERANGE, but
781 * the range of libm bugs appears unbounded.
782 */
783 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
784 PyExc_ValueError);
785 return NULL;
786 }
787 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000788}
789
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000790#undef DOUBLE_IS_ODD_INTEGER
791
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000792static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000793float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000796}
797
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000798static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000799float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802}
803
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000804static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000805float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000808}
809
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000810static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000811float_is_integer(PyObject *v)
812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 double x = PyFloat_AsDouble(v);
814 PyObject *o;
815
816 if (x == -1.0 && PyErr_Occurred())
817 return NULL;
818 if (!Py_IS_FINITE(x))
819 Py_RETURN_FALSE;
820 errno = 0;
821 PyFPE_START_PROTECT("is_integer", return NULL)
822 o = (floor(x) == x) ? Py_True : Py_False;
823 PyFPE_END_PROTECT(x)
824 if (errno != 0) {
825 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
826 PyExc_ValueError);
827 return NULL;
828 }
829 Py_INCREF(o);
830 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000831}
832
833#if 0
834static PyObject *
835float_is_inf(PyObject *v)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 double x = PyFloat_AsDouble(v);
838 if (x == -1.0 && PyErr_Occurred())
839 return NULL;
840 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000841}
842
843static PyObject *
844float_is_nan(PyObject *v)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 double x = PyFloat_AsDouble(v);
847 if (x == -1.0 && PyErr_Occurred())
848 return NULL;
849 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000850}
851
852static PyObject *
853float_is_finite(PyObject *v)
854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 double x = PyFloat_AsDouble(v);
856 if (x == -1.0 && PyErr_Occurred())
857 return NULL;
858 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000859}
860#endif
861
862static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000863float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 double x = PyFloat_AsDouble(v);
866 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 (void)modf(x, &wholepart);
869 /* Try to get out cheap if this fits in a Python int. The attempt
870 * to cast to long must be protected, as C doesn't define what
871 * happens if the double is too big to fit in a long. Some rare
872 * systems raise an exception then (RISCOS was mentioned as one,
873 * and someone using a non-default option on Sun also bumped into
874 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
875 * still be vulnerable: if a long has more bits of precision than
876 * a double, casting MIN/MAX to double may yield an approximation,
877 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
878 * yield true from the C expression wholepart<=LONG_MAX, despite
879 * that wholepart is actually greater than LONG_MAX.
880 */
881 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
882 const long aslong = (long)wholepart;
883 return PyLong_FromLong(aslong);
884 }
885 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000886}
887
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000888/* double_round: rounds a finite double to the closest multiple of
889 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
890 ndigits <= 323). Returns a Python float, or sets a Python error and
891 returns NULL on failure (OverflowError and memory errors are possible). */
892
893#ifndef PY_NO_SHORT_FLOAT_REPR
894/* version of double_round that uses the correctly-rounded string<->double
895 conversions from Python/dtoa.c */
896
897static PyObject *
898double_round(double x, int ndigits) {
899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 double rounded;
901 Py_ssize_t buflen, mybuflen=100;
902 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
903 int decpt, sign;
904 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000905 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000908 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000910 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (buf == NULL) {
912 PyErr_NoMemory();
913 return NULL;
914 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
917 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
918 buflen = buf_end - buf;
919 if (buflen + 8 > mybuflen) {
920 mybuflen = buflen+8;
921 mybuf = (char *)PyMem_Malloc(mybuflen);
922 if (mybuf == NULL) {
923 PyErr_NoMemory();
924 goto exit;
925 }
926 }
927 /* copy buf to mybuf, adding exponent, sign and leading 0 */
928 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
929 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* and convert the resulting string back to a double */
932 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000933 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000935 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (errno == ERANGE && fabs(rounded) >= 1.)
937 PyErr_SetString(PyExc_OverflowError,
938 "rounded value too large to represent");
939 else
940 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* done computing value; now clean up */
943 if (mybuf != shortbuf)
944 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000945 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 _Py_dg_freedtoa(buf);
947 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000948}
949
950#else /* PY_NO_SHORT_FLOAT_REPR */
951
952/* fallback version, to be used when correctly rounded binary<->decimal
953 conversions aren't available */
954
955static PyObject *
956double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 double pow1, pow2, y, z;
958 if (ndigits >= 0) {
959 if (ndigits > 22) {
960 /* pow1 and pow2 are each safe from overflow, but
961 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
962 pow1 = pow(10.0, (double)(ndigits-22));
963 pow2 = 1e22;
964 }
965 else {
966 pow1 = pow(10.0, (double)ndigits);
967 pow2 = 1.0;
968 }
969 y = (x*pow1)*pow2;
970 /* if y overflows, then rounded value is exactly x */
971 if (!Py_IS_FINITE(y))
972 return PyFloat_FromDouble(x);
973 }
974 else {
975 pow1 = pow(10.0, (double)-ndigits);
976 pow2 = 1.0; /* unused; silences a gcc compiler warning */
977 y = x / pow1;
978 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 z = round(y);
981 if (fabs(y-z) == 0.5)
982 /* halfway between two integers; use round-half-even */
983 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (ndigits >= 0)
986 z = (z / pow2) / pow1;
987 else
988 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* if computation resulted in overflow, raise OverflowError */
991 if (!Py_IS_FINITE(z)) {
992 PyErr_SetString(PyExc_OverflowError,
993 "overflow occurred during round");
994 return NULL;
995 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000998}
999
1000#endif /* PY_NO_SHORT_FLOAT_REPR */
1001
1002/* round a Python float v to the closest multiple of 10**-ndigits */
1003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001004static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001005float_round(PyObject *v, PyObject *args)
1006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 double x, rounded;
1008 PyObject *o_ndigits = NULL;
1009 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 x = PyFloat_AsDouble(v);
1012 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1013 return NULL;
1014 if (o_ndigits == NULL) {
1015 /* single-argument round: round to nearest integer */
1016 rounded = round(x);
1017 if (fabs(x-rounded) == 0.5)
1018 /* halfway case: round to even */
1019 rounded = 2.0*round(x/2.0);
1020 return PyLong_FromDouble(rounded);
1021 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* interpret second argument as a Py_ssize_t; clips on overflow */
1024 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1025 if (ndigits == -1 && PyErr_Occurred())
1026 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* nans and infinities round to themselves */
1029 if (!Py_IS_FINITE(x))
1030 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1033 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1034 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001035#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1036#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (ndigits > NDIGITS_MAX)
1038 /* return x */
1039 return PyFloat_FromDouble(x);
1040 else if (ndigits < NDIGITS_MIN)
1041 /* return 0.0, but with sign of x */
1042 return PyFloat_FromDouble(0.0*x);
1043 else
1044 /* finite x, and ndigits is not unreasonably large */
1045 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001046#undef NDIGITS_MAX
1047#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001048}
1049
1050static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001051float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 if (PyFloat_CheckExact(v))
1054 Py_INCREF(v);
1055 else
1056 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1057 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001058}
1059
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001060/* turn ASCII hex characters into integer values and vice versa */
1061
1062static char
1063char_from_hex(int x)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001066 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001067}
1068
1069static int
1070hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 int x;
1072 switch(c) {
1073 case '0':
1074 x = 0;
1075 break;
1076 case '1':
1077 x = 1;
1078 break;
1079 case '2':
1080 x = 2;
1081 break;
1082 case '3':
1083 x = 3;
1084 break;
1085 case '4':
1086 x = 4;
1087 break;
1088 case '5':
1089 x = 5;
1090 break;
1091 case '6':
1092 x = 6;
1093 break;
1094 case '7':
1095 x = 7;
1096 break;
1097 case '8':
1098 x = 8;
1099 break;
1100 case '9':
1101 x = 9;
1102 break;
1103 case 'a':
1104 case 'A':
1105 x = 10;
1106 break;
1107 case 'b':
1108 case 'B':
1109 x = 11;
1110 break;
1111 case 'c':
1112 case 'C':
1113 x = 12;
1114 break;
1115 case 'd':
1116 case 'D':
1117 x = 13;
1118 break;
1119 case 'e':
1120 case 'E':
1121 x = 14;
1122 break;
1123 case 'f':
1124 case 'F':
1125 x = 15;
1126 break;
1127 default:
1128 x = -1;
1129 break;
1130 }
1131 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001132}
1133
1134/* convert a float to a hexadecimal string */
1135
1136/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1137 of the form 4k+1. */
1138#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1139
1140static PyObject *
1141float_hex(PyObject *v)
1142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 double x, m;
1144 int e, shift, i, si, esign;
1145 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1146 trailing NUL byte. */
1147 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001152 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001155 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 return PyUnicode_FromString("-0x0.0p+0");
1157 else
1158 return PyUnicode_FromString("0x0.0p+0");
1159 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 m = frexp(fabs(x), &e);
1162 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1163 m = ldexp(m, shift);
1164 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 si = 0;
1167 s[si] = char_from_hex((int)m);
1168 si++;
1169 m -= (int)m;
1170 s[si] = '.';
1171 si++;
1172 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1173 m *= 16.0;
1174 s[si] = char_from_hex((int)m);
1175 si++;
1176 m -= (int)m;
1177 }
1178 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (e < 0) {
1181 esign = (int)'-';
1182 e = -e;
1183 }
1184 else
1185 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (x < 0.0)
1188 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1189 else
1190 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001191}
1192
1193PyDoc_STRVAR(float_hex_doc,
1194"float.hex() -> string\n\
1195\n\
1196Return a hexadecimal representation of a floating-point number.\n\
1197>>> (-0.1).hex()\n\
1198'-0x1.999999999999ap-4'\n\
1199>>> 3.14159.hex()\n\
1200'0x1.921f9f01b866ep+1'");
1201
1202/* Convert a hexadecimal string to a float. */
1203
1204static PyObject *
1205float_fromhex(PyObject *cls, PyObject *arg)
1206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 PyObject *result_as_float, *result;
1208 double x;
1209 long exp, top_exp, lsb, key_digit;
1210 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1211 int half_eps, digit, round_up, negate=0;
1212 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /*
1215 * For the sake of simplicity and correctness, we impose an artificial
1216 * limit on ndigits, the total number of hex digits in the coefficient
1217 * The limit is chosen to ensure that, writing exp for the exponent,
1218 *
1219 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1220 * guaranteed to overflow (provided it's nonzero)
1221 *
1222 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1223 * guaranteed to underflow to 0.
1224 *
1225 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1226 * overflow in the calculation of exp and top_exp below.
1227 *
1228 * More specifically, ndigits is assumed to satisfy the following
1229 * inequalities:
1230 *
1231 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1232 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1233 *
1234 * If either of these inequalities is not satisfied, a ValueError is
1235 * raised. Otherwise, write x for the value of the hex string, and
1236 * assume x is nonzero. Then
1237 *
1238 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1239 *
1240 * Now if exp > LONG_MAX/2 then:
1241 *
1242 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1243 * = DBL_MAX_EXP
1244 *
1245 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1246 * double, so overflows. If exp < LONG_MIN/2, then
1247 *
1248 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1249 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1250 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1251 *
1252 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1253 * when converted to a C double.
1254 *
1255 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1256 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1257 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 s = _PyUnicode_AsStringAndSize(arg, &length);
1260 if (s == NULL)
1261 return NULL;
1262 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 /********************
1265 * Parse the string *
1266 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* leading whitespace */
1269 while (Py_ISSPACE(*s))
1270 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* infinities and nans */
1273 x = _Py_parse_inf_or_nan(s, &coeff_end);
1274 if (coeff_end != s) {
1275 s = coeff_end;
1276 goto finished;
1277 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* optional sign */
1280 if (*s == '-') {
1281 s++;
1282 negate = 1;
1283 }
1284 else if (*s == '+')
1285 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* [0x] */
1288 s_store = s;
1289 if (*s == '0') {
1290 s++;
1291 if (*s == 'x' || *s == 'X')
1292 s++;
1293 else
1294 s = s_store;
1295 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* coefficient: <integer> [. <fraction>] */
1298 coeff_start = s;
1299 while (hex_from_char(*s) >= 0)
1300 s++;
1301 s_store = s;
1302 if (*s == '.') {
1303 s++;
1304 while (hex_from_char(*s) >= 0)
1305 s++;
1306 coeff_end = s-1;
1307 }
1308 else
1309 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 /* ndigits = total # of hex digits; fdigits = # after point */
1312 ndigits = coeff_end - coeff_start;
1313 fdigits = coeff_end - s_store;
1314 if (ndigits == 0)
1315 goto parse_error;
1316 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1317 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1318 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* [p <exponent>] */
1321 if (*s == 'p' || *s == 'P') {
1322 s++;
1323 exp_start = s;
1324 if (*s == '-' || *s == '+')
1325 s++;
1326 if (!('0' <= *s && *s <= '9'))
1327 goto parse_error;
1328 s++;
1329 while ('0' <= *s && *s <= '9')
1330 s++;
1331 exp = strtol(exp_start, NULL, 10);
1332 }
1333 else
1334 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001336/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1338 coeff_end-(j) : \
1339 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /*******************************************
1342 * Compute rounded value of the hex string *
1343 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 /* Discard leading zeros, and catch extreme overflow and underflow */
1346 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1347 ndigits--;
1348 if (ndigits == 0 || exp < LONG_MIN/2) {
1349 x = 0.0;
1350 goto finished;
1351 }
1352 if (exp > LONG_MAX/2)
1353 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* Adjust exponent for fractional part. */
1356 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1359 top_exp = exp + 4*((long)ndigits - 1);
1360 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1361 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* catch almost all nonextreme cases of overflow and underflow here */
1364 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1365 x = 0.0;
1366 goto finished;
1367 }
1368 if (top_exp > DBL_MAX_EXP)
1369 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* lsb = exponent of least significant bit of the *rounded* value.
1372 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1373 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 x = 0.0;
1376 if (exp >= lsb) {
1377 /* no rounding required */
1378 for (i = ndigits-1; i >= 0; i--)
1379 x = 16.0*x + HEX_DIGIT(i);
1380 x = ldexp(x, (int)(exp));
1381 goto finished;
1382 }
1383 /* rounding required. key_digit is the index of the hex digit
1384 containing the first bit to be rounded away. */
1385 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1386 key_digit = (lsb - exp - 1) / 4;
1387 for (i = ndigits-1; i > key_digit; i--)
1388 x = 16.0*x + HEX_DIGIT(i);
1389 digit = HEX_DIGIT(key_digit);
1390 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1393 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1394 if ((digit & half_eps) != 0) {
1395 round_up = 0;
1396 if ((digit & (3*half_eps-1)) != 0 ||
1397 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1398 round_up = 1;
1399 else
1400 for (i = key_digit-1; i >= 0; i--)
1401 if (HEX_DIGIT(i) != 0) {
1402 round_up = 1;
1403 break;
1404 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001405 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 x += 2*half_eps;
1407 if (top_exp == DBL_MAX_EXP &&
1408 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1409 /* overflow corner case: pre-rounded value <
1410 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1411 goto overflow_error;
1412 }
1413 }
1414 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001415
1416 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* optional trailing whitespace leading to the end of the string */
1418 while (Py_ISSPACE(*s))
1419 s++;
1420 if (s != s_end)
1421 goto parse_error;
1422 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1423 if (result_as_float == NULL)
1424 return NULL;
1425 result = PyObject_CallObject(cls, result_as_float);
1426 Py_DECREF(result_as_float);
1427 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001428
1429 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyErr_SetString(PyExc_OverflowError,
1431 "hexadecimal value too large to represent as a float");
1432 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001433
1434 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyErr_SetString(PyExc_ValueError,
1436 "invalid hexadecimal floating-point string");
1437 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001438
1439 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 PyErr_SetString(PyExc_ValueError,
1441 "hexadecimal string too long to convert");
1442 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443}
1444
1445PyDoc_STRVAR(float_fromhex_doc,
1446"float.fromhex(string) -> float\n\
1447\n\
1448Create a floating-point number from a hexadecimal string.\n\
1449>>> float.fromhex('0x1.ffffp10')\n\
14502047.984375\n\
1451>>> float.fromhex('-0x1p-1074')\n\
1452-4.9406564584124654e-324");
1453
1454
Christian Heimes26855632008-01-27 23:50:43 +00001455static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001456float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 double self;
1459 double float_part;
1460 int exponent;
1461 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PyObject *prev;
1464 PyObject *py_exponent = NULL;
1465 PyObject *numerator = NULL;
1466 PyObject *denominator = NULL;
1467 PyObject *result_pair = NULL;
1468 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001469
1470#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 prev = obj; \
1472 obj = call; \
1473 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (Py_IS_INFINITY(self)) {
1478 PyErr_SetString(PyExc_OverflowError,
1479 "Cannot pass infinity to float.as_integer_ratio.");
1480 return NULL;
1481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (Py_IS_NAN(self)) {
1483 PyErr_SetString(PyExc_ValueError,
1484 "Cannot pass NaN to float.as_integer_ratio.");
1485 return NULL;
1486 }
Christian Heimes26855632008-01-27 23:50:43 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1489 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1490 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1493 float_part *= 2.0;
1494 exponent--;
1495 }
1496 /* self == float_part * 2**exponent exactly and float_part is integral.
1497 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1498 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 numerator = PyLong_FromDouble(float_part);
1501 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 /* fold in 2**exponent */
1504 denominator = PyLong_FromLong(1);
1505 py_exponent = PyLong_FromLong(labs((long)exponent));
1506 if (py_exponent == NULL) goto error;
1507 INPLACE_UPDATE(py_exponent,
1508 long_methods->nb_lshift(denominator, py_exponent));
1509 if (py_exponent == NULL) goto error;
1510 if (exponent > 0) {
1511 INPLACE_UPDATE(numerator,
1512 long_methods->nb_multiply(numerator, py_exponent));
1513 if (numerator == NULL) goto error;
1514 }
1515 else {
1516 Py_DECREF(denominator);
1517 denominator = py_exponent;
1518 py_exponent = NULL;
1519 }
1520
1521 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001522
1523#undef INPLACE_UPDATE
1524error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 Py_XDECREF(py_exponent);
1526 Py_XDECREF(denominator);
1527 Py_XDECREF(numerator);
1528 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001529}
1530
1531PyDoc_STRVAR(float_as_integer_ratio_doc,
1532"float.as_integer_ratio() -> (int, int)\n"
1533"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001534"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1535"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001536"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001537"\n"
1538">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001539"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001540">>> (0.0).as_integer_ratio()\n"
1541"(0, 1)\n"
1542">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001543"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001544
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001545
Jeremy Hylton938ace62002-07-17 16:30:39 +00001546static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001547float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1548
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549static PyObject *
1550float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyObject *x = Py_False; /* Integer zero */
1553 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (type != &PyFloat_Type)
1556 return float_subtype_new(type, args, kwds); /* Wimp out */
1557 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1558 return NULL;
1559 /* If it's a string, but not a string subclass, use
1560 PyFloat_FromString. */
1561 if (PyUnicode_CheckExact(x))
1562 return PyFloat_FromString(x);
1563 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564}
1565
Guido van Rossumbef14172001-08-29 15:47:46 +00001566/* Wimpy, slow approach to tp_new calls for subtypes of float:
1567 first create a regular float from whatever arguments we got,
1568 then allocate a subtype instance and initialize its ob_fval
1569 from the regular float. The regular float is then thrown away.
1570*/
1571static PyObject *
1572float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 assert(PyType_IsSubtype(type, &PyFloat_Type));
1577 tmp = float_new(&PyFloat_Type, args, kwds);
1578 if (tmp == NULL)
1579 return NULL;
1580 assert(PyFloat_CheckExact(tmp));
1581 newobj = type->tp_alloc(type, 0);
1582 if (newobj == NULL) {
1583 Py_DECREF(tmp);
1584 return NULL;
1585 }
1586 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1587 Py_DECREF(tmp);
1588 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001589}
1590
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001591static PyObject *
1592float_getnewargs(PyFloatObject *v)
1593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001595}
1596
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597/* this is for the benefit of the pack/unpack routines below */
1598
1599typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001601} float_format_type;
1602
1603static float_format_type double_format, float_format;
1604static float_format_type detected_double_format, detected_float_format;
1605
1606static PyObject *
1607float_getformat(PyTypeObject *v, PyObject* arg)
1608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 char* s;
1610 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (!PyUnicode_Check(arg)) {
1613 PyErr_Format(PyExc_TypeError,
1614 "__getformat__() argument must be string, not %.500s",
1615 Py_TYPE(arg)->tp_name);
1616 return NULL;
1617 }
1618 s = _PyUnicode_AsString(arg);
1619 if (s == NULL)
1620 return NULL;
1621 if (strcmp(s, "double") == 0) {
1622 r = double_format;
1623 }
1624 else if (strcmp(s, "float") == 0) {
1625 r = float_format;
1626 }
1627 else {
1628 PyErr_SetString(PyExc_ValueError,
1629 "__getformat__() argument 1 must be "
1630 "'double' or 'float'");
1631 return NULL;
1632 }
1633
1634 switch (r) {
1635 case unknown_format:
1636 return PyUnicode_FromString("unknown");
1637 case ieee_little_endian_format:
1638 return PyUnicode_FromString("IEEE, little-endian");
1639 case ieee_big_endian_format:
1640 return PyUnicode_FromString("IEEE, big-endian");
1641 default:
1642 Py_FatalError("insane float_format or double_format");
1643 return NULL;
1644 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001645}
1646
1647PyDoc_STRVAR(float_getformat_doc,
1648"float.__getformat__(typestr) -> string\n"
1649"\n"
1650"You probably don't want to use this function. It exists mainly to be\n"
1651"used in Python's test suite.\n"
1652"\n"
1653"typestr must be 'double' or 'float'. This function returns whichever of\n"
1654"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1655"format of floating point numbers used by the C type named by typestr.");
1656
1657static PyObject *
1658float_setformat(PyTypeObject *v, PyObject* args)
1659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 char* typestr;
1661 char* format;
1662 float_format_type f;
1663 float_format_type detected;
1664 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1667 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (strcmp(typestr, "double") == 0) {
1670 p = &double_format;
1671 detected = detected_double_format;
1672 }
1673 else if (strcmp(typestr, "float") == 0) {
1674 p = &float_format;
1675 detected = detected_float_format;
1676 }
1677 else {
1678 PyErr_SetString(PyExc_ValueError,
1679 "__setformat__() argument 1 must "
1680 "be 'double' or 'float'");
1681 return NULL;
1682 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (strcmp(format, "unknown") == 0) {
1685 f = unknown_format;
1686 }
1687 else if (strcmp(format, "IEEE, little-endian") == 0) {
1688 f = ieee_little_endian_format;
1689 }
1690 else if (strcmp(format, "IEEE, big-endian") == 0) {
1691 f = ieee_big_endian_format;
1692 }
1693 else {
1694 PyErr_SetString(PyExc_ValueError,
1695 "__setformat__() argument 2 must be "
1696 "'unknown', 'IEEE, little-endian' or "
1697 "'IEEE, big-endian'");
1698 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (f != unknown_format && f != detected) {
1703 PyErr_Format(PyExc_ValueError,
1704 "can only set %s format to 'unknown' or the "
1705 "detected platform value", typestr);
1706 return NULL;
1707 }
1708
1709 *p = f;
1710 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711}
1712
1713PyDoc_STRVAR(float_setformat_doc,
1714"float.__setformat__(typestr, fmt) -> None\n"
1715"\n"
1716"You probably don't want to use this function. It exists mainly to be\n"
1717"used in Python's test suite.\n"
1718"\n"
1719"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1720"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1721"one of the latter two if it appears to match the underlying C reality.\n"
1722"\n"
1723"Overrides the automatic determination of C-level floating point type.\n"
1724"This affects how floats are converted to and from binary strings.");
1725
Guido van Rossumb43daf72007-08-01 18:08:08 +00001726static PyObject *
1727float_getzero(PyObject *v, void *closure)
1728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001730}
1731
Eric Smith8c663262007-08-25 02:26:07 +00001732static PyObject *
1733float__format__(PyObject *self, PyObject *args)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1738 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 return _PyFloat_FormatAdvanced(self, format_spec, 0,
1740 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001741}
1742
1743PyDoc_STRVAR(float__format__doc,
1744"float.__format__(format_spec) -> string\n"
1745"\n"
1746"Formats the float according to format_spec.");
1747
1748
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001749static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1751 "Returns self, the complex conjugate of any float."},
1752 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1753 "Returns the Integral closest to x between 0 and x."},
1754 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1755 "Returns the Integral closest to x, rounding half toward even.\n"
1756 "When an argument is passed, works like built-in round(x, ndigits)."},
1757 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1758 float_as_integer_ratio_doc},
1759 {"fromhex", (PyCFunction)float_fromhex,
1760 METH_O|METH_CLASS, float_fromhex_doc},
1761 {"hex", (PyCFunction)float_hex,
1762 METH_NOARGS, float_hex_doc},
1763 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1764 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001765#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1767 "Returns True if the float is positive or negative infinite."},
1768 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1769 "Returns True if the float is finite, neither infinite nor NaN."},
1770 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1771 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001772#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1774 {"__getformat__", (PyCFunction)float_getformat,
1775 METH_O|METH_CLASS, float_getformat_doc},
1776 {"__setformat__", (PyCFunction)float_setformat,
1777 METH_VARARGS|METH_CLASS, float_setformat_doc},
1778 {"__format__", (PyCFunction)float__format__,
1779 METH_VARARGS, float__format__doc},
1780 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001781};
1782
Guido van Rossumb43daf72007-08-01 18:08:08 +00001783static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001785 (getter)float_float, (setter)NULL,
1786 "the real part of a complex number",
1787 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001789 (getter)float_getzero, (setter)NULL,
1790 "the imaginary part of a complex number",
1791 NULL},
1792 {NULL} /* Sentinel */
1793};
1794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001795PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796"float(x) -> floating point number\n\
1797\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001798Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799
1800
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001801static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 float_add, /*nb_add*/
1803 float_sub, /*nb_subtract*/
1804 float_mul, /*nb_multiply*/
1805 float_rem, /*nb_remainder*/
1806 float_divmod, /*nb_divmod*/
1807 float_pow, /*nb_power*/
1808 (unaryfunc)float_neg, /*nb_negative*/
1809 (unaryfunc)float_float, /*nb_positive*/
1810 (unaryfunc)float_abs, /*nb_absolute*/
1811 (inquiry)float_bool, /*nb_bool*/
1812 0, /*nb_invert*/
1813 0, /*nb_lshift*/
1814 0, /*nb_rshift*/
1815 0, /*nb_and*/
1816 0, /*nb_xor*/
1817 0, /*nb_or*/
1818 float_trunc, /*nb_int*/
1819 0, /*nb_reserved*/
1820 float_float, /*nb_float*/
1821 0, /* nb_inplace_add */
1822 0, /* nb_inplace_subtract */
1823 0, /* nb_inplace_multiply */
1824 0, /* nb_inplace_remainder */
1825 0, /* nb_inplace_power */
1826 0, /* nb_inplace_lshift */
1827 0, /* nb_inplace_rshift */
1828 0, /* nb_inplace_and */
1829 0, /* nb_inplace_xor */
1830 0, /* nb_inplace_or */
1831 float_floor_div, /* nb_floor_divide */
1832 float_div, /* nb_true_divide */
1833 0, /* nb_inplace_floor_divide */
1834 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001835};
1836
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001837PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1839 "float",
1840 sizeof(PyFloatObject),
1841 0,
1842 (destructor)float_dealloc, /* tp_dealloc */
1843 0, /* tp_print */
1844 0, /* tp_getattr */
1845 0, /* tp_setattr */
1846 0, /* tp_reserved */
1847 (reprfunc)float_repr, /* tp_repr */
1848 &float_as_number, /* tp_as_number */
1849 0, /* tp_as_sequence */
1850 0, /* tp_as_mapping */
1851 (hashfunc)float_hash, /* tp_hash */
1852 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001853 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyObject_GenericGetAttr, /* tp_getattro */
1855 0, /* tp_setattro */
1856 0, /* tp_as_buffer */
1857 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1858 float_doc, /* tp_doc */
1859 0, /* tp_traverse */
1860 0, /* tp_clear */
1861 float_richcompare, /* tp_richcompare */
1862 0, /* tp_weaklistoffset */
1863 0, /* tp_iter */
1864 0, /* tp_iternext */
1865 float_methods, /* tp_methods */
1866 0, /* tp_members */
1867 float_getset, /* tp_getset */
1868 0, /* tp_base */
1869 0, /* tp_dict */
1870 0, /* tp_descr_get */
1871 0, /* tp_descr_set */
1872 0, /* tp_dictoffset */
1873 0, /* tp_init */
1874 0, /* tp_alloc */
1875 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001876};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001877
1878void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001879_PyFloat_Init(void)
1880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* We attempt to determine if this machine is using IEEE
1882 floating point formats by peering at the bits of some
1883 carefully chosen values. If it looks like we are on an
1884 IEEE platform, the float packing/unpacking routines can
1885 just copy bits, if not they resort to arithmetic & shifts
1886 and masks. The shifts & masks approach works on all finite
1887 values, but what happens to infinities, NaNs and signed
1888 zeroes on packing is an accident, and attempting to unpack
1889 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 Note that if we're on some whacked-out platform which uses
1892 IEEE formats but isn't strictly little-endian or big-
1893 endian, we will fall back to the portable shifts & masks
1894 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001895
1896#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 {
1898 double x = 9006104071832581.0;
1899 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1900 detected_double_format = ieee_big_endian_format;
1901 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1902 detected_double_format = ieee_little_endian_format;
1903 else
1904 detected_double_format = unknown_format;
1905 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908#endif
1909
1910#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 {
1912 float y = 16711938.0;
1913 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1914 detected_float_format = ieee_big_endian_format;
1915 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1916 detected_float_format = ieee_little_endian_format;
1917 else
1918 detected_float_format = unknown_format;
1919 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001920#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001922#endif
1923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 double_format = detected_double_format;
1925 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 /* Init float info */
1928 if (FloatInfoType.tp_name == 0)
1929 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930}
1931
Georg Brandl2ee470f2008-07-16 12:55:28 +00001932int
1933PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyFloatObject *p;
1936 PyFloatBlock *list, *next;
1937 int i;
1938 int u; /* remaining unfreed floats per block */
1939 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 list = block_list;
1942 block_list = NULL;
1943 free_list = NULL;
1944 while (list != NULL) {
1945 u = 0;
1946 for (i = 0, p = &list->objects[0];
1947 i < N_FLOATOBJECTS;
1948 i++, p++) {
1949 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1950 u++;
1951 }
1952 next = list->next;
1953 if (u) {
1954 list->next = block_list;
1955 block_list = list;
1956 for (i = 0, p = &list->objects[0];
1957 i < N_FLOATOBJECTS;
1958 i++, p++) {
1959 if (!PyFloat_CheckExact(p) ||
1960 Py_REFCNT(p) == 0) {
1961 Py_TYPE(p) = (struct _typeobject *)
1962 free_list;
1963 free_list = p;
1964 }
1965 }
1966 }
1967 else {
1968 PyMem_FREE(list);
1969 }
1970 freelist_size += u;
1971 list = next;
1972 }
1973 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001974}
1975
1976void
1977PyFloat_Fini(void)
1978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 PyFloatObject *p;
1980 PyFloatBlock *list;
1981 int i;
1982 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (!Py_VerboseFlag)
1987 return;
1988 fprintf(stderr, "# cleanup floats");
1989 if (!u) {
1990 fprintf(stderr, "\n");
1991 }
1992 else {
1993 fprintf(stderr,
1994 ": %d unfreed float%s\n",
1995 u, u == 1 ? "" : "s");
1996 }
1997 if (Py_VerboseFlag > 1) {
1998 list = block_list;
1999 while (list != NULL) {
2000 for (i = 0, p = &list->objects[0];
2001 i < N_FLOATOBJECTS;
2002 i++, p++) {
2003 if (PyFloat_CheckExact(p) &&
2004 Py_REFCNT(p) != 0) {
2005 char *buf = PyOS_double_to_string(
2006 PyFloat_AS_DOUBLE(p), 'r',
2007 0, 0, NULL);
2008 if (buf) {
2009 /* XXX(twouters) cast
2010 refcount to long
2011 until %zd is
2012 universally
2013 available
2014 */
2015 fprintf(stderr,
2016 "# <float at %p, refcnt=%ld, val=%s>\n",
2017 p, (long)Py_REFCNT(p), buf);
2018 PyMem_Free(buf);
2019 }
2020 }
2021 }
2022 list = list->next;
2023 }
2024 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002025}
Tim Peters9905b942003-03-20 20:53:32 +00002026
2027/*----------------------------------------------------------------------------
2028 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002029 */
2030int
2031_PyFloat_Pack4(double x, unsigned char *p, int le)
2032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (float_format == unknown_format) {
2034 unsigned char sign;
2035 int e;
2036 double f;
2037 unsigned int fbits;
2038 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (le) {
2041 p += 3;
2042 incr = -1;
2043 }
Tim Peters9905b942003-03-20 20:53:32 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 if (x < 0) {
2046 sign = 1;
2047 x = -x;
2048 }
2049 else
2050 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* Normalize f to be in the range [1.0, 2.0) */
2055 if (0.5 <= f && f < 1.0) {
2056 f *= 2.0;
2057 e--;
2058 }
2059 else if (f == 0.0)
2060 e = 0;
2061 else {
2062 PyErr_SetString(PyExc_SystemError,
2063 "frexp() result out of range");
2064 return -1;
2065 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (e >= 128)
2068 goto Overflow;
2069 else if (e < -126) {
2070 /* Gradual underflow */
2071 f = ldexp(f, 126 + e);
2072 e = 0;
2073 }
2074 else if (!(e == 0 && f == 0.0)) {
2075 e += 127;
2076 f -= 1.0; /* Get rid of leading 1 */
2077 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 f *= 8388608.0; /* 2**23 */
2080 fbits = (unsigned int)(f + 0.5); /* Round */
2081 assert(fbits <= 8388608);
2082 if (fbits >> 23) {
2083 /* The carry propagated out of a string of 23 1 bits. */
2084 fbits = 0;
2085 ++e;
2086 if (e >= 255)
2087 goto Overflow;
2088 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 /* First byte */
2091 *p = (sign << 7) | (e >> 1);
2092 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* Second byte */
2095 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2096 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* Third byte */
2099 *p = (fbits >> 8) & 0xFF;
2100 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* Fourth byte */
2103 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 /* Done */
2106 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 }
2109 else {
2110 float y = (float)x;
2111 const char *s = (char*)&y;
2112 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2115 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if ((float_format == ieee_little_endian_format && !le)
2118 || (float_format == ieee_big_endian_format && le)) {
2119 p += 3;
2120 incr = -1;
2121 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 for (i = 0; i < 4; i++) {
2124 *p = *s++;
2125 p += incr;
2126 }
2127 return 0;
2128 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002129 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyErr_SetString(PyExc_OverflowError,
2131 "float too large to pack with f format");
2132 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002133}
2134
2135int
2136_PyFloat_Pack8(double x, unsigned char *p, int le)
2137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (double_format == unknown_format) {
2139 unsigned char sign;
2140 int e;
2141 double f;
2142 unsigned int fhi, flo;
2143 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (le) {
2146 p += 7;
2147 incr = -1;
2148 }
Tim Peters9905b942003-03-20 20:53:32 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (x < 0) {
2151 sign = 1;
2152 x = -x;
2153 }
2154 else
2155 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 /* Normalize f to be in the range [1.0, 2.0) */
2160 if (0.5 <= f && f < 1.0) {
2161 f *= 2.0;
2162 e--;
2163 }
2164 else if (f == 0.0)
2165 e = 0;
2166 else {
2167 PyErr_SetString(PyExc_SystemError,
2168 "frexp() result out of range");
2169 return -1;
2170 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (e >= 1024)
2173 goto Overflow;
2174 else if (e < -1022) {
2175 /* Gradual underflow */
2176 f = ldexp(f, 1022 + e);
2177 e = 0;
2178 }
2179 else if (!(e == 0 && f == 0.0)) {
2180 e += 1023;
2181 f -= 1.0; /* Get rid of leading 1 */
2182 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2185 f *= 268435456.0; /* 2**28 */
2186 fhi = (unsigned int)f; /* Truncate */
2187 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 f -= (double)fhi;
2190 f *= 16777216.0; /* 2**24 */
2191 flo = (unsigned int)(f + 0.5); /* Round */
2192 assert(flo <= 16777216);
2193 if (flo >> 24) {
2194 /* The carry propagated out of a string of 24 1 bits. */
2195 flo = 0;
2196 ++fhi;
2197 if (fhi >> 28) {
2198 /* And it also progagated out of the next 28 bits. */
2199 fhi = 0;
2200 ++e;
2201 if (e >= 2047)
2202 goto Overflow;
2203 }
2204 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* First byte */
2207 *p = (sign << 7) | (e >> 4);
2208 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* Second byte */
2211 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2212 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* Third byte */
2215 *p = (fhi >> 16) & 0xFF;
2216 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Fourth byte */
2219 *p = (fhi >> 8) & 0xFF;
2220 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Fifth byte */
2223 *p = fhi & 0xFF;
2224 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Sixth byte */
2227 *p = (flo >> 16) & 0xFF;
2228 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Seventh byte */
2231 *p = (flo >> 8) & 0xFF;
2232 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Eighth byte */
2235 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002236 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Done */
2239 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 Overflow:
2242 PyErr_SetString(PyExc_OverflowError,
2243 "float too large to pack with d format");
2244 return -1;
2245 }
2246 else {
2247 const char *s = (char*)&x;
2248 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 if ((double_format == ieee_little_endian_format && !le)
2251 || (double_format == ieee_big_endian_format && le)) {
2252 p += 7;
2253 incr = -1;
2254 }
2255
2256 for (i = 0; i < 8; i++) {
2257 *p = *s++;
2258 p += incr;
2259 }
2260 return 0;
2261 }
Tim Peters9905b942003-03-20 20:53:32 +00002262}
2263
2264double
2265_PyFloat_Unpack4(const unsigned char *p, int le)
2266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 if (float_format == unknown_format) {
2268 unsigned char sign;
2269 int e;
2270 unsigned int f;
2271 double x;
2272 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (le) {
2275 p += 3;
2276 incr = -1;
2277 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* First byte */
2280 sign = (*p >> 7) & 1;
2281 e = (*p & 0x7F) << 1;
2282 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Second byte */
2285 e |= (*p >> 7) & 1;
2286 f = (*p & 0x7F) << 16;
2287 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 if (e == 255) {
2290 PyErr_SetString(
2291 PyExc_ValueError,
2292 "can't unpack IEEE 754 special value "
2293 "on non-IEEE platform");
2294 return -1;
2295 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Third byte */
2298 f |= *p << 8;
2299 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Fourth byte */
2302 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* XXX This sadly ignores Inf/NaN issues */
2307 if (e == 0)
2308 e = -126;
2309 else {
2310 x += 1.0;
2311 e -= 127;
2312 }
2313 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (sign)
2316 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return x;
2319 }
2320 else {
2321 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if ((float_format == ieee_little_endian_format && !le)
2324 || (float_format == ieee_big_endian_format && le)) {
2325 char buf[4];
2326 char *d = &buf[3];
2327 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 for (i = 0; i < 4; i++) {
2330 *d-- = *p++;
2331 }
2332 memcpy(&x, buf, 4);
2333 }
2334 else {
2335 memcpy(&x, p, 4);
2336 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 return x;
2339 }
Tim Peters9905b942003-03-20 20:53:32 +00002340}
2341
2342double
2343_PyFloat_Unpack8(const unsigned char *p, int le)
2344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 if (double_format == unknown_format) {
2346 unsigned char sign;
2347 int e;
2348 unsigned int fhi, flo;
2349 double x;
2350 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (le) {
2353 p += 7;
2354 incr = -1;
2355 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* First byte */
2358 sign = (*p >> 7) & 1;
2359 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Second byte */
2364 e |= (*p >> 4) & 0xF;
2365 fhi = (*p & 0xF) << 24;
2366 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (e == 2047) {
2369 PyErr_SetString(
2370 PyExc_ValueError,
2371 "can't unpack IEEE 754 special value "
2372 "on non-IEEE platform");
2373 return -1.0;
2374 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* Third byte */
2377 fhi |= *p << 16;
2378 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* Fourth byte */
2381 fhi |= *p << 8;
2382 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* Fifth byte */
2385 fhi |= *p;
2386 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* Sixth byte */
2389 flo = *p << 16;
2390 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Seventh byte */
2393 flo |= *p << 8;
2394 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* Eighth byte */
2397 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2400 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 if (e == 0)
2403 e = -1022;
2404 else {
2405 x += 1.0;
2406 e -= 1023;
2407 }
2408 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (sign)
2411 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return x;
2414 }
2415 else {
2416 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if ((double_format == ieee_little_endian_format && !le)
2419 || (double_format == ieee_big_endian_format && le)) {
2420 char buf[8];
2421 char *d = &buf[7];
2422 int i;
2423
2424 for (i = 0; i < 8; i++) {
2425 *d-- = *p++;
2426 }
2427 memcpy(&x, buf, 8);
2428 }
2429 else {
2430 memcpy(&x, p, 8);
2431 }
2432
2433 return x;
2434 }
Tim Peters9905b942003-03-20 20:53:32 +00002435}