blob: 1c8a6a32a38f30c9143a80b415c76f08060a50a5 [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 Dickinsone6a076d2009-04-18 11:48:33 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* round to a decimal string */
907 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
908 if (buf == NULL) {
909 PyErr_NoMemory();
910 return NULL;
911 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
914 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
915 buflen = buf_end - buf;
916 if (buflen + 8 > mybuflen) {
917 mybuflen = buflen+8;
918 mybuf = (char *)PyMem_Malloc(mybuflen);
919 if (mybuf == NULL) {
920 PyErr_NoMemory();
921 goto exit;
922 }
923 }
924 /* copy buf to mybuf, adding exponent, sign and leading 0 */
925 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
926 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* and convert the resulting string back to a double */
929 errno = 0;
930 rounded = _Py_dg_strtod(mybuf, NULL);
931 if (errno == ERANGE && fabs(rounded) >= 1.)
932 PyErr_SetString(PyExc_OverflowError,
933 "rounded value too large to represent");
934 else
935 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* done computing value; now clean up */
938 if (mybuf != shortbuf)
939 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000940 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 _Py_dg_freedtoa(buf);
942 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000943}
944
945#else /* PY_NO_SHORT_FLOAT_REPR */
946
947/* fallback version, to be used when correctly rounded binary<->decimal
948 conversions aren't available */
949
950static PyObject *
951double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 double pow1, pow2, y, z;
953 if (ndigits >= 0) {
954 if (ndigits > 22) {
955 /* pow1 and pow2 are each safe from overflow, but
956 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
957 pow1 = pow(10.0, (double)(ndigits-22));
958 pow2 = 1e22;
959 }
960 else {
961 pow1 = pow(10.0, (double)ndigits);
962 pow2 = 1.0;
963 }
964 y = (x*pow1)*pow2;
965 /* if y overflows, then rounded value is exactly x */
966 if (!Py_IS_FINITE(y))
967 return PyFloat_FromDouble(x);
968 }
969 else {
970 pow1 = pow(10.0, (double)-ndigits);
971 pow2 = 1.0; /* unused; silences a gcc compiler warning */
972 y = x / pow1;
973 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 z = round(y);
976 if (fabs(y-z) == 0.5)
977 /* halfway between two integers; use round-half-even */
978 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (ndigits >= 0)
981 z = (z / pow2) / pow1;
982 else
983 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* if computation resulted in overflow, raise OverflowError */
986 if (!Py_IS_FINITE(z)) {
987 PyErr_SetString(PyExc_OverflowError,
988 "overflow occurred during round");
989 return NULL;
990 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000993}
994
995#endif /* PY_NO_SHORT_FLOAT_REPR */
996
997/* round a Python float v to the closest multiple of 10**-ndigits */
998
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000999static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000float_round(PyObject *v, PyObject *args)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 double x, rounded;
1003 PyObject *o_ndigits = NULL;
1004 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 x = PyFloat_AsDouble(v);
1007 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1008 return NULL;
1009 if (o_ndigits == NULL) {
1010 /* single-argument round: round to nearest integer */
1011 rounded = round(x);
1012 if (fabs(x-rounded) == 0.5)
1013 /* halfway case: round to even */
1014 rounded = 2.0*round(x/2.0);
1015 return PyLong_FromDouble(rounded);
1016 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* interpret second argument as a Py_ssize_t; clips on overflow */
1019 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1020 if (ndigits == -1 && PyErr_Occurred())
1021 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* nans and infinities round to themselves */
1024 if (!Py_IS_FINITE(x))
1025 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1028 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1029 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001030#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1031#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (ndigits > NDIGITS_MAX)
1033 /* return x */
1034 return PyFloat_FromDouble(x);
1035 else if (ndigits < NDIGITS_MIN)
1036 /* return 0.0, but with sign of x */
1037 return PyFloat_FromDouble(0.0*x);
1038 else
1039 /* finite x, and ndigits is not unreasonably large */
1040 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001041#undef NDIGITS_MAX
1042#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001043}
1044
1045static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001046float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (PyFloat_CheckExact(v))
1049 Py_INCREF(v);
1050 else
1051 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1052 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001053}
1054
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001055/* turn ASCII hex characters into integer values and vice versa */
1056
1057static char
1058char_from_hex(int x)
1059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 assert(0 <= x && x < 16);
1061 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001062}
1063
1064static int
1065hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 int x;
1067 switch(c) {
1068 case '0':
1069 x = 0;
1070 break;
1071 case '1':
1072 x = 1;
1073 break;
1074 case '2':
1075 x = 2;
1076 break;
1077 case '3':
1078 x = 3;
1079 break;
1080 case '4':
1081 x = 4;
1082 break;
1083 case '5':
1084 x = 5;
1085 break;
1086 case '6':
1087 x = 6;
1088 break;
1089 case '7':
1090 x = 7;
1091 break;
1092 case '8':
1093 x = 8;
1094 break;
1095 case '9':
1096 x = 9;
1097 break;
1098 case 'a':
1099 case 'A':
1100 x = 10;
1101 break;
1102 case 'b':
1103 case 'B':
1104 x = 11;
1105 break;
1106 case 'c':
1107 case 'C':
1108 x = 12;
1109 break;
1110 case 'd':
1111 case 'D':
1112 x = 13;
1113 break;
1114 case 'e':
1115 case 'E':
1116 x = 14;
1117 break;
1118 case 'f':
1119 case 'F':
1120 x = 15;
1121 break;
1122 default:
1123 x = -1;
1124 break;
1125 }
1126 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001127}
1128
1129/* convert a float to a hexadecimal string */
1130
1131/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1132 of the form 4k+1. */
1133#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1134
1135static PyObject *
1136float_hex(PyObject *v)
1137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 double x, m;
1139 int e, shift, i, si, esign;
1140 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1141 trailing NUL byte. */
1142 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001147 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001150 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return PyUnicode_FromString("-0x0.0p+0");
1152 else
1153 return PyUnicode_FromString("0x0.0p+0");
1154 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 m = frexp(fabs(x), &e);
1157 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1158 m = ldexp(m, shift);
1159 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 si = 0;
1162 s[si] = char_from_hex((int)m);
1163 si++;
1164 m -= (int)m;
1165 s[si] = '.';
1166 si++;
1167 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1168 m *= 16.0;
1169 s[si] = char_from_hex((int)m);
1170 si++;
1171 m -= (int)m;
1172 }
1173 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (e < 0) {
1176 esign = (int)'-';
1177 e = -e;
1178 }
1179 else
1180 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (x < 0.0)
1183 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1184 else
1185 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001186}
1187
1188PyDoc_STRVAR(float_hex_doc,
1189"float.hex() -> string\n\
1190\n\
1191Return a hexadecimal representation of a floating-point number.\n\
1192>>> (-0.1).hex()\n\
1193'-0x1.999999999999ap-4'\n\
1194>>> 3.14159.hex()\n\
1195'0x1.921f9f01b866ep+1'");
1196
1197/* Convert a hexadecimal string to a float. */
1198
1199static PyObject *
1200float_fromhex(PyObject *cls, PyObject *arg)
1201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyObject *result_as_float, *result;
1203 double x;
1204 long exp, top_exp, lsb, key_digit;
1205 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1206 int half_eps, digit, round_up, negate=0;
1207 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 /*
1210 * For the sake of simplicity and correctness, we impose an artificial
1211 * limit on ndigits, the total number of hex digits in the coefficient
1212 * The limit is chosen to ensure that, writing exp for the exponent,
1213 *
1214 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1215 * guaranteed to overflow (provided it's nonzero)
1216 *
1217 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1218 * guaranteed to underflow to 0.
1219 *
1220 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1221 * overflow in the calculation of exp and top_exp below.
1222 *
1223 * More specifically, ndigits is assumed to satisfy the following
1224 * inequalities:
1225 *
1226 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1227 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1228 *
1229 * If either of these inequalities is not satisfied, a ValueError is
1230 * raised. Otherwise, write x for the value of the hex string, and
1231 * assume x is nonzero. Then
1232 *
1233 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1234 *
1235 * Now if exp > LONG_MAX/2 then:
1236 *
1237 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1238 * = DBL_MAX_EXP
1239 *
1240 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1241 * double, so overflows. If exp < LONG_MIN/2, then
1242 *
1243 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1244 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1245 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1246 *
1247 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1248 * when converted to a C double.
1249 *
1250 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1251 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1252 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 s = _PyUnicode_AsStringAndSize(arg, &length);
1255 if (s == NULL)
1256 return NULL;
1257 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /********************
1260 * Parse the string *
1261 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* leading whitespace */
1264 while (Py_ISSPACE(*s))
1265 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* infinities and nans */
1268 x = _Py_parse_inf_or_nan(s, &coeff_end);
1269 if (coeff_end != s) {
1270 s = coeff_end;
1271 goto finished;
1272 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 /* optional sign */
1275 if (*s == '-') {
1276 s++;
1277 negate = 1;
1278 }
1279 else if (*s == '+')
1280 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 /* [0x] */
1283 s_store = s;
1284 if (*s == '0') {
1285 s++;
1286 if (*s == 'x' || *s == 'X')
1287 s++;
1288 else
1289 s = s_store;
1290 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* coefficient: <integer> [. <fraction>] */
1293 coeff_start = s;
1294 while (hex_from_char(*s) >= 0)
1295 s++;
1296 s_store = s;
1297 if (*s == '.') {
1298 s++;
1299 while (hex_from_char(*s) >= 0)
1300 s++;
1301 coeff_end = s-1;
1302 }
1303 else
1304 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 /* ndigits = total # of hex digits; fdigits = # after point */
1307 ndigits = coeff_end - coeff_start;
1308 fdigits = coeff_end - s_store;
1309 if (ndigits == 0)
1310 goto parse_error;
1311 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1312 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1313 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /* [p <exponent>] */
1316 if (*s == 'p' || *s == 'P') {
1317 s++;
1318 exp_start = s;
1319 if (*s == '-' || *s == '+')
1320 s++;
1321 if (!('0' <= *s && *s <= '9'))
1322 goto parse_error;
1323 s++;
1324 while ('0' <= *s && *s <= '9')
1325 s++;
1326 exp = strtol(exp_start, NULL, 10);
1327 }
1328 else
1329 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1333 coeff_end-(j) : \
1334 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /*******************************************
1337 * Compute rounded value of the hex string *
1338 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* Discard leading zeros, and catch extreme overflow and underflow */
1341 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1342 ndigits--;
1343 if (ndigits == 0 || exp < LONG_MIN/2) {
1344 x = 0.0;
1345 goto finished;
1346 }
1347 if (exp > LONG_MAX/2)
1348 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* Adjust exponent for fractional part. */
1351 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1354 top_exp = exp + 4*((long)ndigits - 1);
1355 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1356 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* catch almost all nonextreme cases of overflow and underflow here */
1359 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1360 x = 0.0;
1361 goto finished;
1362 }
1363 if (top_exp > DBL_MAX_EXP)
1364 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* lsb = exponent of least significant bit of the *rounded* value.
1367 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1368 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 x = 0.0;
1371 if (exp >= lsb) {
1372 /* no rounding required */
1373 for (i = ndigits-1; i >= 0; i--)
1374 x = 16.0*x + HEX_DIGIT(i);
1375 x = ldexp(x, (int)(exp));
1376 goto finished;
1377 }
1378 /* rounding required. key_digit is the index of the hex digit
1379 containing the first bit to be rounded away. */
1380 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1381 key_digit = (lsb - exp - 1) / 4;
1382 for (i = ndigits-1; i > key_digit; i--)
1383 x = 16.0*x + HEX_DIGIT(i);
1384 digit = HEX_DIGIT(key_digit);
1385 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1388 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1389 if ((digit & half_eps) != 0) {
1390 round_up = 0;
1391 if ((digit & (3*half_eps-1)) != 0 ||
1392 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1393 round_up = 1;
1394 else
1395 for (i = key_digit-1; i >= 0; i--)
1396 if (HEX_DIGIT(i) != 0) {
1397 round_up = 1;
1398 break;
1399 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001400 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 x += 2*half_eps;
1402 if (top_exp == DBL_MAX_EXP &&
1403 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1404 /* overflow corner case: pre-rounded value <
1405 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1406 goto overflow_error;
1407 }
1408 }
1409 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001410
1411 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* optional trailing whitespace leading to the end of the string */
1413 while (Py_ISSPACE(*s))
1414 s++;
1415 if (s != s_end)
1416 goto parse_error;
1417 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1418 if (result_as_float == NULL)
1419 return NULL;
1420 result = PyObject_CallObject(cls, result_as_float);
1421 Py_DECREF(result_as_float);
1422 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001423
1424 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyErr_SetString(PyExc_OverflowError,
1426 "hexadecimal value too large to represent as a float");
1427 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001428
1429 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyErr_SetString(PyExc_ValueError,
1431 "invalid hexadecimal floating-point string");
1432 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001433
1434 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyErr_SetString(PyExc_ValueError,
1436 "hexadecimal string too long to convert");
1437 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001438}
1439
1440PyDoc_STRVAR(float_fromhex_doc,
1441"float.fromhex(string) -> float\n\
1442\n\
1443Create a floating-point number from a hexadecimal string.\n\
1444>>> float.fromhex('0x1.ffffp10')\n\
14452047.984375\n\
1446>>> float.fromhex('-0x1p-1074')\n\
1447-4.9406564584124654e-324");
1448
1449
Christian Heimes26855632008-01-27 23:50:43 +00001450static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001451float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 double self;
1454 double float_part;
1455 int exponent;
1456 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 PyObject *prev;
1459 PyObject *py_exponent = NULL;
1460 PyObject *numerator = NULL;
1461 PyObject *denominator = NULL;
1462 PyObject *result_pair = NULL;
1463 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001464
1465#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 prev = obj; \
1467 obj = call; \
1468 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (Py_IS_INFINITY(self)) {
1473 PyErr_SetString(PyExc_OverflowError,
1474 "Cannot pass infinity to float.as_integer_ratio.");
1475 return NULL;
1476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (Py_IS_NAN(self)) {
1478 PyErr_SetString(PyExc_ValueError,
1479 "Cannot pass NaN to float.as_integer_ratio.");
1480 return NULL;
1481 }
Christian Heimes26855632008-01-27 23:50:43 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1484 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1485 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1488 float_part *= 2.0;
1489 exponent--;
1490 }
1491 /* self == float_part * 2**exponent exactly and float_part is integral.
1492 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1493 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 numerator = PyLong_FromDouble(float_part);
1496 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 /* fold in 2**exponent */
1499 denominator = PyLong_FromLong(1);
1500 py_exponent = PyLong_FromLong(labs((long)exponent));
1501 if (py_exponent == NULL) goto error;
1502 INPLACE_UPDATE(py_exponent,
1503 long_methods->nb_lshift(denominator, py_exponent));
1504 if (py_exponent == NULL) goto error;
1505 if (exponent > 0) {
1506 INPLACE_UPDATE(numerator,
1507 long_methods->nb_multiply(numerator, py_exponent));
1508 if (numerator == NULL) goto error;
1509 }
1510 else {
1511 Py_DECREF(denominator);
1512 denominator = py_exponent;
1513 py_exponent = NULL;
1514 }
1515
1516 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001517
1518#undef INPLACE_UPDATE
1519error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_XDECREF(py_exponent);
1521 Py_XDECREF(denominator);
1522 Py_XDECREF(numerator);
1523 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001524}
1525
1526PyDoc_STRVAR(float_as_integer_ratio_doc,
1527"float.as_integer_ratio() -> (int, int)\n"
1528"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001529"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1530"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001531"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001532"\n"
1533">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001534"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001535">>> (0.0).as_integer_ratio()\n"
1536"(0, 1)\n"
1537">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001538"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001539
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001540
Jeremy Hylton938ace62002-07-17 16:30:39 +00001541static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001542float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1543
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544static PyObject *
1545float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 PyObject *x = Py_False; /* Integer zero */
1548 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (type != &PyFloat_Type)
1551 return float_subtype_new(type, args, kwds); /* Wimp out */
1552 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1553 return NULL;
1554 /* If it's a string, but not a string subclass, use
1555 PyFloat_FromString. */
1556 if (PyUnicode_CheckExact(x))
1557 return PyFloat_FromString(x);
1558 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559}
1560
Guido van Rossumbef14172001-08-29 15:47:46 +00001561/* Wimpy, slow approach to tp_new calls for subtypes of float:
1562 first create a regular float from whatever arguments we got,
1563 then allocate a subtype instance and initialize its ob_fval
1564 from the regular float. The regular float is then thrown away.
1565*/
1566static PyObject *
1567float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 assert(PyType_IsSubtype(type, &PyFloat_Type));
1572 tmp = float_new(&PyFloat_Type, args, kwds);
1573 if (tmp == NULL)
1574 return NULL;
1575 assert(PyFloat_CheckExact(tmp));
1576 newobj = type->tp_alloc(type, 0);
1577 if (newobj == NULL) {
1578 Py_DECREF(tmp);
1579 return NULL;
1580 }
1581 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1582 Py_DECREF(tmp);
1583 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001584}
1585
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001586static PyObject *
1587float_getnewargs(PyFloatObject *v)
1588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001590}
1591
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001592/* this is for the benefit of the pack/unpack routines below */
1593
1594typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001596} float_format_type;
1597
1598static float_format_type double_format, float_format;
1599static float_format_type detected_double_format, detected_float_format;
1600
1601static PyObject *
1602float_getformat(PyTypeObject *v, PyObject* arg)
1603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 char* s;
1605 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (!PyUnicode_Check(arg)) {
1608 PyErr_Format(PyExc_TypeError,
1609 "__getformat__() argument must be string, not %.500s",
1610 Py_TYPE(arg)->tp_name);
1611 return NULL;
1612 }
1613 s = _PyUnicode_AsString(arg);
1614 if (s == NULL)
1615 return NULL;
1616 if (strcmp(s, "double") == 0) {
1617 r = double_format;
1618 }
1619 else if (strcmp(s, "float") == 0) {
1620 r = float_format;
1621 }
1622 else {
1623 PyErr_SetString(PyExc_ValueError,
1624 "__getformat__() argument 1 must be "
1625 "'double' or 'float'");
1626 return NULL;
1627 }
1628
1629 switch (r) {
1630 case unknown_format:
1631 return PyUnicode_FromString("unknown");
1632 case ieee_little_endian_format:
1633 return PyUnicode_FromString("IEEE, little-endian");
1634 case ieee_big_endian_format:
1635 return PyUnicode_FromString("IEEE, big-endian");
1636 default:
1637 Py_FatalError("insane float_format or double_format");
1638 return NULL;
1639 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001640}
1641
1642PyDoc_STRVAR(float_getformat_doc,
1643"float.__getformat__(typestr) -> string\n"
1644"\n"
1645"You probably don't want to use this function. It exists mainly to be\n"
1646"used in Python's test suite.\n"
1647"\n"
1648"typestr must be 'double' or 'float'. This function returns whichever of\n"
1649"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1650"format of floating point numbers used by the C type named by typestr.");
1651
1652static PyObject *
1653float_setformat(PyTypeObject *v, PyObject* args)
1654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 char* typestr;
1656 char* format;
1657 float_format_type f;
1658 float_format_type detected;
1659 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1662 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (strcmp(typestr, "double") == 0) {
1665 p = &double_format;
1666 detected = detected_double_format;
1667 }
1668 else if (strcmp(typestr, "float") == 0) {
1669 p = &float_format;
1670 detected = detected_float_format;
1671 }
1672 else {
1673 PyErr_SetString(PyExc_ValueError,
1674 "__setformat__() argument 1 must "
1675 "be 'double' or 'float'");
1676 return NULL;
1677 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (strcmp(format, "unknown") == 0) {
1680 f = unknown_format;
1681 }
1682 else if (strcmp(format, "IEEE, little-endian") == 0) {
1683 f = ieee_little_endian_format;
1684 }
1685 else if (strcmp(format, "IEEE, big-endian") == 0) {
1686 f = ieee_big_endian_format;
1687 }
1688 else {
1689 PyErr_SetString(PyExc_ValueError,
1690 "__setformat__() argument 2 must be "
1691 "'unknown', 'IEEE, little-endian' or "
1692 "'IEEE, big-endian'");
1693 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 if (f != unknown_format && f != detected) {
1698 PyErr_Format(PyExc_ValueError,
1699 "can only set %s format to 'unknown' or the "
1700 "detected platform value", typestr);
1701 return NULL;
1702 }
1703
1704 *p = f;
1705 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001706}
1707
1708PyDoc_STRVAR(float_setformat_doc,
1709"float.__setformat__(typestr, fmt) -> None\n"
1710"\n"
1711"You probably don't want to use this function. It exists mainly to be\n"
1712"used in Python's test suite.\n"
1713"\n"
1714"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1715"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1716"one of the latter two if it appears to match the underlying C reality.\n"
1717"\n"
1718"Overrides the automatic determination of C-level floating point type.\n"
1719"This affects how floats are converted to and from binary strings.");
1720
Guido van Rossumb43daf72007-08-01 18:08:08 +00001721static PyObject *
1722float_getzero(PyObject *v, void *closure)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001725}
1726
Eric Smith8c663262007-08-25 02:26:07 +00001727static PyObject *
1728float__format__(PyObject *self, PyObject *args)
1729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1733 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 return _PyFloat_FormatAdvanced(self, format_spec, 0,
1735 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001736}
1737
1738PyDoc_STRVAR(float__format__doc,
1739"float.__format__(format_spec) -> string\n"
1740"\n"
1741"Formats the float according to format_spec.");
1742
1743
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001744static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1746 "Returns self, the complex conjugate of any float."},
1747 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1748 "Returns the Integral closest to x between 0 and x."},
1749 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1750 "Returns the Integral closest to x, rounding half toward even.\n"
1751 "When an argument is passed, works like built-in round(x, ndigits)."},
1752 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1753 float_as_integer_ratio_doc},
1754 {"fromhex", (PyCFunction)float_fromhex,
1755 METH_O|METH_CLASS, float_fromhex_doc},
1756 {"hex", (PyCFunction)float_hex,
1757 METH_NOARGS, float_hex_doc},
1758 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1759 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001760#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1762 "Returns True if the float is positive or negative infinite."},
1763 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1764 "Returns True if the float is finite, neither infinite nor NaN."},
1765 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1766 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001767#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1769 {"__getformat__", (PyCFunction)float_getformat,
1770 METH_O|METH_CLASS, float_getformat_doc},
1771 {"__setformat__", (PyCFunction)float_setformat,
1772 METH_VARARGS|METH_CLASS, float_setformat_doc},
1773 {"__format__", (PyCFunction)float__format__,
1774 METH_VARARGS, float__format__doc},
1775 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001776};
1777
Guido van Rossumb43daf72007-08-01 18:08:08 +00001778static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001780 (getter)float_float, (setter)NULL,
1781 "the real part of a complex number",
1782 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001784 (getter)float_getzero, (setter)NULL,
1785 "the imaginary part of a complex number",
1786 NULL},
1787 {NULL} /* Sentinel */
1788};
1789
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001790PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791"float(x) -> floating point number\n\
1792\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001793Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794
1795
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001796static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 float_add, /*nb_add*/
1798 float_sub, /*nb_subtract*/
1799 float_mul, /*nb_multiply*/
1800 float_rem, /*nb_remainder*/
1801 float_divmod, /*nb_divmod*/
1802 float_pow, /*nb_power*/
1803 (unaryfunc)float_neg, /*nb_negative*/
1804 (unaryfunc)float_float, /*nb_positive*/
1805 (unaryfunc)float_abs, /*nb_absolute*/
1806 (inquiry)float_bool, /*nb_bool*/
1807 0, /*nb_invert*/
1808 0, /*nb_lshift*/
1809 0, /*nb_rshift*/
1810 0, /*nb_and*/
1811 0, /*nb_xor*/
1812 0, /*nb_or*/
1813 float_trunc, /*nb_int*/
1814 0, /*nb_reserved*/
1815 float_float, /*nb_float*/
1816 0, /* nb_inplace_add */
1817 0, /* nb_inplace_subtract */
1818 0, /* nb_inplace_multiply */
1819 0, /* nb_inplace_remainder */
1820 0, /* nb_inplace_power */
1821 0, /* nb_inplace_lshift */
1822 0, /* nb_inplace_rshift */
1823 0, /* nb_inplace_and */
1824 0, /* nb_inplace_xor */
1825 0, /* nb_inplace_or */
1826 float_floor_div, /* nb_floor_divide */
1827 float_div, /* nb_true_divide */
1828 0, /* nb_inplace_floor_divide */
1829 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001830};
1831
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001832PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1834 "float",
1835 sizeof(PyFloatObject),
1836 0,
1837 (destructor)float_dealloc, /* tp_dealloc */
1838 0, /* tp_print */
1839 0, /* tp_getattr */
1840 0, /* tp_setattr */
1841 0, /* tp_reserved */
1842 (reprfunc)float_repr, /* tp_repr */
1843 &float_as_number, /* tp_as_number */
1844 0, /* tp_as_sequence */
1845 0, /* tp_as_mapping */
1846 (hashfunc)float_hash, /* tp_hash */
1847 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001848 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 PyObject_GenericGetAttr, /* tp_getattro */
1850 0, /* tp_setattro */
1851 0, /* tp_as_buffer */
1852 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1853 float_doc, /* tp_doc */
1854 0, /* tp_traverse */
1855 0, /* tp_clear */
1856 float_richcompare, /* tp_richcompare */
1857 0, /* tp_weaklistoffset */
1858 0, /* tp_iter */
1859 0, /* tp_iternext */
1860 float_methods, /* tp_methods */
1861 0, /* tp_members */
1862 float_getset, /* tp_getset */
1863 0, /* tp_base */
1864 0, /* tp_dict */
1865 0, /* tp_descr_get */
1866 0, /* tp_descr_set */
1867 0, /* tp_dictoffset */
1868 0, /* tp_init */
1869 0, /* tp_alloc */
1870 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001871};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001872
1873void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001874_PyFloat_Init(void)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 /* We attempt to determine if this machine is using IEEE
1877 floating point formats by peering at the bits of some
1878 carefully chosen values. If it looks like we are on an
1879 IEEE platform, the float packing/unpacking routines can
1880 just copy bits, if not they resort to arithmetic & shifts
1881 and masks. The shifts & masks approach works on all finite
1882 values, but what happens to infinities, NaNs and signed
1883 zeroes on packing is an accident, and attempting to unpack
1884 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 Note that if we're on some whacked-out platform which uses
1887 IEEE formats but isn't strictly little-endian or big-
1888 endian, we will fall back to the portable shifts & masks
1889 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001890
1891#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 {
1893 double x = 9006104071832581.0;
1894 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1895 detected_double_format = ieee_big_endian_format;
1896 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1897 detected_double_format = ieee_little_endian_format;
1898 else
1899 detected_double_format = unknown_format;
1900 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001903#endif
1904
1905#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 {
1907 float y = 16711938.0;
1908 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1909 detected_float_format = ieee_big_endian_format;
1910 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1911 detected_float_format = ieee_little_endian_format;
1912 else
1913 detected_float_format = unknown_format;
1914 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001915#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001917#endif
1918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 double_format = detected_double_format;
1920 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 /* Init float info */
1923 if (FloatInfoType.tp_name == 0)
1924 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001925}
1926
Georg Brandl2ee470f2008-07-16 12:55:28 +00001927int
1928PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyFloatObject *p;
1931 PyFloatBlock *list, *next;
1932 int i;
1933 int u; /* remaining unfreed floats per block */
1934 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 list = block_list;
1937 block_list = NULL;
1938 free_list = NULL;
1939 while (list != NULL) {
1940 u = 0;
1941 for (i = 0, p = &list->objects[0];
1942 i < N_FLOATOBJECTS;
1943 i++, p++) {
1944 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1945 u++;
1946 }
1947 next = list->next;
1948 if (u) {
1949 list->next = block_list;
1950 block_list = list;
1951 for (i = 0, p = &list->objects[0];
1952 i < N_FLOATOBJECTS;
1953 i++, p++) {
1954 if (!PyFloat_CheckExact(p) ||
1955 Py_REFCNT(p) == 0) {
1956 Py_TYPE(p) = (struct _typeobject *)
1957 free_list;
1958 free_list = p;
1959 }
1960 }
1961 }
1962 else {
1963 PyMem_FREE(list);
1964 }
1965 freelist_size += u;
1966 list = next;
1967 }
1968 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001969}
1970
1971void
1972PyFloat_Fini(void)
1973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyFloatObject *p;
1975 PyFloatBlock *list;
1976 int i;
1977 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (!Py_VerboseFlag)
1982 return;
1983 fprintf(stderr, "# cleanup floats");
1984 if (!u) {
1985 fprintf(stderr, "\n");
1986 }
1987 else {
1988 fprintf(stderr,
1989 ": %d unfreed float%s\n",
1990 u, u == 1 ? "" : "s");
1991 }
1992 if (Py_VerboseFlag > 1) {
1993 list = block_list;
1994 while (list != NULL) {
1995 for (i = 0, p = &list->objects[0];
1996 i < N_FLOATOBJECTS;
1997 i++, p++) {
1998 if (PyFloat_CheckExact(p) &&
1999 Py_REFCNT(p) != 0) {
2000 char *buf = PyOS_double_to_string(
2001 PyFloat_AS_DOUBLE(p), 'r',
2002 0, 0, NULL);
2003 if (buf) {
2004 /* XXX(twouters) cast
2005 refcount to long
2006 until %zd is
2007 universally
2008 available
2009 */
2010 fprintf(stderr,
2011 "# <float at %p, refcnt=%ld, val=%s>\n",
2012 p, (long)Py_REFCNT(p), buf);
2013 PyMem_Free(buf);
2014 }
2015 }
2016 }
2017 list = list->next;
2018 }
2019 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002020}
Tim Peters9905b942003-03-20 20:53:32 +00002021
2022/*----------------------------------------------------------------------------
2023 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002024 */
2025int
2026_PyFloat_Pack4(double x, unsigned char *p, int le)
2027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (float_format == unknown_format) {
2029 unsigned char sign;
2030 int e;
2031 double f;
2032 unsigned int fbits;
2033 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (le) {
2036 p += 3;
2037 incr = -1;
2038 }
Tim Peters9905b942003-03-20 20:53:32 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (x < 0) {
2041 sign = 1;
2042 x = -x;
2043 }
2044 else
2045 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* Normalize f to be in the range [1.0, 2.0) */
2050 if (0.5 <= f && f < 1.0) {
2051 f *= 2.0;
2052 e--;
2053 }
2054 else if (f == 0.0)
2055 e = 0;
2056 else {
2057 PyErr_SetString(PyExc_SystemError,
2058 "frexp() result out of range");
2059 return -1;
2060 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (e >= 128)
2063 goto Overflow;
2064 else if (e < -126) {
2065 /* Gradual underflow */
2066 f = ldexp(f, 126 + e);
2067 e = 0;
2068 }
2069 else if (!(e == 0 && f == 0.0)) {
2070 e += 127;
2071 f -= 1.0; /* Get rid of leading 1 */
2072 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 f *= 8388608.0; /* 2**23 */
2075 fbits = (unsigned int)(f + 0.5); /* Round */
2076 assert(fbits <= 8388608);
2077 if (fbits >> 23) {
2078 /* The carry propagated out of a string of 23 1 bits. */
2079 fbits = 0;
2080 ++e;
2081 if (e >= 255)
2082 goto Overflow;
2083 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* First byte */
2086 *p = (sign << 7) | (e >> 1);
2087 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 /* Second byte */
2090 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2091 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 /* Third byte */
2094 *p = (fbits >> 8) & 0xFF;
2095 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* Fourth byte */
2098 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* Done */
2101 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 }
2104 else {
2105 float y = (float)x;
2106 const char *s = (char*)&y;
2107 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2110 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if ((float_format == ieee_little_endian_format && !le)
2113 || (float_format == ieee_big_endian_format && le)) {
2114 p += 3;
2115 incr = -1;
2116 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 for (i = 0; i < 4; i++) {
2119 *p = *s++;
2120 p += incr;
2121 }
2122 return 0;
2123 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002124 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyErr_SetString(PyExc_OverflowError,
2126 "float too large to pack with f format");
2127 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002128}
2129
2130int
2131_PyFloat_Pack8(double x, unsigned char *p, int le)
2132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (double_format == unknown_format) {
2134 unsigned char sign;
2135 int e;
2136 double f;
2137 unsigned int fhi, flo;
2138 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (le) {
2141 p += 7;
2142 incr = -1;
2143 }
Tim Peters9905b942003-03-20 20:53:32 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (x < 0) {
2146 sign = 1;
2147 x = -x;
2148 }
2149 else
2150 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 /* Normalize f to be in the range [1.0, 2.0) */
2155 if (0.5 <= f && f < 1.0) {
2156 f *= 2.0;
2157 e--;
2158 }
2159 else if (f == 0.0)
2160 e = 0;
2161 else {
2162 PyErr_SetString(PyExc_SystemError,
2163 "frexp() result out of range");
2164 return -1;
2165 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (e >= 1024)
2168 goto Overflow;
2169 else if (e < -1022) {
2170 /* Gradual underflow */
2171 f = ldexp(f, 1022 + e);
2172 e = 0;
2173 }
2174 else if (!(e == 0 && f == 0.0)) {
2175 e += 1023;
2176 f -= 1.0; /* Get rid of leading 1 */
2177 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2180 f *= 268435456.0; /* 2**28 */
2181 fhi = (unsigned int)f; /* Truncate */
2182 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 f -= (double)fhi;
2185 f *= 16777216.0; /* 2**24 */
2186 flo = (unsigned int)(f + 0.5); /* Round */
2187 assert(flo <= 16777216);
2188 if (flo >> 24) {
2189 /* The carry propagated out of a string of 24 1 bits. */
2190 flo = 0;
2191 ++fhi;
2192 if (fhi >> 28) {
2193 /* And it also progagated out of the next 28 bits. */
2194 fhi = 0;
2195 ++e;
2196 if (e >= 2047)
2197 goto Overflow;
2198 }
2199 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* First byte */
2202 *p = (sign << 7) | (e >> 4);
2203 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* Second byte */
2206 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2207 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 /* Third byte */
2210 *p = (fhi >> 16) & 0xFF;
2211 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* Fourth byte */
2214 *p = (fhi >> 8) & 0xFF;
2215 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* Fifth byte */
2218 *p = fhi & 0xFF;
2219 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* Sixth byte */
2222 *p = (flo >> 16) & 0xFF;
2223 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Seventh byte */
2226 *p = (flo >> 8) & 0xFF;
2227 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* Eighth byte */
2230 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002231 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Done */
2234 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Overflow:
2237 PyErr_SetString(PyExc_OverflowError,
2238 "float too large to pack with d format");
2239 return -1;
2240 }
2241 else {
2242 const char *s = (char*)&x;
2243 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 if ((double_format == ieee_little_endian_format && !le)
2246 || (double_format == ieee_big_endian_format && le)) {
2247 p += 7;
2248 incr = -1;
2249 }
2250
2251 for (i = 0; i < 8; i++) {
2252 *p = *s++;
2253 p += incr;
2254 }
2255 return 0;
2256 }
Tim Peters9905b942003-03-20 20:53:32 +00002257}
2258
2259double
2260_PyFloat_Unpack4(const unsigned char *p, int le)
2261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if (float_format == unknown_format) {
2263 unsigned char sign;
2264 int e;
2265 unsigned int f;
2266 double x;
2267 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (le) {
2270 p += 3;
2271 incr = -1;
2272 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* First byte */
2275 sign = (*p >> 7) & 1;
2276 e = (*p & 0x7F) << 1;
2277 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* Second byte */
2280 e |= (*p >> 7) & 1;
2281 f = (*p & 0x7F) << 16;
2282 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (e == 255) {
2285 PyErr_SetString(
2286 PyExc_ValueError,
2287 "can't unpack IEEE 754 special value "
2288 "on non-IEEE platform");
2289 return -1;
2290 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 /* Third byte */
2293 f |= *p << 8;
2294 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Fourth byte */
2297 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* XXX This sadly ignores Inf/NaN issues */
2302 if (e == 0)
2303 e = -126;
2304 else {
2305 x += 1.0;
2306 e -= 127;
2307 }
2308 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 if (sign)
2311 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 return x;
2314 }
2315 else {
2316 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if ((float_format == ieee_little_endian_format && !le)
2319 || (float_format == ieee_big_endian_format && le)) {
2320 char buf[4];
2321 char *d = &buf[3];
2322 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 for (i = 0; i < 4; i++) {
2325 *d-- = *p++;
2326 }
2327 memcpy(&x, buf, 4);
2328 }
2329 else {
2330 memcpy(&x, p, 4);
2331 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 return x;
2334 }
Tim Peters9905b942003-03-20 20:53:32 +00002335}
2336
2337double
2338_PyFloat_Unpack8(const unsigned char *p, int le)
2339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 if (double_format == unknown_format) {
2341 unsigned char sign;
2342 int e;
2343 unsigned int fhi, flo;
2344 double x;
2345 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (le) {
2348 p += 7;
2349 incr = -1;
2350 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 /* First byte */
2353 sign = (*p >> 7) & 1;
2354 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* Second byte */
2359 e |= (*p >> 4) & 0xF;
2360 fhi = (*p & 0xF) << 24;
2361 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (e == 2047) {
2364 PyErr_SetString(
2365 PyExc_ValueError,
2366 "can't unpack IEEE 754 special value "
2367 "on non-IEEE platform");
2368 return -1.0;
2369 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* Third byte */
2372 fhi |= *p << 16;
2373 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Fourth byte */
2376 fhi |= *p << 8;
2377 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* Fifth byte */
2380 fhi |= *p;
2381 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* Sixth byte */
2384 flo = *p << 16;
2385 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* Seventh byte */
2388 flo |= *p << 8;
2389 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Eighth byte */
2392 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2395 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 if (e == 0)
2398 e = -1022;
2399 else {
2400 x += 1.0;
2401 e -= 1023;
2402 }
2403 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 if (sign)
2406 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return x;
2409 }
2410 else {
2411 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 if ((double_format == ieee_little_endian_format && !le)
2414 || (double_format == ieee_big_endian_format && le)) {
2415 char buf[8];
2416 char *d = &buf[7];
2417 int i;
2418
2419 for (i = 0; i < 8; i++) {
2420 *d-- = *p++;
2421 }
2422 memcpy(&x, buf, 8);
2423 }
2424 else {
2425 memcpy(&x, p, 8);
2426 }
2427
2428 return x;
2429 }
Tim Peters9905b942003-03-20 20:53:32 +00002430}