blob: 05b76795532063b70b753d8a3840b9225c2ad2a9 [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
Guido van Rossum6923e131990-11-02 17:50:43 +000012
Mark Dickinsond19052c2010-06-27 18:19:09 +000013/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000014 free_list is a singly-linked list of available PyFloatObjects, linked
15 via abuse of their ob_type members.
16*/
17
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000018#ifndef PyFloat_MAXFREELIST
19#define PyFloat_MAXFREELIST 100
20#endif
21static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000022static PyFloatObject *free_list = NULL;
23
Christian Heimes93852662007-12-01 12:22:32 +000024double
25PyFloat_GetMax(void)
26{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000028}
29
30double
31PyFloat_GetMin(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
Christian Heimesd32ed6f2008-01-14 18:49:24 +000036static PyTypeObject FloatInfoType;
37
38PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000039"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000040\n\
41A structseq holding information about the float type. It contains low level\n\
42information about the precision and internal representation. Please study\n\
43your system's :file:`float.h` for more information.");
44
45static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 {"max", "DBL_MAX -- maximum representable finite float"},
47 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
48 "is representable"},
49 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
50 "is representable"},
51 {"min", "DBL_MIN -- Minimum positive normalizer float"},
52 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
53 "is a normalized float"},
54 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
55 "a normalized"},
56 {"dig", "DBL_DIG -- digits"},
57 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
58 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
59 "representable float"},
60 {"radix", "FLT_RADIX -- radix of exponent"},
61 {"rounds", "FLT_ROUNDS -- addition rounds"},
62 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000063};
64
65static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 "sys.float_info", /* name */
67 floatinfo__doc__, /* doc */
68 floatinfo_fields, /* fields */
69 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000070};
71
Christian Heimes93852662007-12-01 12:22:32 +000072PyObject *
73PyFloat_GetInfo(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject* floatinfo;
76 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 floatinfo = PyStructSequence_New(&FloatInfoType);
79 if (floatinfo == NULL) {
80 return NULL;
81 }
Christian Heimes93852662007-12-01 12:22:32 +000082
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000085#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 SetDblFlag(DBL_MAX);
89 SetIntFlag(DBL_MAX_EXP);
90 SetIntFlag(DBL_MAX_10_EXP);
91 SetDblFlag(DBL_MIN);
92 SetIntFlag(DBL_MIN_EXP);
93 SetIntFlag(DBL_MIN_10_EXP);
94 SetIntFlag(DBL_DIG);
95 SetIntFlag(DBL_MANT_DIG);
96 SetDblFlag(DBL_EPSILON);
97 SetIntFlag(FLT_RADIX);
98 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +000099#undef SetIntFlag
100#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101
102 if (PyErr_Occurred()) {
103 Py_CLEAR(floatinfo);
104 return NULL;
105 }
106 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000107}
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200112 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000113 if (op != NULL) {
114 free_list = (PyFloatObject *) Py_TYPE(op);
115 numfree--;
116 } else {
117 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
118 if (!op)
119 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
121 /* Inline PyObject_New */
Christian Heimesd3afe782013-12-04 09:27:47 +0100122 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 op->ob_fval = fval;
124 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125}
126
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000127PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000128PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 const char *s, *last, *end;
131 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000132 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_ssize_t len;
134 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200137 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000139 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200140 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000141 if (s == NULL) {
142 Py_DECREF(s_buffer);
143 return NULL;
144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 }
146 else if (PyObject_AsCharBuffer(v, &s, &len)) {
Ezio Melottia5b95992013-11-07 19:18:34 +0200147 PyErr_Format(PyExc_TypeError,
148 "float() argument must be a string or a number, not '%.200s'",
149 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return NULL;
151 }
152 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000153 /* strip space */
154 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000156 while (s < last - 1 && Py_ISSPACE(last[-1]))
157 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 /* We don't care about overflow or underflow. If the platform
159 * supports them, infinities and signed zeroes (on underflow) are
160 * fine. */
161 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000162 if (end != last) {
163 PyErr_Format(PyExc_ValueError,
164 "could not convert string to float: "
165 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 result = NULL;
167 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000168 else if (x == -1.0 && PyErr_Occurred())
169 result = NULL;
170 else
171 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000172
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000173 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175}
176
Guido van Rossum234f9421993-06-17 12:35:49 +0000177static void
Fred Drakefd99de62000-07-09 05:02:18 +0000178float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000181 if (numfree >= PyFloat_MAXFREELIST) {
182 PyObject_FREE(op);
183 return;
184 }
185 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 Py_TYPE(op) = (struct _typeobject *)free_list;
187 free_list = op;
188 }
189 else
190 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000191}
192
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193double
Fred Drakefd99de62000-07-09 05:02:18 +0000194PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 PyNumberMethods *nb;
197 PyFloatObject *fo;
198 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 if (op && PyFloat_Check(op))
201 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (op == NULL) {
204 PyErr_BadArgument();
205 return -1;
206 }
Tim Petersd2364e82001-11-01 20:09:42 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
209 PyErr_SetString(PyExc_TypeError, "a float is required");
210 return -1;
211 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 fo = (PyFloatObject*) (*nb->nb_float) (op);
214 if (fo == NULL)
215 return -1;
216 if (!PyFloat_Check(fo)) {
217 PyErr_SetString(PyExc_TypeError,
218 "nb_float should return float object");
219 return -1;
220 }
Tim Petersd2364e82001-11-01 20:09:42 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 val = PyFloat_AS_DOUBLE(fo);
223 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226}
227
Neil Schemenauer32117e52001-01-04 01:44:34 +0000228/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000229 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000230 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300231 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000232 stored in obj, and returned from the function invoking this macro.
233*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234#define CONVERT_TO_DOUBLE(obj, dbl) \
235 if (PyFloat_Check(obj)) \
236 dbl = PyFloat_AS_DOUBLE(obj); \
237 else if (convert_to_double(&(obj), &(dbl)) < 0) \
238 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000239
Eric Smith0923d1d2009-04-16 20:16:10 +0000240/* Methods */
241
Neil Schemenauer32117e52001-01-04 01:44:34 +0000242static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000243convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000244{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200245 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (PyLong_Check(obj)) {
248 *dbl = PyLong_AsDouble(obj);
249 if (*dbl == -1.0 && PyErr_Occurred()) {
250 *v = NULL;
251 return -1;
252 }
253 }
254 else {
255 Py_INCREF(Py_NotImplemented);
256 *v = Py_NotImplemented;
257 return -1;
258 }
259 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000260}
261
Eric Smith0923d1d2009-04-16 20:16:10 +0000262static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000263float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000264{
265 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200266 char *buf;
267
268 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
269 'r', 0,
270 Py_DTSF_ADD_DOT_0,
271 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000272 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000273 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200274 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000275 PyMem_Free(buf);
276 return result;
277}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000278
Tim Peters307fa782004-09-23 08:06:40 +0000279/* Comparison is pretty much a nightmare. When comparing float to float,
280 * we do it as straightforwardly (and long-windedly) as conceivable, so
281 * that, e.g., Python x == y delivers the same result as the platform
282 * C x == y when x and/or y is a NaN.
283 * When mixing float with an integer type, there's no good *uniform* approach.
284 * Converting the double to an integer obviously doesn't work, since we
285 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300286 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000287 * large to fit in the dynamic range of a C double); (2) even a C long may have
Ezio Melotti3f5db392013-01-27 06:20:14 +0200288 * more bits than fit in a C double (e.g., on a 64-bit box long may have
Tim Peters307fa782004-09-23 08:06:40 +0000289 * 63 bits of precision, but a C double probably has only 53), and then
290 * we can falsely claim equality when low-order integer bits are lost by
291 * coercion to double. So this part is painful too.
292 */
293
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000294static PyObject*
295float_richcompare(PyObject *v, PyObject *w, int op)
296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 double i, j;
298 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 assert(PyFloat_Check(v));
301 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 /* Switch on the type of w. Set i and j to doubles to be compared,
304 * and op to the richcomp to use.
305 */
306 if (PyFloat_Check(w))
307 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 else if (!Py_IS_FINITE(i)) {
310 if (PyLong_Check(w))
311 /* If i is an infinity, its magnitude exceeds any
312 * finite integer, so it doesn't matter which int we
313 * compare i with. If i is a NaN, similarly.
314 */
315 j = 0.0;
316 else
317 goto Unimplemented;
318 }
Tim Peters307fa782004-09-23 08:06:40 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 else if (PyLong_Check(w)) {
321 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
322 int wsign = _PyLong_Sign(w);
323 size_t nbits;
324 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (vsign != wsign) {
327 /* Magnitudes are irrelevant -- the signs alone
328 * determine the outcome.
329 */
330 i = (double)vsign;
331 j = (double)wsign;
332 goto Compare;
333 }
334 /* The signs are the same. */
335 /* Convert w to a double if it fits. In particular, 0 fits. */
336 nbits = _PyLong_NumBits(w);
337 if (nbits == (size_t)-1 && PyErr_Occurred()) {
338 /* This long is so large that size_t isn't big enough
339 * to hold the # of bits. Replace with little doubles
340 * that give the same outcome -- w is so large that
341 * its magnitude must exceed the magnitude of any
342 * finite float.
343 */
344 PyErr_Clear();
345 i = (double)vsign;
346 assert(wsign != 0);
347 j = wsign * 2.0;
348 goto Compare;
349 }
350 if (nbits <= 48) {
351 j = PyLong_AsDouble(w);
352 /* It's impossible that <= 48 bits overflowed. */
353 assert(j != -1.0 || ! PyErr_Occurred());
354 goto Compare;
355 }
356 assert(wsign != 0); /* else nbits was 0 */
357 assert(vsign != 0); /* if vsign were 0, then since wsign is
358 * not 0, we would have taken the
359 * vsign != wsign branch at the start */
360 /* We want to work with non-negative numbers. */
361 if (vsign < 0) {
362 /* "Multiply both sides" by -1; this also swaps the
363 * comparator.
364 */
365 i = -i;
366 op = _Py_SwappedOp[op];
367 }
368 assert(i > 0.0);
369 (void) frexp(i, &exponent);
370 /* exponent is the # of bits in v before the radix point;
371 * we know that nbits (the # of bits in w) > 48 at this point
372 */
373 if (exponent < 0 || (size_t)exponent < nbits) {
374 i = 1.0;
375 j = 2.0;
376 goto Compare;
377 }
378 if ((size_t)exponent > nbits) {
379 i = 2.0;
380 j = 1.0;
381 goto Compare;
382 }
383 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300384 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 * outcome.
386 */
387 {
388 double fracpart;
389 double intpart;
390 PyObject *result = NULL;
391 PyObject *one = NULL;
392 PyObject *vv = NULL;
393 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (wsign < 0) {
396 ww = PyNumber_Negative(w);
397 if (ww == NULL)
398 goto Error;
399 }
400 else
401 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 fracpart = modf(i, &intpart);
404 vv = PyLong_FromDouble(intpart);
405 if (vv == NULL)
406 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (fracpart != 0.0) {
409 /* Shift left, and or a 1 bit into vv
410 * to represent the lost fraction.
411 */
412 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 one = PyLong_FromLong(1);
415 if (one == NULL)
416 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 temp = PyNumber_Lshift(ww, one);
419 if (temp == NULL)
420 goto Error;
421 Py_DECREF(ww);
422 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 temp = PyNumber_Lshift(vv, one);
425 if (temp == NULL)
426 goto Error;
427 Py_DECREF(vv);
428 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 temp = PyNumber_Or(vv, one);
431 if (temp == NULL)
432 goto Error;
433 Py_DECREF(vv);
434 vv = temp;
435 }
Tim Peters307fa782004-09-23 08:06:40 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 r = PyObject_RichCompareBool(vv, ww, op);
438 if (r < 0)
439 goto Error;
440 result = PyBool_FromLong(r);
441 Error:
442 Py_XDECREF(vv);
443 Py_XDECREF(ww);
444 Py_XDECREF(one);
445 return result;
446 }
447 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000448
Serhiy Storchaka95949422013-08-27 19:40:23 +0300449 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000451
452 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyFPE_START_PROTECT("richcompare", return NULL)
454 switch (op) {
455 case Py_EQ:
456 r = i == j;
457 break;
458 case Py_NE:
459 r = i != j;
460 break;
461 case Py_LE:
462 r = i <= j;
463 break;
464 case Py_GE:
465 r = i >= j;
466 break;
467 case Py_LT:
468 r = i < j;
469 break;
470 case Py_GT:
471 r = i > j;
472 break;
473 }
474 PyFPE_END_PROTECT(r)
475 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000476
477 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500478 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000479}
480
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000481static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000482float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000485}
486
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000488float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 double a,b;
491 CONVERT_TO_DOUBLE(v, a);
492 CONVERT_TO_DOUBLE(w, b);
493 PyFPE_START_PROTECT("add", return 0)
494 a = a + b;
495 PyFPE_END_PROTECT(a)
496 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000500float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 double a,b;
503 CONVERT_TO_DOUBLE(v, a);
504 CONVERT_TO_DOUBLE(w, b);
505 PyFPE_START_PROTECT("subtract", return 0)
506 a = a - b;
507 PyFPE_END_PROTECT(a)
508 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000509}
510
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000512float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 double a,b;
515 CONVERT_TO_DOUBLE(v, a);
516 CONVERT_TO_DOUBLE(w, b);
517 PyFPE_START_PROTECT("multiply", return 0)
518 a = a * b;
519 PyFPE_END_PROTECT(a)
520 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521}
522
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000524float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 double a,b;
527 CONVERT_TO_DOUBLE(v, a);
528 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (b == 0.0) {
530 PyErr_SetString(PyExc_ZeroDivisionError,
531 "float division by zero");
532 return NULL;
533 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 PyFPE_START_PROTECT("divide", return 0)
535 a = a / b;
536 PyFPE_END_PROTECT(a)
537 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538}
539
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 double vx, wx;
544 double mod;
545 CONVERT_TO_DOUBLE(v, vx);
546 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (wx == 0.0) {
548 PyErr_SetString(PyExc_ZeroDivisionError,
549 "float modulo");
550 return NULL;
551 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyFPE_START_PROTECT("modulo", return 0)
553 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000554 if (mod) {
555 /* ensure the remainder has the same sign as the denominator */
556 if ((wx < 0) != (mod < 0)) {
557 mod += wx;
558 }
559 }
560 else {
561 /* the remainder is zero, and in the presence of signed zeroes
562 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000563 it has the same sign as the denominator. */
564 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
566 PyFPE_END_PROTECT(mod)
567 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568}
569
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000571float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 double vx, wx;
574 double div, mod, floordiv;
575 CONVERT_TO_DOUBLE(v, vx);
576 CONVERT_TO_DOUBLE(w, wx);
577 if (wx == 0.0) {
578 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
579 return NULL;
580 }
581 PyFPE_START_PROTECT("divmod", return 0)
582 mod = fmod(vx, wx);
583 /* fmod is typically exact, so vx-mod is *mathematically* an
584 exact multiple of wx. But this is fp arithmetic, and fp
585 vx - mod is an approximation; the result is that div may
586 not be an exact integral value after the division, although
587 it will always be very close to one.
588 */
589 div = (vx - mod) / wx;
590 if (mod) {
591 /* ensure the remainder has the same sign as the denominator */
592 if ((wx < 0) != (mod < 0)) {
593 mod += wx;
594 div -= 1.0;
595 }
596 }
597 else {
598 /* the remainder is zero, and in the presence of signed zeroes
599 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000600 it has the same sign as the denominator. */
601 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 }
603 /* snap quotient to nearest integral value */
604 if (div) {
605 floordiv = floor(div);
606 if (div - floordiv > 0.5)
607 floordiv += 1.0;
608 }
609 else {
610 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000611 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
613 PyFPE_END_PROTECT(floordiv)
614 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000615}
616
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000617static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000618float_floor_div(PyObject *v, PyObject *w)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 t = float_divmod(v, w);
623 if (t == NULL || t == Py_NotImplemented)
624 return t;
625 assert(PyTuple_CheckExact(t));
626 r = PyTuple_GET_ITEM(t, 0);
627 Py_INCREF(r);
628 Py_DECREF(t);
629 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000630}
631
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000632/* determine whether x is an odd integer or not; assumes that
633 x is not an infinity or nan. */
634#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
635
Tim Peters63a35712001-12-11 19:57:24 +0000636static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000637float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 double iv, iw, ix;
640 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if ((PyObject *)z != Py_None) {
643 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
644 "allowed unless all arguments are integers");
645 return NULL;
646 }
Tim Peters32f453e2001-09-03 08:35:41 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 CONVERT_TO_DOUBLE(v, iv);
649 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 /* Sort out special cases here instead of relying on pow() */
652 if (iw == 0) { /* v**0 is 1, even 0**0 */
653 return PyFloat_FromDouble(1.0);
654 }
655 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
656 return PyFloat_FromDouble(iv);
657 }
658 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
659 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
660 }
661 if (Py_IS_INFINITY(iw)) {
662 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
663 * abs(v) > 1 (including case where v infinite)
664 *
665 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
666 * abs(v) > 1 (including case where v infinite)
667 */
668 iv = fabs(iv);
669 if (iv == 1.0)
670 return PyFloat_FromDouble(1.0);
671 else if ((iw > 0.0) == (iv > 1.0))
672 return PyFloat_FromDouble(fabs(iw)); /* return inf */
673 else
674 return PyFloat_FromDouble(0.0);
675 }
676 if (Py_IS_INFINITY(iv)) {
677 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
678 * both cases, we need to add the appropriate sign if w is
679 * an odd integer.
680 */
681 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
682 if (iw > 0.0)
683 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
684 else
685 return PyFloat_FromDouble(iw_is_odd ?
686 copysign(0.0, iv) : 0.0);
687 }
688 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
689 (already dealt with above), and an error
690 if w is negative. */
691 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
692 if (iw < 0.0) {
693 PyErr_SetString(PyExc_ZeroDivisionError,
694 "0.0 cannot be raised to a "
695 "negative power");
696 return NULL;
697 }
698 /* use correct sign if iw is odd */
699 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
700 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (iv < 0.0) {
703 /* Whether this is an error is a mess, and bumps into libm
704 * bugs so we have to figure it out ourselves.
705 */
706 if (iw != floor(iw)) {
707 /* Negative numbers raised to fractional powers
708 * become complex.
709 */
710 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
711 }
712 /* iw is an exact integer, albeit perhaps a very large
713 * one. Replace iv by its absolute value and remember
714 * to negate the pow result if iw is odd.
715 */
716 iv = -iv;
717 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
718 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
721 /* (-1) ** large_integer also ends up here. Here's an
722 * extract from the comments for the previous
723 * implementation explaining why this special case is
724 * necessary:
725 *
726 * -1 raised to an exact integer should never be exceptional.
727 * Alas, some libms (chiefly glibc as of early 2003) return
728 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
729 * happen to be representable in a *C* integer. That's a
730 * bug.
731 */
732 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
733 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 /* Now iv and iw are finite, iw is nonzero, and iv is
736 * positive and not equal to 1.0. We finally allow
737 * the platform pow to step in and do the rest.
738 */
739 errno = 0;
740 PyFPE_START_PROTECT("pow", return NULL)
741 ix = pow(iv, iw);
742 PyFPE_END_PROTECT(ix)
743 Py_ADJUST_ERANGE1(ix);
744 if (negate_result)
745 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (errno != 0) {
748 /* We don't expect any errno value other than ERANGE, but
749 * the range of libm bugs appears unbounded.
750 */
751 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
752 PyExc_ValueError);
753 return NULL;
754 }
755 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756}
757
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000758#undef DOUBLE_IS_ODD_INTEGER
759
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000761float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764}
765
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000766static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000767float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770}
771
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000772static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000773float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000779float_is_integer(PyObject *v)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 double x = PyFloat_AsDouble(v);
782 PyObject *o;
783
784 if (x == -1.0 && PyErr_Occurred())
785 return NULL;
786 if (!Py_IS_FINITE(x))
787 Py_RETURN_FALSE;
788 errno = 0;
789 PyFPE_START_PROTECT("is_integer", return NULL)
790 o = (floor(x) == x) ? Py_True : Py_False;
791 PyFPE_END_PROTECT(x)
792 if (errno != 0) {
793 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
794 PyExc_ValueError);
795 return NULL;
796 }
797 Py_INCREF(o);
798 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000799}
800
801#if 0
802static PyObject *
803float_is_inf(PyObject *v)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 double x = PyFloat_AsDouble(v);
806 if (x == -1.0 && PyErr_Occurred())
807 return NULL;
808 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000809}
810
811static PyObject *
812float_is_nan(PyObject *v)
813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 double x = PyFloat_AsDouble(v);
815 if (x == -1.0 && PyErr_Occurred())
816 return NULL;
817 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000818}
819
820static PyObject *
821float_is_finite(PyObject *v)
822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 double x = PyFloat_AsDouble(v);
824 if (x == -1.0 && PyErr_Occurred())
825 return NULL;
826 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000827}
828#endif
829
830static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000831float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 double x = PyFloat_AsDouble(v);
834 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 (void)modf(x, &wholepart);
837 /* Try to get out cheap if this fits in a Python int. The attempt
838 * to cast to long must be protected, as C doesn't define what
839 * happens if the double is too big to fit in a long. Some rare
840 * systems raise an exception then (RISCOS was mentioned as one,
841 * and someone using a non-default option on Sun also bumped into
842 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
843 * still be vulnerable: if a long has more bits of precision than
844 * a double, casting MIN/MAX to double may yield an approximation,
845 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
846 * yield true from the C expression wholepart<=LONG_MAX, despite
847 * that wholepart is actually greater than LONG_MAX.
848 */
849 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
850 const long aslong = (long)wholepart;
851 return PyLong_FromLong(aslong);
852 }
853 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000854}
855
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000856/* double_round: rounds a finite double to the closest multiple of
857 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
858 ndigits <= 323). Returns a Python float, or sets a Python error and
859 returns NULL on failure (OverflowError and memory errors are possible). */
860
861#ifndef PY_NO_SHORT_FLOAT_REPR
862/* version of double_round that uses the correctly-rounded string<->double
863 conversions from Python/dtoa.c */
864
865static PyObject *
866double_round(double x, int ndigits) {
867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 double rounded;
869 Py_ssize_t buflen, mybuflen=100;
870 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
871 int decpt, sign;
872 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000873 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000876 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000878 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (buf == NULL) {
880 PyErr_NoMemory();
881 return NULL;
882 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
885 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
886 buflen = buf_end - buf;
887 if (buflen + 8 > mybuflen) {
888 mybuflen = buflen+8;
889 mybuf = (char *)PyMem_Malloc(mybuflen);
890 if (mybuf == NULL) {
891 PyErr_NoMemory();
892 goto exit;
893 }
894 }
895 /* copy buf to mybuf, adding exponent, sign and leading 0 */
896 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
897 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* and convert the resulting string back to a double */
900 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000901 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000903 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (errno == ERANGE && fabs(rounded) >= 1.)
905 PyErr_SetString(PyExc_OverflowError,
906 "rounded value too large to represent");
907 else
908 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* done computing value; now clean up */
911 if (mybuf != shortbuf)
912 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000913 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 _Py_dg_freedtoa(buf);
915 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916}
917
918#else /* PY_NO_SHORT_FLOAT_REPR */
919
920/* fallback version, to be used when correctly rounded binary<->decimal
921 conversions aren't available */
922
923static PyObject *
924double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 double pow1, pow2, y, z;
926 if (ndigits >= 0) {
927 if (ndigits > 22) {
928 /* pow1 and pow2 are each safe from overflow, but
929 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
930 pow1 = pow(10.0, (double)(ndigits-22));
931 pow2 = 1e22;
932 }
933 else {
934 pow1 = pow(10.0, (double)ndigits);
935 pow2 = 1.0;
936 }
937 y = (x*pow1)*pow2;
938 /* if y overflows, then rounded value is exactly x */
939 if (!Py_IS_FINITE(y))
940 return PyFloat_FromDouble(x);
941 }
942 else {
943 pow1 = pow(10.0, (double)-ndigits);
944 pow2 = 1.0; /* unused; silences a gcc compiler warning */
945 y = x / pow1;
946 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 z = round(y);
949 if (fabs(y-z) == 0.5)
950 /* halfway between two integers; use round-half-even */
951 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (ndigits >= 0)
954 z = (z / pow2) / pow1;
955 else
956 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* if computation resulted in overflow, raise OverflowError */
959 if (!Py_IS_FINITE(z)) {
960 PyErr_SetString(PyExc_OverflowError,
961 "overflow occurred during round");
962 return NULL;
963 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000966}
967
968#endif /* PY_NO_SHORT_FLOAT_REPR */
969
970/* round a Python float v to the closest multiple of 10**-ndigits */
971
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000972static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000973float_round(PyObject *v, PyObject *args)
974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 double x, rounded;
976 PyObject *o_ndigits = NULL;
977 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 x = PyFloat_AsDouble(v);
980 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
981 return NULL;
982 if (o_ndigits == NULL) {
983 /* single-argument round: round to nearest integer */
984 rounded = round(x);
985 if (fabs(x-rounded) == 0.5)
986 /* halfway case: round to even */
987 rounded = 2.0*round(x/2.0);
988 return PyLong_FromDouble(rounded);
989 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* interpret second argument as a Py_ssize_t; clips on overflow */
992 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
993 if (ndigits == -1 && PyErr_Occurred())
994 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 /* nans and infinities round to themselves */
997 if (!Py_IS_FINITE(x))
998 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1001 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1002 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1004#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (ndigits > NDIGITS_MAX)
1006 /* return x */
1007 return PyFloat_FromDouble(x);
1008 else if (ndigits < NDIGITS_MIN)
1009 /* return 0.0, but with sign of x */
1010 return PyFloat_FromDouble(0.0*x);
1011 else
1012 /* finite x, and ndigits is not unreasonably large */
1013 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001014#undef NDIGITS_MAX
1015#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001016}
1017
1018static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001019float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (PyFloat_CheckExact(v))
1022 Py_INCREF(v);
1023 else
1024 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1025 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001026}
1027
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001028/* turn ASCII hex characters into integer values and vice versa */
1029
1030static char
1031char_from_hex(int x)
1032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001034 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001035}
1036
1037static int
1038hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 int x;
1040 switch(c) {
1041 case '0':
1042 x = 0;
1043 break;
1044 case '1':
1045 x = 1;
1046 break;
1047 case '2':
1048 x = 2;
1049 break;
1050 case '3':
1051 x = 3;
1052 break;
1053 case '4':
1054 x = 4;
1055 break;
1056 case '5':
1057 x = 5;
1058 break;
1059 case '6':
1060 x = 6;
1061 break;
1062 case '7':
1063 x = 7;
1064 break;
1065 case '8':
1066 x = 8;
1067 break;
1068 case '9':
1069 x = 9;
1070 break;
1071 case 'a':
1072 case 'A':
1073 x = 10;
1074 break;
1075 case 'b':
1076 case 'B':
1077 x = 11;
1078 break;
1079 case 'c':
1080 case 'C':
1081 x = 12;
1082 break;
1083 case 'd':
1084 case 'D':
1085 x = 13;
1086 break;
1087 case 'e':
1088 case 'E':
1089 x = 14;
1090 break;
1091 case 'f':
1092 case 'F':
1093 x = 15;
1094 break;
1095 default:
1096 x = -1;
1097 break;
1098 }
1099 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001100}
1101
1102/* convert a float to a hexadecimal string */
1103
1104/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1105 of the form 4k+1. */
1106#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1107
1108static PyObject *
1109float_hex(PyObject *v)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 double x, m;
1112 int e, shift, i, si, esign;
1113 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1114 trailing NUL byte. */
1115 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001120 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001123 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 return PyUnicode_FromString("-0x0.0p+0");
1125 else
1126 return PyUnicode_FromString("0x0.0p+0");
1127 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001130 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 m = ldexp(m, shift);
1132 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 si = 0;
1135 s[si] = char_from_hex((int)m);
1136 si++;
1137 m -= (int)m;
1138 s[si] = '.';
1139 si++;
1140 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1141 m *= 16.0;
1142 s[si] = char_from_hex((int)m);
1143 si++;
1144 m -= (int)m;
1145 }
1146 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (e < 0) {
1149 esign = (int)'-';
1150 e = -e;
1151 }
1152 else
1153 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (x < 0.0)
1156 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1157 else
1158 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001159}
1160
1161PyDoc_STRVAR(float_hex_doc,
1162"float.hex() -> string\n\
1163\n\
1164Return a hexadecimal representation of a floating-point number.\n\
1165>>> (-0.1).hex()\n\
1166'-0x1.999999999999ap-4'\n\
1167>>> 3.14159.hex()\n\
1168'0x1.921f9f01b866ep+1'");
1169
1170/* Convert a hexadecimal string to a float. */
1171
1172static PyObject *
1173float_fromhex(PyObject *cls, PyObject *arg)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *result_as_float, *result;
1176 double x;
1177 long exp, top_exp, lsb, key_digit;
1178 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1179 int half_eps, digit, round_up, negate=0;
1180 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /*
1183 * For the sake of simplicity and correctness, we impose an artificial
1184 * limit on ndigits, the total number of hex digits in the coefficient
1185 * The limit is chosen to ensure that, writing exp for the exponent,
1186 *
1187 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1188 * guaranteed to overflow (provided it's nonzero)
1189 *
1190 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1191 * guaranteed to underflow to 0.
1192 *
1193 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1194 * overflow in the calculation of exp and top_exp below.
1195 *
1196 * More specifically, ndigits is assumed to satisfy the following
1197 * inequalities:
1198 *
1199 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1200 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1201 *
1202 * If either of these inequalities is not satisfied, a ValueError is
1203 * raised. Otherwise, write x for the value of the hex string, and
1204 * assume x is nonzero. Then
1205 *
1206 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1207 *
1208 * Now if exp > LONG_MAX/2 then:
1209 *
1210 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1211 * = DBL_MAX_EXP
1212 *
1213 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1214 * double, so overflows. If exp < LONG_MIN/2, then
1215 *
1216 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1217 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1218 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1219 *
1220 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1221 * when converted to a C double.
1222 *
1223 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1224 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1225 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 s = _PyUnicode_AsStringAndSize(arg, &length);
1228 if (s == NULL)
1229 return NULL;
1230 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /********************
1233 * Parse the string *
1234 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /* leading whitespace */
1237 while (Py_ISSPACE(*s))
1238 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* infinities and nans */
1241 x = _Py_parse_inf_or_nan(s, &coeff_end);
1242 if (coeff_end != s) {
1243 s = coeff_end;
1244 goto finished;
1245 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 /* optional sign */
1248 if (*s == '-') {
1249 s++;
1250 negate = 1;
1251 }
1252 else if (*s == '+')
1253 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /* [0x] */
1256 s_store = s;
1257 if (*s == '0') {
1258 s++;
1259 if (*s == 'x' || *s == 'X')
1260 s++;
1261 else
1262 s = s_store;
1263 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 /* coefficient: <integer> [. <fraction>] */
1266 coeff_start = s;
1267 while (hex_from_char(*s) >= 0)
1268 s++;
1269 s_store = s;
1270 if (*s == '.') {
1271 s++;
1272 while (hex_from_char(*s) >= 0)
1273 s++;
1274 coeff_end = s-1;
1275 }
1276 else
1277 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* ndigits = total # of hex digits; fdigits = # after point */
1280 ndigits = coeff_end - coeff_start;
1281 fdigits = coeff_end - s_store;
1282 if (ndigits == 0)
1283 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001284 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1285 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* [p <exponent>] */
1289 if (*s == 'p' || *s == 'P') {
1290 s++;
1291 exp_start = s;
1292 if (*s == '-' || *s == '+')
1293 s++;
1294 if (!('0' <= *s && *s <= '9'))
1295 goto parse_error;
1296 s++;
1297 while ('0' <= *s && *s <= '9')
1298 s++;
1299 exp = strtol(exp_start, NULL, 10);
1300 }
1301 else
1302 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1306 coeff_end-(j) : \
1307 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /*******************************************
1310 * Compute rounded value of the hex string *
1311 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 /* Discard leading zeros, and catch extreme overflow and underflow */
1314 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1315 ndigits--;
1316 if (ndigits == 0 || exp < LONG_MIN/2) {
1317 x = 0.0;
1318 goto finished;
1319 }
1320 if (exp > LONG_MAX/2)
1321 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* Adjust exponent for fractional part. */
1324 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1327 top_exp = exp + 4*((long)ndigits - 1);
1328 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1329 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* catch almost all nonextreme cases of overflow and underflow here */
1332 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1333 x = 0.0;
1334 goto finished;
1335 }
1336 if (top_exp > DBL_MAX_EXP)
1337 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* lsb = exponent of least significant bit of the *rounded* value.
1340 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001341 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 x = 0.0;
1344 if (exp >= lsb) {
1345 /* no rounding required */
1346 for (i = ndigits-1; i >= 0; i--)
1347 x = 16.0*x + HEX_DIGIT(i);
1348 x = ldexp(x, (int)(exp));
1349 goto finished;
1350 }
1351 /* rounding required. key_digit is the index of the hex digit
1352 containing the first bit to be rounded away. */
1353 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1354 key_digit = (lsb - exp - 1) / 4;
1355 for (i = ndigits-1; i > key_digit; i--)
1356 x = 16.0*x + HEX_DIGIT(i);
1357 digit = HEX_DIGIT(key_digit);
1358 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1361 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1362 if ((digit & half_eps) != 0) {
1363 round_up = 0;
1364 if ((digit & (3*half_eps-1)) != 0 ||
1365 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1366 round_up = 1;
1367 else
1368 for (i = key_digit-1; i >= 0; i--)
1369 if (HEX_DIGIT(i) != 0) {
1370 round_up = 1;
1371 break;
1372 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001373 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 x += 2*half_eps;
1375 if (top_exp == DBL_MAX_EXP &&
1376 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1377 /* overflow corner case: pre-rounded value <
1378 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1379 goto overflow_error;
1380 }
1381 }
1382 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001383
1384 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 /* optional trailing whitespace leading to the end of the string */
1386 while (Py_ISSPACE(*s))
1387 s++;
1388 if (s != s_end)
1389 goto parse_error;
1390 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1391 if (result_as_float == NULL)
1392 return NULL;
1393 result = PyObject_CallObject(cls, result_as_float);
1394 Py_DECREF(result_as_float);
1395 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
1397 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyErr_SetString(PyExc_OverflowError,
1399 "hexadecimal value too large to represent as a float");
1400 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001401
1402 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 PyErr_SetString(PyExc_ValueError,
1404 "invalid hexadecimal floating-point string");
1405 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406
1407 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyErr_SetString(PyExc_ValueError,
1409 "hexadecimal string too long to convert");
1410 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001411}
1412
1413PyDoc_STRVAR(float_fromhex_doc,
1414"float.fromhex(string) -> float\n\
1415\n\
1416Create a floating-point number from a hexadecimal string.\n\
1417>>> float.fromhex('0x1.ffffp10')\n\
14182047.984375\n\
1419>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001420-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001421
1422
Christian Heimes26855632008-01-27 23:50:43 +00001423static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001424float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 double self;
1427 double float_part;
1428 int exponent;
1429 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyObject *prev;
1432 PyObject *py_exponent = NULL;
1433 PyObject *numerator = NULL;
1434 PyObject *denominator = NULL;
1435 PyObject *result_pair = NULL;
1436 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001437
1438#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 prev = obj; \
1440 obj = call; \
1441 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (Py_IS_INFINITY(self)) {
1446 PyErr_SetString(PyExc_OverflowError,
1447 "Cannot pass infinity to float.as_integer_ratio.");
1448 return NULL;
1449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (Py_IS_NAN(self)) {
1451 PyErr_SetString(PyExc_ValueError,
1452 "Cannot pass NaN to float.as_integer_ratio.");
1453 return NULL;
1454 }
Christian Heimes26855632008-01-27 23:50:43 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1457 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1458 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1461 float_part *= 2.0;
1462 exponent--;
1463 }
1464 /* self == float_part * 2**exponent exactly and float_part is integral.
1465 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1466 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 numerator = PyLong_FromDouble(float_part);
1469 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 /* fold in 2**exponent */
1472 denominator = PyLong_FromLong(1);
1473 py_exponent = PyLong_FromLong(labs((long)exponent));
1474 if (py_exponent == NULL) goto error;
1475 INPLACE_UPDATE(py_exponent,
1476 long_methods->nb_lshift(denominator, py_exponent));
1477 if (py_exponent == NULL) goto error;
1478 if (exponent > 0) {
1479 INPLACE_UPDATE(numerator,
1480 long_methods->nb_multiply(numerator, py_exponent));
1481 if (numerator == NULL) goto error;
1482 }
1483 else {
1484 Py_DECREF(denominator);
1485 denominator = py_exponent;
1486 py_exponent = NULL;
1487 }
1488
1489 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001490
1491#undef INPLACE_UPDATE
1492error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 Py_XDECREF(py_exponent);
1494 Py_XDECREF(denominator);
1495 Py_XDECREF(numerator);
1496 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001497}
1498
1499PyDoc_STRVAR(float_as_integer_ratio_doc,
1500"float.as_integer_ratio() -> (int, int)\n"
1501"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001502"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001503"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001504"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001505"\n"
1506">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001507"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001508">>> (0.0).as_integer_ratio()\n"
1509"(0, 1)\n"
1510">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001511"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001512
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001513
Jeremy Hylton938ace62002-07-17 16:30:39 +00001514static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001515float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1516
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517static PyObject *
1518float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 PyObject *x = Py_False; /* Integer zero */
1521 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (type != &PyFloat_Type)
1524 return float_subtype_new(type, args, kwds); /* Wimp out */
1525 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1526 return NULL;
1527 /* If it's a string, but not a string subclass, use
1528 PyFloat_FromString. */
1529 if (PyUnicode_CheckExact(x))
1530 return PyFloat_FromString(x);
1531 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532}
1533
Guido van Rossumbef14172001-08-29 15:47:46 +00001534/* Wimpy, slow approach to tp_new calls for subtypes of float:
1535 first create a regular float from whatever arguments we got,
1536 then allocate a subtype instance and initialize its ob_fval
1537 from the regular float. The regular float is then thrown away.
1538*/
1539static PyObject *
1540float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 assert(PyType_IsSubtype(type, &PyFloat_Type));
1545 tmp = float_new(&PyFloat_Type, args, kwds);
1546 if (tmp == NULL)
1547 return NULL;
1548 assert(PyFloat_CheckExact(tmp));
1549 newobj = type->tp_alloc(type, 0);
1550 if (newobj == NULL) {
1551 Py_DECREF(tmp);
1552 return NULL;
1553 }
1554 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1555 Py_DECREF(tmp);
1556 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001557}
1558
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001559static PyObject *
1560float_getnewargs(PyFloatObject *v)
1561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001563}
1564
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001565/* this is for the benefit of the pack/unpack routines below */
1566
1567typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001569} float_format_type;
1570
1571static float_format_type double_format, float_format;
1572static float_format_type detected_double_format, detected_float_format;
1573
1574static PyObject *
1575float_getformat(PyTypeObject *v, PyObject* arg)
1576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 char* s;
1578 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (!PyUnicode_Check(arg)) {
1581 PyErr_Format(PyExc_TypeError,
1582 "__getformat__() argument must be string, not %.500s",
1583 Py_TYPE(arg)->tp_name);
1584 return NULL;
1585 }
1586 s = _PyUnicode_AsString(arg);
1587 if (s == NULL)
1588 return NULL;
1589 if (strcmp(s, "double") == 0) {
1590 r = double_format;
1591 }
1592 else if (strcmp(s, "float") == 0) {
1593 r = float_format;
1594 }
1595 else {
1596 PyErr_SetString(PyExc_ValueError,
1597 "__getformat__() argument 1 must be "
1598 "'double' or 'float'");
1599 return NULL;
1600 }
1601
1602 switch (r) {
1603 case unknown_format:
1604 return PyUnicode_FromString("unknown");
1605 case ieee_little_endian_format:
1606 return PyUnicode_FromString("IEEE, little-endian");
1607 case ieee_big_endian_format:
1608 return PyUnicode_FromString("IEEE, big-endian");
1609 default:
1610 Py_FatalError("insane float_format or double_format");
1611 return NULL;
1612 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613}
1614
1615PyDoc_STRVAR(float_getformat_doc,
1616"float.__getformat__(typestr) -> string\n"
1617"\n"
1618"You probably don't want to use this function. It exists mainly to be\n"
1619"used in Python's test suite.\n"
1620"\n"
1621"typestr must be 'double' or 'float'. This function returns whichever of\n"
1622"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1623"format of floating point numbers used by the C type named by typestr.");
1624
1625static PyObject *
1626float_setformat(PyTypeObject *v, PyObject* args)
1627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 char* typestr;
1629 char* format;
1630 float_format_type f;
1631 float_format_type detected;
1632 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1635 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (strcmp(typestr, "double") == 0) {
1638 p = &double_format;
1639 detected = detected_double_format;
1640 }
1641 else if (strcmp(typestr, "float") == 0) {
1642 p = &float_format;
1643 detected = detected_float_format;
1644 }
1645 else {
1646 PyErr_SetString(PyExc_ValueError,
1647 "__setformat__() argument 1 must "
1648 "be 'double' or 'float'");
1649 return NULL;
1650 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (strcmp(format, "unknown") == 0) {
1653 f = unknown_format;
1654 }
1655 else if (strcmp(format, "IEEE, little-endian") == 0) {
1656 f = ieee_little_endian_format;
1657 }
1658 else if (strcmp(format, "IEEE, big-endian") == 0) {
1659 f = ieee_big_endian_format;
1660 }
1661 else {
1662 PyErr_SetString(PyExc_ValueError,
1663 "__setformat__() argument 2 must be "
1664 "'unknown', 'IEEE, little-endian' or "
1665 "'IEEE, big-endian'");
1666 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (f != unknown_format && f != detected) {
1671 PyErr_Format(PyExc_ValueError,
1672 "can only set %s format to 'unknown' or the "
1673 "detected platform value", typestr);
1674 return NULL;
1675 }
1676
1677 *p = f;
1678 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001679}
1680
1681PyDoc_STRVAR(float_setformat_doc,
1682"float.__setformat__(typestr, fmt) -> None\n"
1683"\n"
1684"You probably don't want to use this function. It exists mainly to be\n"
1685"used in Python's test suite.\n"
1686"\n"
1687"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1688"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1689"one of the latter two if it appears to match the underlying C reality.\n"
1690"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001691"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001692"This affects how floats are converted to and from binary strings.");
1693
Guido van Rossumb43daf72007-08-01 18:08:08 +00001694static PyObject *
1695float_getzero(PyObject *v, void *closure)
1696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001698}
1699
Eric Smith8c663262007-08-25 02:26:07 +00001700static PyObject *
1701float__format__(PyObject *self, PyObject *args)
1702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001704 _PyUnicodeWriter writer;
1705 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1708 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001709
Victor Stinner8f674cc2013-04-17 23:02:17 +02001710 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001711 ret = _PyFloat_FormatAdvancedWriter(
1712 &writer,
1713 self,
1714 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1715 if (ret == -1) {
1716 _PyUnicodeWriter_Dealloc(&writer);
1717 return NULL;
1718 }
1719 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001720}
1721
1722PyDoc_STRVAR(float__format__doc,
1723"float.__format__(format_spec) -> string\n"
1724"\n"
1725"Formats the float according to format_spec.");
1726
1727
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001728static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001730 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001732 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001734 "Return the Integral closest to x, rounding half toward even.\n"
1735 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1737 float_as_integer_ratio_doc},
1738 {"fromhex", (PyCFunction)float_fromhex,
1739 METH_O|METH_CLASS, float_fromhex_doc},
1740 {"hex", (PyCFunction)float_hex,
1741 METH_NOARGS, float_hex_doc},
1742 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001743 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001744#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001746 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001748 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001750 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001751#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1753 {"__getformat__", (PyCFunction)float_getformat,
1754 METH_O|METH_CLASS, float_getformat_doc},
1755 {"__setformat__", (PyCFunction)float_setformat,
1756 METH_VARARGS|METH_CLASS, float_setformat_doc},
1757 {"__format__", (PyCFunction)float__format__,
1758 METH_VARARGS, float__format__doc},
1759 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001760};
1761
Guido van Rossumb43daf72007-08-01 18:08:08 +00001762static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001764 (getter)float_float, (setter)NULL,
1765 "the real part of a complex number",
1766 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001768 (getter)float_getzero, (setter)NULL,
1769 "the imaginary part of a complex number",
1770 NULL},
1771 {NULL} /* Sentinel */
1772};
1773
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001774PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775"float(x) -> floating point number\n\
1776\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001777Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778
1779
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001780static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 float_add, /*nb_add*/
1782 float_sub, /*nb_subtract*/
1783 float_mul, /*nb_multiply*/
1784 float_rem, /*nb_remainder*/
1785 float_divmod, /*nb_divmod*/
1786 float_pow, /*nb_power*/
1787 (unaryfunc)float_neg, /*nb_negative*/
1788 (unaryfunc)float_float, /*nb_positive*/
1789 (unaryfunc)float_abs, /*nb_absolute*/
1790 (inquiry)float_bool, /*nb_bool*/
1791 0, /*nb_invert*/
1792 0, /*nb_lshift*/
1793 0, /*nb_rshift*/
1794 0, /*nb_and*/
1795 0, /*nb_xor*/
1796 0, /*nb_or*/
1797 float_trunc, /*nb_int*/
1798 0, /*nb_reserved*/
1799 float_float, /*nb_float*/
1800 0, /* nb_inplace_add */
1801 0, /* nb_inplace_subtract */
1802 0, /* nb_inplace_multiply */
1803 0, /* nb_inplace_remainder */
1804 0, /* nb_inplace_power */
1805 0, /* nb_inplace_lshift */
1806 0, /* nb_inplace_rshift */
1807 0, /* nb_inplace_and */
1808 0, /* nb_inplace_xor */
1809 0, /* nb_inplace_or */
1810 float_floor_div, /* nb_floor_divide */
1811 float_div, /* nb_true_divide */
1812 0, /* nb_inplace_floor_divide */
1813 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001814};
1815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001816PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1818 "float",
1819 sizeof(PyFloatObject),
1820 0,
1821 (destructor)float_dealloc, /* tp_dealloc */
1822 0, /* tp_print */
1823 0, /* tp_getattr */
1824 0, /* tp_setattr */
1825 0, /* tp_reserved */
1826 (reprfunc)float_repr, /* tp_repr */
1827 &float_as_number, /* tp_as_number */
1828 0, /* tp_as_sequence */
1829 0, /* tp_as_mapping */
1830 (hashfunc)float_hash, /* tp_hash */
1831 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001832 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyObject_GenericGetAttr, /* tp_getattro */
1834 0, /* tp_setattro */
1835 0, /* tp_as_buffer */
1836 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1837 float_doc, /* tp_doc */
1838 0, /* tp_traverse */
1839 0, /* tp_clear */
1840 float_richcompare, /* tp_richcompare */
1841 0, /* tp_weaklistoffset */
1842 0, /* tp_iter */
1843 0, /* tp_iternext */
1844 float_methods, /* tp_methods */
1845 0, /* tp_members */
1846 float_getset, /* tp_getset */
1847 0, /* tp_base */
1848 0, /* tp_dict */
1849 0, /* tp_descr_get */
1850 0, /* tp_descr_set */
1851 0, /* tp_dictoffset */
1852 0, /* tp_init */
1853 0, /* tp_alloc */
1854 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001856
Victor Stinner1c8f0592013-07-22 22:24:54 +02001857int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001858_PyFloat_Init(void)
1859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* We attempt to determine if this machine is using IEEE
1861 floating point formats by peering at the bits of some
1862 carefully chosen values. If it looks like we are on an
1863 IEEE platform, the float packing/unpacking routines can
1864 just copy bits, if not they resort to arithmetic & shifts
1865 and masks. The shifts & masks approach works on all finite
1866 values, but what happens to infinities, NaNs and signed
1867 zeroes on packing is an accident, and attempting to unpack
1868 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 Note that if we're on some whacked-out platform which uses
1871 IEEE formats but isn't strictly little-endian or big-
1872 endian, we will fall back to the portable shifts & masks
1873 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001874
1875#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 {
1877 double x = 9006104071832581.0;
1878 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1879 detected_double_format = ieee_big_endian_format;
1880 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1881 detected_double_format = ieee_little_endian_format;
1882 else
1883 detected_double_format = unknown_format;
1884 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001885#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887#endif
1888
1889#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 {
1891 float y = 16711938.0;
1892 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1893 detected_float_format = ieee_big_endian_format;
1894 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1895 detected_float_format = ieee_little_endian_format;
1896 else
1897 detected_float_format = unknown_format;
1898 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001899#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901#endif
1902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 double_format = detected_double_format;
1904 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001907 if (FloatInfoType.tp_name == NULL) {
1908 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1909 return 0;
1910 }
1911 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001912}
1913
Georg Brandl2ee470f2008-07-16 12:55:28 +00001914int
1915PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001916{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001917 PyFloatObject *f = free_list, *next;
1918 int i = numfree;
1919 while (f) {
1920 next = (PyFloatObject*) Py_TYPE(f);
1921 PyObject_FREE(f);
1922 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001924 free_list = NULL;
1925 numfree = 0;
1926 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001927}
1928
1929void
1930PyFloat_Fini(void)
1931{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001932 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001933}
Tim Peters9905b942003-03-20 20:53:32 +00001934
David Malcolm49526f42012-06-22 14:55:41 -04001935/* Print summary info about the state of the optimized allocator */
1936void
1937_PyFloat_DebugMallocStats(FILE *out)
1938{
1939 _PyDebugAllocatorStats(out,
1940 "free PyFloatObject",
1941 numfree, sizeof(PyFloatObject));
1942}
1943
1944
Tim Peters9905b942003-03-20 20:53:32 +00001945/*----------------------------------------------------------------------------
1946 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001947 */
1948int
1949_PyFloat_Pack4(double x, unsigned char *p, int le)
1950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 if (float_format == unknown_format) {
1952 unsigned char sign;
1953 int e;
1954 double f;
1955 unsigned int fbits;
1956 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (le) {
1959 p += 3;
1960 incr = -1;
1961 }
Tim Peters9905b942003-03-20 20:53:32 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (x < 0) {
1964 sign = 1;
1965 x = -x;
1966 }
1967 else
1968 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 /* Normalize f to be in the range [1.0, 2.0) */
1973 if (0.5 <= f && f < 1.0) {
1974 f *= 2.0;
1975 e--;
1976 }
1977 else if (f == 0.0)
1978 e = 0;
1979 else {
1980 PyErr_SetString(PyExc_SystemError,
1981 "frexp() result out of range");
1982 return -1;
1983 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (e >= 128)
1986 goto Overflow;
1987 else if (e < -126) {
1988 /* Gradual underflow */
1989 f = ldexp(f, 126 + e);
1990 e = 0;
1991 }
1992 else if (!(e == 0 && f == 0.0)) {
1993 e += 127;
1994 f -= 1.0; /* Get rid of leading 1 */
1995 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 f *= 8388608.0; /* 2**23 */
1998 fbits = (unsigned int)(f + 0.5); /* Round */
1999 assert(fbits <= 8388608);
2000 if (fbits >> 23) {
2001 /* The carry propagated out of a string of 23 1 bits. */
2002 fbits = 0;
2003 ++e;
2004 if (e >= 255)
2005 goto Overflow;
2006 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 /* First byte */
2009 *p = (sign << 7) | (e >> 1);
2010 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* Second byte */
2013 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2014 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* Third byte */
2017 *p = (fbits >> 8) & 0xFF;
2018 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Fourth byte */
2021 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 /* Done */
2024 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 }
2027 else {
2028 float y = (float)x;
2029 const char *s = (char*)&y;
2030 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2033 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if ((float_format == ieee_little_endian_format && !le)
2036 || (float_format == ieee_big_endian_format && le)) {
2037 p += 3;
2038 incr = -1;
2039 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 for (i = 0; i < 4; i++) {
2042 *p = *s++;
2043 p += incr;
2044 }
2045 return 0;
2046 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002047 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 PyErr_SetString(PyExc_OverflowError,
2049 "float too large to pack with f format");
2050 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002051}
2052
2053int
2054_PyFloat_Pack8(double x, unsigned char *p, int le)
2055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (double_format == unknown_format) {
2057 unsigned char sign;
2058 int e;
2059 double f;
2060 unsigned int fhi, flo;
2061 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (le) {
2064 p += 7;
2065 incr = -1;
2066 }
Tim Peters9905b942003-03-20 20:53:32 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (x < 0) {
2069 sign = 1;
2070 x = -x;
2071 }
2072 else
2073 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 /* Normalize f to be in the range [1.0, 2.0) */
2078 if (0.5 <= f && f < 1.0) {
2079 f *= 2.0;
2080 e--;
2081 }
2082 else if (f == 0.0)
2083 e = 0;
2084 else {
2085 PyErr_SetString(PyExc_SystemError,
2086 "frexp() result out of range");
2087 return -1;
2088 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (e >= 1024)
2091 goto Overflow;
2092 else if (e < -1022) {
2093 /* Gradual underflow */
2094 f = ldexp(f, 1022 + e);
2095 e = 0;
2096 }
2097 else if (!(e == 0 && f == 0.0)) {
2098 e += 1023;
2099 f -= 1.0; /* Get rid of leading 1 */
2100 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2103 f *= 268435456.0; /* 2**28 */
2104 fhi = (unsigned int)f; /* Truncate */
2105 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 f -= (double)fhi;
2108 f *= 16777216.0; /* 2**24 */
2109 flo = (unsigned int)(f + 0.5); /* Round */
2110 assert(flo <= 16777216);
2111 if (flo >> 24) {
2112 /* The carry propagated out of a string of 24 1 bits. */
2113 flo = 0;
2114 ++fhi;
2115 if (fhi >> 28) {
2116 /* And it also progagated out of the next 28 bits. */
2117 fhi = 0;
2118 ++e;
2119 if (e >= 2047)
2120 goto Overflow;
2121 }
2122 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* First byte */
2125 *p = (sign << 7) | (e >> 4);
2126 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* Second byte */
2129 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2130 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* Third byte */
2133 *p = (fhi >> 16) & 0xFF;
2134 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* Fourth byte */
2137 *p = (fhi >> 8) & 0xFF;
2138 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 /* Fifth byte */
2141 *p = fhi & 0xFF;
2142 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 /* Sixth byte */
2145 *p = (flo >> 16) & 0xFF;
2146 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* Seventh byte */
2149 *p = (flo >> 8) & 0xFF;
2150 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 /* Eighth byte */
2153 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002154 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 /* Done */
2157 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 Overflow:
2160 PyErr_SetString(PyExc_OverflowError,
2161 "float too large to pack with d format");
2162 return -1;
2163 }
2164 else {
2165 const char *s = (char*)&x;
2166 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if ((double_format == ieee_little_endian_format && !le)
2169 || (double_format == ieee_big_endian_format && le)) {
2170 p += 7;
2171 incr = -1;
2172 }
2173
2174 for (i = 0; i < 8; i++) {
2175 *p = *s++;
2176 p += incr;
2177 }
2178 return 0;
2179 }
Tim Peters9905b942003-03-20 20:53:32 +00002180}
2181
2182double
2183_PyFloat_Unpack4(const unsigned char *p, int le)
2184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (float_format == unknown_format) {
2186 unsigned char sign;
2187 int e;
2188 unsigned int f;
2189 double x;
2190 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (le) {
2193 p += 3;
2194 incr = -1;
2195 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* First byte */
2198 sign = (*p >> 7) & 1;
2199 e = (*p & 0x7F) << 1;
2200 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* Second byte */
2203 e |= (*p >> 7) & 1;
2204 f = (*p & 0x7F) << 16;
2205 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (e == 255) {
2208 PyErr_SetString(
2209 PyExc_ValueError,
2210 "can't unpack IEEE 754 special value "
2211 "on non-IEEE platform");
2212 return -1;
2213 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* Third byte */
2216 f |= *p << 8;
2217 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* Fourth byte */
2220 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* XXX This sadly ignores Inf/NaN issues */
2225 if (e == 0)
2226 e = -126;
2227 else {
2228 x += 1.0;
2229 e -= 127;
2230 }
2231 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (sign)
2234 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 return x;
2237 }
2238 else {
2239 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if ((float_format == ieee_little_endian_format && !le)
2242 || (float_format == ieee_big_endian_format && le)) {
2243 char buf[4];
2244 char *d = &buf[3];
2245 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 for (i = 0; i < 4; i++) {
2248 *d-- = *p++;
2249 }
2250 memcpy(&x, buf, 4);
2251 }
2252 else {
2253 memcpy(&x, p, 4);
2254 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 return x;
2257 }
Tim Peters9905b942003-03-20 20:53:32 +00002258}
2259
2260double
2261_PyFloat_Unpack8(const unsigned char *p, int le)
2262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if (double_format == unknown_format) {
2264 unsigned char sign;
2265 int e;
2266 unsigned int fhi, flo;
2267 double x;
2268 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (le) {
2271 p += 7;
2272 incr = -1;
2273 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 /* First byte */
2276 sign = (*p >> 7) & 1;
2277 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 /* Second byte */
2282 e |= (*p >> 4) & 0xF;
2283 fhi = (*p & 0xF) << 24;
2284 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (e == 2047) {
2287 PyErr_SetString(
2288 PyExc_ValueError,
2289 "can't unpack IEEE 754 special value "
2290 "on non-IEEE platform");
2291 return -1.0;
2292 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Third byte */
2295 fhi |= *p << 16;
2296 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* Fourth byte */
2299 fhi |= *p << 8;
2300 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Fifth byte */
2303 fhi |= *p;
2304 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Sixth byte */
2307 flo = *p << 16;
2308 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Seventh byte */
2311 flo |= *p << 8;
2312 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Eighth byte */
2315 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2318 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 if (e == 0)
2321 e = -1022;
2322 else {
2323 x += 1.0;
2324 e -= 1023;
2325 }
2326 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (sign)
2329 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 return x;
2332 }
2333 else {
2334 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if ((double_format == ieee_little_endian_format && !le)
2337 || (double_format == ieee_big_endian_format && le)) {
2338 char buf[8];
2339 char *d = &buf[7];
2340 int i;
2341
2342 for (i = 0; i < 8; i++) {
2343 *d-- = *p++;
2344 }
2345 memcpy(&x, buf, 8);
2346 }
2347 else {
2348 memcpy(&x, p, 8);
2349 }
2350
2351 return x;
2352 }
Tim Peters9905b942003-03-20 20:53:32 +00002353}