blob: d6819814ef8334d93c0d175340b9b10da1afeaa2 [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;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200134 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200138 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000140 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200141 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000142 if (s == NULL) {
143 Py_DECREF(s_buffer);
144 return NULL;
145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200147 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
148 s = (const char *)view.buf;
149 len = view.len;
150 }
151 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200152 PyErr_Format(PyExc_TypeError,
153 "float() argument must be a string or a number, not '%.200s'",
154 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 return NULL;
156 }
157 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000158 /* strip space */
159 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000161 while (s < last - 1 && Py_ISSPACE(last[-1]))
162 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 /* We don't care about overflow or underflow. If the platform
164 * supports them, infinities and signed zeroes (on underflow) are
165 * fine. */
166 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000167 if (end != last) {
168 PyErr_Format(PyExc_ValueError,
169 "could not convert string to float: "
170 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 result = NULL;
172 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000173 else if (x == -1.0 && PyErr_Occurred())
174 result = NULL;
175 else
176 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000177
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200178 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000179 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181}
182
Guido van Rossum234f9421993-06-17 12:35:49 +0000183static void
Fred Drakefd99de62000-07-09 05:02:18 +0000184float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000187 if (numfree >= PyFloat_MAXFREELIST) {
188 PyObject_FREE(op);
189 return;
190 }
191 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 Py_TYPE(op) = (struct _typeobject *)free_list;
193 free_list = op;
194 }
195 else
196 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000197}
198
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199double
Fred Drakefd99de62000-07-09 05:02:18 +0000200PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 PyNumberMethods *nb;
203 PyFloatObject *fo;
204 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (op && PyFloat_Check(op))
207 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (op == NULL) {
210 PyErr_BadArgument();
211 return -1;
212 }
Tim Petersd2364e82001-11-01 20:09:42 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
215 PyErr_SetString(PyExc_TypeError, "a float is required");
216 return -1;
217 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 fo = (PyFloatObject*) (*nb->nb_float) (op);
220 if (fo == NULL)
221 return -1;
222 if (!PyFloat_Check(fo)) {
Benjamin Petersona9157232015-03-06 09:08:44 -0500223 Py_DECREF(fo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyErr_SetString(PyExc_TypeError,
225 "nb_float should return float object");
226 return -1;
227 }
Tim Petersd2364e82001-11-01 20:09:42 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 val = PyFloat_AS_DOUBLE(fo);
230 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233}
234
Neil Schemenauer32117e52001-01-04 01:44:34 +0000235/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000236 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000237 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300238 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000239 stored in obj, and returned from the function invoking this macro.
240*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241#define CONVERT_TO_DOUBLE(obj, dbl) \
242 if (PyFloat_Check(obj)) \
243 dbl = PyFloat_AS_DOUBLE(obj); \
244 else if (convert_to_double(&(obj), &(dbl)) < 0) \
245 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000246
Eric Smith0923d1d2009-04-16 20:16:10 +0000247/* Methods */
248
Neil Schemenauer32117e52001-01-04 01:44:34 +0000249static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000250convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000251{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200252 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (PyLong_Check(obj)) {
255 *dbl = PyLong_AsDouble(obj);
256 if (*dbl == -1.0 && PyErr_Occurred()) {
257 *v = NULL;
258 return -1;
259 }
260 }
261 else {
262 Py_INCREF(Py_NotImplemented);
263 *v = Py_NotImplemented;
264 return -1;
265 }
266 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000267}
268
Eric Smith0923d1d2009-04-16 20:16:10 +0000269static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000270float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000271{
272 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200273 char *buf;
274
275 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
276 'r', 0,
277 Py_DTSF_ADD_DOT_0,
278 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000279 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000280 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200281 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000282 PyMem_Free(buf);
283 return result;
284}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000285
Tim Peters307fa782004-09-23 08:06:40 +0000286/* Comparison is pretty much a nightmare. When comparing float to float,
287 * we do it as straightforwardly (and long-windedly) as conceivable, so
288 * that, e.g., Python x == y delivers the same result as the platform
289 * C x == y when x and/or y is a NaN.
290 * When mixing float with an integer type, there's no good *uniform* approach.
291 * Converting the double to an integer obviously doesn't work, since we
292 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300293 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000294 * 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 +0200295 * 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 +0000296 * 63 bits of precision, but a C double probably has only 53), and then
297 * we can falsely claim equality when low-order integer bits are lost by
298 * coercion to double. So this part is painful too.
299 */
300
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000301static PyObject*
302float_richcompare(PyObject *v, PyObject *w, int op)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 double i, j;
305 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 assert(PyFloat_Check(v));
308 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 /* Switch on the type of w. Set i and j to doubles to be compared,
311 * and op to the richcomp to use.
312 */
313 if (PyFloat_Check(w))
314 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 else if (!Py_IS_FINITE(i)) {
317 if (PyLong_Check(w))
318 /* If i is an infinity, its magnitude exceeds any
319 * finite integer, so it doesn't matter which int we
320 * compare i with. If i is a NaN, similarly.
321 */
322 j = 0.0;
323 else
324 goto Unimplemented;
325 }
Tim Peters307fa782004-09-23 08:06:40 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 else if (PyLong_Check(w)) {
328 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
329 int wsign = _PyLong_Sign(w);
330 size_t nbits;
331 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (vsign != wsign) {
334 /* Magnitudes are irrelevant -- the signs alone
335 * determine the outcome.
336 */
337 i = (double)vsign;
338 j = (double)wsign;
339 goto Compare;
340 }
341 /* The signs are the same. */
342 /* Convert w to a double if it fits. In particular, 0 fits. */
343 nbits = _PyLong_NumBits(w);
344 if (nbits == (size_t)-1 && PyErr_Occurred()) {
345 /* This long is so large that size_t isn't big enough
346 * to hold the # of bits. Replace with little doubles
347 * that give the same outcome -- w is so large that
348 * its magnitude must exceed the magnitude of any
349 * finite float.
350 */
351 PyErr_Clear();
352 i = (double)vsign;
353 assert(wsign != 0);
354 j = wsign * 2.0;
355 goto Compare;
356 }
357 if (nbits <= 48) {
358 j = PyLong_AsDouble(w);
359 /* It's impossible that <= 48 bits overflowed. */
360 assert(j != -1.0 || ! PyErr_Occurred());
361 goto Compare;
362 }
363 assert(wsign != 0); /* else nbits was 0 */
364 assert(vsign != 0); /* if vsign were 0, then since wsign is
365 * not 0, we would have taken the
366 * vsign != wsign branch at the start */
367 /* We want to work with non-negative numbers. */
368 if (vsign < 0) {
369 /* "Multiply both sides" by -1; this also swaps the
370 * comparator.
371 */
372 i = -i;
373 op = _Py_SwappedOp[op];
374 }
375 assert(i > 0.0);
376 (void) frexp(i, &exponent);
377 /* exponent is the # of bits in v before the radix point;
378 * we know that nbits (the # of bits in w) > 48 at this point
379 */
380 if (exponent < 0 || (size_t)exponent < nbits) {
381 i = 1.0;
382 j = 2.0;
383 goto Compare;
384 }
385 if ((size_t)exponent > nbits) {
386 i = 2.0;
387 j = 1.0;
388 goto Compare;
389 }
390 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300391 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 * outcome.
393 */
394 {
395 double fracpart;
396 double intpart;
397 PyObject *result = NULL;
398 PyObject *one = NULL;
399 PyObject *vv = NULL;
400 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (wsign < 0) {
403 ww = PyNumber_Negative(w);
404 if (ww == NULL)
405 goto Error;
406 }
407 else
408 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 fracpart = modf(i, &intpart);
411 vv = PyLong_FromDouble(intpart);
412 if (vv == NULL)
413 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (fracpart != 0.0) {
416 /* Shift left, and or a 1 bit into vv
417 * to represent the lost fraction.
418 */
419 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 one = PyLong_FromLong(1);
422 if (one == NULL)
423 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 temp = PyNumber_Lshift(ww, one);
426 if (temp == NULL)
427 goto Error;
428 Py_DECREF(ww);
429 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 temp = PyNumber_Lshift(vv, one);
432 if (temp == NULL)
433 goto Error;
434 Py_DECREF(vv);
435 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 temp = PyNumber_Or(vv, one);
438 if (temp == NULL)
439 goto Error;
440 Py_DECREF(vv);
441 vv = temp;
442 }
Tim Peters307fa782004-09-23 08:06:40 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 r = PyObject_RichCompareBool(vv, ww, op);
445 if (r < 0)
446 goto Error;
447 result = PyBool_FromLong(r);
448 Error:
449 Py_XDECREF(vv);
450 Py_XDECREF(ww);
451 Py_XDECREF(one);
452 return result;
453 }
454 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000455
Serhiy Storchaka95949422013-08-27 19:40:23 +0300456 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000458
459 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyFPE_START_PROTECT("richcompare", return NULL)
461 switch (op) {
462 case Py_EQ:
463 r = i == j;
464 break;
465 case Py_NE:
466 r = i != j;
467 break;
468 case Py_LE:
469 r = i <= j;
470 break;
471 case Py_GE:
472 r = i >= j;
473 break;
474 case Py_LT:
475 r = i < j;
476 break;
477 case Py_GT:
478 r = i > j;
479 break;
480 }
481 PyFPE_END_PROTECT(r)
482 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000483
484 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500485 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000486}
487
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000488static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000489float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000492}
493
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000495float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 double a,b;
498 CONVERT_TO_DOUBLE(v, a);
499 CONVERT_TO_DOUBLE(w, b);
500 PyFPE_START_PROTECT("add", return 0)
501 a = a + b;
502 PyFPE_END_PROTECT(a)
503 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000504}
505
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000507float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 double a,b;
510 CONVERT_TO_DOUBLE(v, a);
511 CONVERT_TO_DOUBLE(w, b);
512 PyFPE_START_PROTECT("subtract", return 0)
513 a = a - b;
514 PyFPE_END_PROTECT(a)
515 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516}
517
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000519float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 double a,b;
522 CONVERT_TO_DOUBLE(v, a);
523 CONVERT_TO_DOUBLE(w, b);
524 PyFPE_START_PROTECT("multiply", return 0)
525 a = a * b;
526 PyFPE_END_PROTECT(a)
527 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528}
529
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000531float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 double a,b;
534 CONVERT_TO_DOUBLE(v, a);
535 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (b == 0.0) {
537 PyErr_SetString(PyExc_ZeroDivisionError,
538 "float division by zero");
539 return NULL;
540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyFPE_START_PROTECT("divide", return 0)
542 a = a / b;
543 PyFPE_END_PROTECT(a)
544 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545}
546
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000548float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 double vx, wx;
551 double mod;
552 CONVERT_TO_DOUBLE(v, vx);
553 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (wx == 0.0) {
555 PyErr_SetString(PyExc_ZeroDivisionError,
556 "float modulo");
557 return NULL;
558 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 PyFPE_START_PROTECT("modulo", return 0)
560 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000561 if (mod) {
562 /* ensure the remainder has the same sign as the denominator */
563 if ((wx < 0) != (mod < 0)) {
564 mod += wx;
565 }
566 }
567 else {
568 /* the remainder is zero, and in the presence of signed zeroes
569 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000570 it has the same sign as the denominator. */
571 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 }
573 PyFPE_END_PROTECT(mod)
574 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575}
576
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000578float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 double vx, wx;
581 double div, mod, floordiv;
582 CONVERT_TO_DOUBLE(v, vx);
583 CONVERT_TO_DOUBLE(w, wx);
584 if (wx == 0.0) {
585 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
586 return NULL;
587 }
588 PyFPE_START_PROTECT("divmod", return 0)
589 mod = fmod(vx, wx);
590 /* fmod is typically exact, so vx-mod is *mathematically* an
591 exact multiple of wx. But this is fp arithmetic, and fp
592 vx - mod is an approximation; the result is that div may
593 not be an exact integral value after the division, although
594 it will always be very close to one.
595 */
596 div = (vx - mod) / wx;
597 if (mod) {
598 /* ensure the remainder has the same sign as the denominator */
599 if ((wx < 0) != (mod < 0)) {
600 mod += wx;
601 div -= 1.0;
602 }
603 }
604 else {
605 /* the remainder is zero, and in the presence of signed zeroes
606 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000607 it has the same sign as the denominator. */
608 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 }
610 /* snap quotient to nearest integral value */
611 if (div) {
612 floordiv = floor(div);
613 if (div - floordiv > 0.5)
614 floordiv += 1.0;
615 }
616 else {
617 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000618 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 }
620 PyFPE_END_PROTECT(floordiv)
621 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000622}
623
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000625float_floor_div(PyObject *v, PyObject *w)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 t = float_divmod(v, w);
630 if (t == NULL || t == Py_NotImplemented)
631 return t;
632 assert(PyTuple_CheckExact(t));
633 r = PyTuple_GET_ITEM(t, 0);
634 Py_INCREF(r);
635 Py_DECREF(t);
636 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000637}
638
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000639/* determine whether x is an odd integer or not; assumes that
640 x is not an infinity or nan. */
641#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
642
Tim Peters63a35712001-12-11 19:57:24 +0000643static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000644float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 double iv, iw, ix;
647 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if ((PyObject *)z != Py_None) {
650 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
651 "allowed unless all arguments are integers");
652 return NULL;
653 }
Tim Peters32f453e2001-09-03 08:35:41 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 CONVERT_TO_DOUBLE(v, iv);
656 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 /* Sort out special cases here instead of relying on pow() */
659 if (iw == 0) { /* v**0 is 1, even 0**0 */
660 return PyFloat_FromDouble(1.0);
661 }
662 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
663 return PyFloat_FromDouble(iv);
664 }
665 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
666 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
667 }
668 if (Py_IS_INFINITY(iw)) {
669 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
670 * abs(v) > 1 (including case where v infinite)
671 *
672 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
673 * abs(v) > 1 (including case where v infinite)
674 */
675 iv = fabs(iv);
676 if (iv == 1.0)
677 return PyFloat_FromDouble(1.0);
678 else if ((iw > 0.0) == (iv > 1.0))
679 return PyFloat_FromDouble(fabs(iw)); /* return inf */
680 else
681 return PyFloat_FromDouble(0.0);
682 }
683 if (Py_IS_INFINITY(iv)) {
684 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
685 * both cases, we need to add the appropriate sign if w is
686 * an odd integer.
687 */
688 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
689 if (iw > 0.0)
690 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
691 else
692 return PyFloat_FromDouble(iw_is_odd ?
693 copysign(0.0, iv) : 0.0);
694 }
695 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
696 (already dealt with above), and an error
697 if w is negative. */
698 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
699 if (iw < 0.0) {
700 PyErr_SetString(PyExc_ZeroDivisionError,
701 "0.0 cannot be raised to a "
702 "negative power");
703 return NULL;
704 }
705 /* use correct sign if iw is odd */
706 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
707 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (iv < 0.0) {
710 /* Whether this is an error is a mess, and bumps into libm
711 * bugs so we have to figure it out ourselves.
712 */
713 if (iw != floor(iw)) {
714 /* Negative numbers raised to fractional powers
715 * become complex.
716 */
717 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
718 }
719 /* iw is an exact integer, albeit perhaps a very large
720 * one. Replace iv by its absolute value and remember
721 * to negate the pow result if iw is odd.
722 */
723 iv = -iv;
724 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
725 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
728 /* (-1) ** large_integer also ends up here. Here's an
729 * extract from the comments for the previous
730 * implementation explaining why this special case is
731 * necessary:
732 *
733 * -1 raised to an exact integer should never be exceptional.
734 * Alas, some libms (chiefly glibc as of early 2003) return
735 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
736 * happen to be representable in a *C* integer. That's a
737 * bug.
738 */
739 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
740 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* Now iv and iw are finite, iw is nonzero, and iv is
743 * positive and not equal to 1.0. We finally allow
744 * the platform pow to step in and do the rest.
745 */
746 errno = 0;
747 PyFPE_START_PROTECT("pow", return NULL)
748 ix = pow(iv, iw);
749 PyFPE_END_PROTECT(ix)
750 Py_ADJUST_ERANGE1(ix);
751 if (negate_result)
752 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (errno != 0) {
755 /* We don't expect any errno value other than ERANGE, but
756 * the range of libm bugs appears unbounded.
757 */
758 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
759 PyExc_ValueError);
760 return NULL;
761 }
762 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763}
764
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000765#undef DOUBLE_IS_ODD_INTEGER
766
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000768float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771}
772
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000774float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777}
778
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000779static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000780float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000783}
784
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000785static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000786float_is_integer(PyObject *v)
787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 double x = PyFloat_AsDouble(v);
789 PyObject *o;
790
791 if (x == -1.0 && PyErr_Occurred())
792 return NULL;
793 if (!Py_IS_FINITE(x))
794 Py_RETURN_FALSE;
795 errno = 0;
796 PyFPE_START_PROTECT("is_integer", return NULL)
797 o = (floor(x) == x) ? Py_True : Py_False;
798 PyFPE_END_PROTECT(x)
799 if (errno != 0) {
800 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
801 PyExc_ValueError);
802 return NULL;
803 }
804 Py_INCREF(o);
805 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000806}
807
808#if 0
809static PyObject *
810float_is_inf(PyObject *v)
811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 double x = PyFloat_AsDouble(v);
813 if (x == -1.0 && PyErr_Occurred())
814 return NULL;
815 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000816}
817
818static PyObject *
819float_is_nan(PyObject *v)
820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 double x = PyFloat_AsDouble(v);
822 if (x == -1.0 && PyErr_Occurred())
823 return NULL;
824 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000825}
826
827static PyObject *
828float_is_finite(PyObject *v)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 double x = PyFloat_AsDouble(v);
831 if (x == -1.0 && PyErr_Occurred())
832 return NULL;
833 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000834}
835#endif
836
837static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000838float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 double x = PyFloat_AsDouble(v);
841 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 (void)modf(x, &wholepart);
844 /* Try to get out cheap if this fits in a Python int. The attempt
845 * to cast to long must be protected, as C doesn't define what
846 * happens if the double is too big to fit in a long. Some rare
847 * systems raise an exception then (RISCOS was mentioned as one,
848 * and someone using a non-default option on Sun also bumped into
849 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
850 * still be vulnerable: if a long has more bits of precision than
851 * a double, casting MIN/MAX to double may yield an approximation,
852 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
853 * yield true from the C expression wholepart<=LONG_MAX, despite
854 * that wholepart is actually greater than LONG_MAX.
855 */
856 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
857 const long aslong = (long)wholepart;
858 return PyLong_FromLong(aslong);
859 }
860 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000861}
862
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000863/* double_round: rounds a finite double to the closest multiple of
864 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
865 ndigits <= 323). Returns a Python float, or sets a Python error and
866 returns NULL on failure (OverflowError and memory errors are possible). */
867
868#ifndef PY_NO_SHORT_FLOAT_REPR
869/* version of double_round that uses the correctly-rounded string<->double
870 conversions from Python/dtoa.c */
871
872static PyObject *
873double_round(double x, int ndigits) {
874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 double rounded;
876 Py_ssize_t buflen, mybuflen=100;
877 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
878 int decpt, sign;
879 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000880 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000883 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000885 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (buf == NULL) {
887 PyErr_NoMemory();
888 return NULL;
889 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
892 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
893 buflen = buf_end - buf;
894 if (buflen + 8 > mybuflen) {
895 mybuflen = buflen+8;
896 mybuf = (char *)PyMem_Malloc(mybuflen);
897 if (mybuf == NULL) {
898 PyErr_NoMemory();
899 goto exit;
900 }
901 }
902 /* copy buf to mybuf, adding exponent, sign and leading 0 */
903 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
904 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* and convert the resulting string back to a double */
907 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000908 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000910 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (errno == ERANGE && fabs(rounded) >= 1.)
912 PyErr_SetString(PyExc_OverflowError,
913 "rounded value too large to represent");
914 else
915 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* done computing value; now clean up */
918 if (mybuf != shortbuf)
919 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000920 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 _Py_dg_freedtoa(buf);
922 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000923}
924
925#else /* PY_NO_SHORT_FLOAT_REPR */
926
927/* fallback version, to be used when correctly rounded binary<->decimal
928 conversions aren't available */
929
930static PyObject *
931double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 double pow1, pow2, y, z;
933 if (ndigits >= 0) {
934 if (ndigits > 22) {
935 /* pow1 and pow2 are each safe from overflow, but
936 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
937 pow1 = pow(10.0, (double)(ndigits-22));
938 pow2 = 1e22;
939 }
940 else {
941 pow1 = pow(10.0, (double)ndigits);
942 pow2 = 1.0;
943 }
944 y = (x*pow1)*pow2;
945 /* if y overflows, then rounded value is exactly x */
946 if (!Py_IS_FINITE(y))
947 return PyFloat_FromDouble(x);
948 }
949 else {
950 pow1 = pow(10.0, (double)-ndigits);
951 pow2 = 1.0; /* unused; silences a gcc compiler warning */
952 y = x / pow1;
953 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 z = round(y);
956 if (fabs(y-z) == 0.5)
957 /* halfway between two integers; use round-half-even */
958 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (ndigits >= 0)
961 z = (z / pow2) / pow1;
962 else
963 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* if computation resulted in overflow, raise OverflowError */
966 if (!Py_IS_FINITE(z)) {
967 PyErr_SetString(PyExc_OverflowError,
968 "overflow occurred during round");
969 return NULL;
970 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000973}
974
975#endif /* PY_NO_SHORT_FLOAT_REPR */
976
977/* round a Python float v to the closest multiple of 10**-ndigits */
978
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000979static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000980float_round(PyObject *v, PyObject *args)
981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 double x, rounded;
983 PyObject *o_ndigits = NULL;
984 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 x = PyFloat_AsDouble(v);
987 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
988 return NULL;
Steve Dowercb39d1f2015-04-15 16:10:59 -0400989 if (o_ndigits == NULL || o_ndigits == Py_None) {
990 /* single-argument round or with None ndigits:
991 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 rounded = round(x);
993 if (fabs(x-rounded) == 0.5)
994 /* halfway case: round to even */
995 rounded = 2.0*round(x/2.0);
996 return PyLong_FromDouble(rounded);
997 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* interpret second argument as a Py_ssize_t; clips on overflow */
1000 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1001 if (ndigits == -1 && PyErr_Occurred())
1002 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 /* nans and infinities round to themselves */
1005 if (!Py_IS_FINITE(x))
1006 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1009 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1010 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001011#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1012#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (ndigits > NDIGITS_MAX)
1014 /* return x */
1015 return PyFloat_FromDouble(x);
1016 else if (ndigits < NDIGITS_MIN)
1017 /* return 0.0, but with sign of x */
1018 return PyFloat_FromDouble(0.0*x);
1019 else
1020 /* finite x, and ndigits is not unreasonably large */
1021 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001022#undef NDIGITS_MAX
1023#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001024}
1025
1026static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001027float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (PyFloat_CheckExact(v))
1030 Py_INCREF(v);
1031 else
1032 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1033 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001034}
1035
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001036/* turn ASCII hex characters into integer values and vice versa */
1037
1038static char
1039char_from_hex(int x)
1040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001042 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001043}
1044
1045static int
1046hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 int x;
1048 switch(c) {
1049 case '0':
1050 x = 0;
1051 break;
1052 case '1':
1053 x = 1;
1054 break;
1055 case '2':
1056 x = 2;
1057 break;
1058 case '3':
1059 x = 3;
1060 break;
1061 case '4':
1062 x = 4;
1063 break;
1064 case '5':
1065 x = 5;
1066 break;
1067 case '6':
1068 x = 6;
1069 break;
1070 case '7':
1071 x = 7;
1072 break;
1073 case '8':
1074 x = 8;
1075 break;
1076 case '9':
1077 x = 9;
1078 break;
1079 case 'a':
1080 case 'A':
1081 x = 10;
1082 break;
1083 case 'b':
1084 case 'B':
1085 x = 11;
1086 break;
1087 case 'c':
1088 case 'C':
1089 x = 12;
1090 break;
1091 case 'd':
1092 case 'D':
1093 x = 13;
1094 break;
1095 case 'e':
1096 case 'E':
1097 x = 14;
1098 break;
1099 case 'f':
1100 case 'F':
1101 x = 15;
1102 break;
1103 default:
1104 x = -1;
1105 break;
1106 }
1107 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001108}
1109
1110/* convert a float to a hexadecimal string */
1111
1112/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1113 of the form 4k+1. */
1114#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1115
1116static PyObject *
1117float_hex(PyObject *v)
1118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 double x, m;
1120 int e, shift, i, si, esign;
1121 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1122 trailing NUL byte. */
1123 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001128 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001131 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 return PyUnicode_FromString("-0x0.0p+0");
1133 else
1134 return PyUnicode_FromString("0x0.0p+0");
1135 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001138 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 m = ldexp(m, shift);
1140 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 si = 0;
1143 s[si] = char_from_hex((int)m);
1144 si++;
1145 m -= (int)m;
1146 s[si] = '.';
1147 si++;
1148 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1149 m *= 16.0;
1150 s[si] = char_from_hex((int)m);
1151 si++;
1152 m -= (int)m;
1153 }
1154 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (e < 0) {
1157 esign = (int)'-';
1158 e = -e;
1159 }
1160 else
1161 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (x < 0.0)
1164 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1165 else
1166 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001167}
1168
1169PyDoc_STRVAR(float_hex_doc,
1170"float.hex() -> string\n\
1171\n\
1172Return a hexadecimal representation of a floating-point number.\n\
1173>>> (-0.1).hex()\n\
1174'-0x1.999999999999ap-4'\n\
1175>>> 3.14159.hex()\n\
1176'0x1.921f9f01b866ep+1'");
1177
1178/* Convert a hexadecimal string to a float. */
1179
1180static PyObject *
1181float_fromhex(PyObject *cls, PyObject *arg)
1182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyObject *result_as_float, *result;
1184 double x;
1185 long exp, top_exp, lsb, key_digit;
1186 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1187 int half_eps, digit, round_up, negate=0;
1188 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 /*
1191 * For the sake of simplicity and correctness, we impose an artificial
1192 * limit on ndigits, the total number of hex digits in the coefficient
1193 * The limit is chosen to ensure that, writing exp for the exponent,
1194 *
1195 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1196 * guaranteed to overflow (provided it's nonzero)
1197 *
1198 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1199 * guaranteed to underflow to 0.
1200 *
1201 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1202 * overflow in the calculation of exp and top_exp below.
1203 *
1204 * More specifically, ndigits is assumed to satisfy the following
1205 * inequalities:
1206 *
1207 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1208 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1209 *
1210 * If either of these inequalities is not satisfied, a ValueError is
1211 * raised. Otherwise, write x for the value of the hex string, and
1212 * assume x is nonzero. Then
1213 *
1214 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1215 *
1216 * Now if exp > LONG_MAX/2 then:
1217 *
1218 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1219 * = DBL_MAX_EXP
1220 *
1221 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1222 * double, so overflows. If exp < LONG_MIN/2, then
1223 *
1224 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1225 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1226 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1227 *
1228 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1229 * when converted to a C double.
1230 *
1231 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1232 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1233 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 s = _PyUnicode_AsStringAndSize(arg, &length);
1236 if (s == NULL)
1237 return NULL;
1238 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /********************
1241 * Parse the string *
1242 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 /* leading whitespace */
1245 while (Py_ISSPACE(*s))
1246 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 /* infinities and nans */
1249 x = _Py_parse_inf_or_nan(s, &coeff_end);
1250 if (coeff_end != s) {
1251 s = coeff_end;
1252 goto finished;
1253 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /* optional sign */
1256 if (*s == '-') {
1257 s++;
1258 negate = 1;
1259 }
1260 else if (*s == '+')
1261 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* [0x] */
1264 s_store = s;
1265 if (*s == '0') {
1266 s++;
1267 if (*s == 'x' || *s == 'X')
1268 s++;
1269 else
1270 s = s_store;
1271 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* coefficient: <integer> [. <fraction>] */
1274 coeff_start = s;
1275 while (hex_from_char(*s) >= 0)
1276 s++;
1277 s_store = s;
1278 if (*s == '.') {
1279 s++;
1280 while (hex_from_char(*s) >= 0)
1281 s++;
1282 coeff_end = s-1;
1283 }
1284 else
1285 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* ndigits = total # of hex digits; fdigits = # after point */
1288 ndigits = coeff_end - coeff_start;
1289 fdigits = coeff_end - s_store;
1290 if (ndigits == 0)
1291 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001292 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1293 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 /* [p <exponent>] */
1297 if (*s == 'p' || *s == 'P') {
1298 s++;
1299 exp_start = s;
1300 if (*s == '-' || *s == '+')
1301 s++;
1302 if (!('0' <= *s && *s <= '9'))
1303 goto parse_error;
1304 s++;
1305 while ('0' <= *s && *s <= '9')
1306 s++;
1307 exp = strtol(exp_start, NULL, 10);
1308 }
1309 else
1310 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001311
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001312/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1314 coeff_end-(j) : \
1315 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /*******************************************
1318 * Compute rounded value of the hex string *
1319 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* Discard leading zeros, and catch extreme overflow and underflow */
1322 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1323 ndigits--;
1324 if (ndigits == 0 || exp < LONG_MIN/2) {
1325 x = 0.0;
1326 goto finished;
1327 }
1328 if (exp > LONG_MAX/2)
1329 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* Adjust exponent for fractional part. */
1332 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1335 top_exp = exp + 4*((long)ndigits - 1);
1336 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1337 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* catch almost all nonextreme cases of overflow and underflow here */
1340 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1341 x = 0.0;
1342 goto finished;
1343 }
1344 if (top_exp > DBL_MAX_EXP)
1345 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* lsb = exponent of least significant bit of the *rounded* value.
1348 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001349 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 x = 0.0;
1352 if (exp >= lsb) {
1353 /* no rounding required */
1354 for (i = ndigits-1; i >= 0; i--)
1355 x = 16.0*x + HEX_DIGIT(i);
1356 x = ldexp(x, (int)(exp));
1357 goto finished;
1358 }
1359 /* rounding required. key_digit is the index of the hex digit
1360 containing the first bit to be rounded away. */
1361 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1362 key_digit = (lsb - exp - 1) / 4;
1363 for (i = ndigits-1; i > key_digit; i--)
1364 x = 16.0*x + HEX_DIGIT(i);
1365 digit = HEX_DIGIT(key_digit);
1366 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1369 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1370 if ((digit & half_eps) != 0) {
1371 round_up = 0;
1372 if ((digit & (3*half_eps-1)) != 0 ||
1373 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1374 round_up = 1;
1375 else
1376 for (i = key_digit-1; i >= 0; i--)
1377 if (HEX_DIGIT(i) != 0) {
1378 round_up = 1;
1379 break;
1380 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001381 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 x += 2*half_eps;
1383 if (top_exp == DBL_MAX_EXP &&
1384 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1385 /* overflow corner case: pre-rounded value <
1386 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1387 goto overflow_error;
1388 }
1389 }
1390 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001391
1392 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 /* optional trailing whitespace leading to the end of the string */
1394 while (Py_ISSPACE(*s))
1395 s++;
1396 if (s != s_end)
1397 goto parse_error;
1398 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1399 if (result_as_float == NULL)
1400 return NULL;
1401 result = PyObject_CallObject(cls, result_as_float);
1402 Py_DECREF(result_as_float);
1403 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001404
1405 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyErr_SetString(PyExc_OverflowError,
1407 "hexadecimal value too large to represent as a float");
1408 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001409
1410 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 PyErr_SetString(PyExc_ValueError,
1412 "invalid hexadecimal floating-point string");
1413 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001414
1415 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyErr_SetString(PyExc_ValueError,
1417 "hexadecimal string too long to convert");
1418 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001419}
1420
1421PyDoc_STRVAR(float_fromhex_doc,
1422"float.fromhex(string) -> float\n\
1423\n\
1424Create a floating-point number from a hexadecimal string.\n\
1425>>> float.fromhex('0x1.ffffp10')\n\
14262047.984375\n\
1427>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001428-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001429
1430
Christian Heimes26855632008-01-27 23:50:43 +00001431static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001432float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 double self;
1435 double float_part;
1436 int exponent;
1437 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyObject *prev;
1440 PyObject *py_exponent = NULL;
1441 PyObject *numerator = NULL;
1442 PyObject *denominator = NULL;
1443 PyObject *result_pair = NULL;
1444 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001445
1446#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 prev = obj; \
1448 obj = call; \
1449 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (Py_IS_INFINITY(self)) {
1454 PyErr_SetString(PyExc_OverflowError,
1455 "Cannot pass infinity to float.as_integer_ratio.");
1456 return NULL;
1457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (Py_IS_NAN(self)) {
1459 PyErr_SetString(PyExc_ValueError,
1460 "Cannot pass NaN to float.as_integer_ratio.");
1461 return NULL;
1462 }
Christian Heimes26855632008-01-27 23:50:43 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1465 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1466 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1469 float_part *= 2.0;
1470 exponent--;
1471 }
1472 /* self == float_part * 2**exponent exactly and float_part is integral.
1473 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1474 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 numerator = PyLong_FromDouble(float_part);
1477 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 /* fold in 2**exponent */
1480 denominator = PyLong_FromLong(1);
1481 py_exponent = PyLong_FromLong(labs((long)exponent));
1482 if (py_exponent == NULL) goto error;
1483 INPLACE_UPDATE(py_exponent,
1484 long_methods->nb_lshift(denominator, py_exponent));
1485 if (py_exponent == NULL) goto error;
1486 if (exponent > 0) {
1487 INPLACE_UPDATE(numerator,
1488 long_methods->nb_multiply(numerator, py_exponent));
1489 if (numerator == NULL) goto error;
1490 }
1491 else {
1492 Py_DECREF(denominator);
1493 denominator = py_exponent;
1494 py_exponent = NULL;
1495 }
1496
1497 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001498
1499#undef INPLACE_UPDATE
1500error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 Py_XDECREF(py_exponent);
1502 Py_XDECREF(denominator);
1503 Py_XDECREF(numerator);
1504 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001505}
1506
1507PyDoc_STRVAR(float_as_integer_ratio_doc,
1508"float.as_integer_ratio() -> (int, int)\n"
1509"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001510"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001511"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001512"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001513"\n"
1514">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001515"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001516">>> (0.0).as_integer_ratio()\n"
1517"(0, 1)\n"
1518">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001519"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001520
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001521
Jeremy Hylton938ace62002-07-17 16:30:39 +00001522static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001523float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1524
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525static PyObject *
1526float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 PyObject *x = Py_False; /* Integer zero */
1529 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (type != &PyFloat_Type)
1532 return float_subtype_new(type, args, kwds); /* Wimp out */
1533 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1534 return NULL;
1535 /* If it's a string, but not a string subclass, use
1536 PyFloat_FromString. */
1537 if (PyUnicode_CheckExact(x))
1538 return PyFloat_FromString(x);
1539 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540}
1541
Guido van Rossumbef14172001-08-29 15:47:46 +00001542/* Wimpy, slow approach to tp_new calls for subtypes of float:
1543 first create a regular float from whatever arguments we got,
1544 then allocate a subtype instance and initialize its ob_fval
1545 from the regular float. The regular float is then thrown away.
1546*/
1547static PyObject *
1548float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 assert(PyType_IsSubtype(type, &PyFloat_Type));
1553 tmp = float_new(&PyFloat_Type, args, kwds);
1554 if (tmp == NULL)
1555 return NULL;
1556 assert(PyFloat_CheckExact(tmp));
1557 newobj = type->tp_alloc(type, 0);
1558 if (newobj == NULL) {
1559 Py_DECREF(tmp);
1560 return NULL;
1561 }
1562 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1563 Py_DECREF(tmp);
1564 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001565}
1566
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001567static PyObject *
1568float_getnewargs(PyFloatObject *v)
1569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001571}
1572
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001573/* this is for the benefit of the pack/unpack routines below */
1574
1575typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001577} float_format_type;
1578
1579static float_format_type double_format, float_format;
1580static float_format_type detected_double_format, detected_float_format;
1581
1582static PyObject *
1583float_getformat(PyTypeObject *v, PyObject* arg)
1584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 char* s;
1586 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (!PyUnicode_Check(arg)) {
1589 PyErr_Format(PyExc_TypeError,
1590 "__getformat__() argument must be string, not %.500s",
1591 Py_TYPE(arg)->tp_name);
1592 return NULL;
1593 }
1594 s = _PyUnicode_AsString(arg);
1595 if (s == NULL)
1596 return NULL;
1597 if (strcmp(s, "double") == 0) {
1598 r = double_format;
1599 }
1600 else if (strcmp(s, "float") == 0) {
1601 r = float_format;
1602 }
1603 else {
1604 PyErr_SetString(PyExc_ValueError,
1605 "__getformat__() argument 1 must be "
1606 "'double' or 'float'");
1607 return NULL;
1608 }
1609
1610 switch (r) {
1611 case unknown_format:
1612 return PyUnicode_FromString("unknown");
1613 case ieee_little_endian_format:
1614 return PyUnicode_FromString("IEEE, little-endian");
1615 case ieee_big_endian_format:
1616 return PyUnicode_FromString("IEEE, big-endian");
1617 default:
1618 Py_FatalError("insane float_format or double_format");
1619 return NULL;
1620 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621}
1622
1623PyDoc_STRVAR(float_getformat_doc,
1624"float.__getformat__(typestr) -> string\n"
1625"\n"
1626"You probably don't want to use this function. It exists mainly to be\n"
1627"used in Python's test suite.\n"
1628"\n"
1629"typestr must be 'double' or 'float'. This function returns whichever of\n"
1630"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1631"format of floating point numbers used by the C type named by typestr.");
1632
1633static PyObject *
1634float_setformat(PyTypeObject *v, PyObject* args)
1635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 char* typestr;
1637 char* format;
1638 float_format_type f;
1639 float_format_type detected;
1640 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1643 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (strcmp(typestr, "double") == 0) {
1646 p = &double_format;
1647 detected = detected_double_format;
1648 }
1649 else if (strcmp(typestr, "float") == 0) {
1650 p = &float_format;
1651 detected = detected_float_format;
1652 }
1653 else {
1654 PyErr_SetString(PyExc_ValueError,
1655 "__setformat__() argument 1 must "
1656 "be 'double' or 'float'");
1657 return NULL;
1658 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (strcmp(format, "unknown") == 0) {
1661 f = unknown_format;
1662 }
1663 else if (strcmp(format, "IEEE, little-endian") == 0) {
1664 f = ieee_little_endian_format;
1665 }
1666 else if (strcmp(format, "IEEE, big-endian") == 0) {
1667 f = ieee_big_endian_format;
1668 }
1669 else {
1670 PyErr_SetString(PyExc_ValueError,
1671 "__setformat__() argument 2 must be "
1672 "'unknown', 'IEEE, little-endian' or "
1673 "'IEEE, big-endian'");
1674 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (f != unknown_format && f != detected) {
1679 PyErr_Format(PyExc_ValueError,
1680 "can only set %s format to 'unknown' or the "
1681 "detected platform value", typestr);
1682 return NULL;
1683 }
1684
1685 *p = f;
1686 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687}
1688
1689PyDoc_STRVAR(float_setformat_doc,
1690"float.__setformat__(typestr, fmt) -> None\n"
1691"\n"
1692"You probably don't want to use this function. It exists mainly to be\n"
1693"used in Python's test suite.\n"
1694"\n"
1695"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1696"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1697"one of the latter two if it appears to match the underlying C reality.\n"
1698"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001699"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001700"This affects how floats are converted to and from binary strings.");
1701
Guido van Rossumb43daf72007-08-01 18:08:08 +00001702static PyObject *
1703float_getzero(PyObject *v, void *closure)
1704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001706}
1707
Eric Smith8c663262007-08-25 02:26:07 +00001708static PyObject *
1709float__format__(PyObject *self, PyObject *args)
1710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001712 _PyUnicodeWriter writer;
1713 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1716 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717
Victor Stinner8f674cc2013-04-17 23:02:17 +02001718 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 ret = _PyFloat_FormatAdvancedWriter(
1720 &writer,
1721 self,
1722 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1723 if (ret == -1) {
1724 _PyUnicodeWriter_Dealloc(&writer);
1725 return NULL;
1726 }
1727 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001728}
1729
1730PyDoc_STRVAR(float__format__doc,
1731"float.__format__(format_spec) -> string\n"
1732"\n"
1733"Formats the float according to format_spec.");
1734
1735
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001736static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001738 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001740 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001742 "Return the Integral closest to x, rounding half toward even.\n"
1743 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1745 float_as_integer_ratio_doc},
1746 {"fromhex", (PyCFunction)float_fromhex,
1747 METH_O|METH_CLASS, float_fromhex_doc},
1748 {"hex", (PyCFunction)float_hex,
1749 METH_NOARGS, float_hex_doc},
1750 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001751 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001752#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001754 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001756 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001758 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001759#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1761 {"__getformat__", (PyCFunction)float_getformat,
1762 METH_O|METH_CLASS, float_getformat_doc},
1763 {"__setformat__", (PyCFunction)float_setformat,
1764 METH_VARARGS|METH_CLASS, float_setformat_doc},
1765 {"__format__", (PyCFunction)float__format__,
1766 METH_VARARGS, float__format__doc},
1767 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001768};
1769
Guido van Rossumb43daf72007-08-01 18:08:08 +00001770static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001772 (getter)float_float, (setter)NULL,
1773 "the real part of a complex number",
1774 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001776 (getter)float_getzero, (setter)NULL,
1777 "the imaginary part of a complex number",
1778 NULL},
1779 {NULL} /* Sentinel */
1780};
1781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001782PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783"float(x) -> floating point number\n\
1784\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001785Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786
1787
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001788static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 float_add, /*nb_add*/
1790 float_sub, /*nb_subtract*/
1791 float_mul, /*nb_multiply*/
1792 float_rem, /*nb_remainder*/
1793 float_divmod, /*nb_divmod*/
1794 float_pow, /*nb_power*/
1795 (unaryfunc)float_neg, /*nb_negative*/
1796 (unaryfunc)float_float, /*nb_positive*/
1797 (unaryfunc)float_abs, /*nb_absolute*/
1798 (inquiry)float_bool, /*nb_bool*/
1799 0, /*nb_invert*/
1800 0, /*nb_lshift*/
1801 0, /*nb_rshift*/
1802 0, /*nb_and*/
1803 0, /*nb_xor*/
1804 0, /*nb_or*/
1805 float_trunc, /*nb_int*/
1806 0, /*nb_reserved*/
1807 float_float, /*nb_float*/
1808 0, /* nb_inplace_add */
1809 0, /* nb_inplace_subtract */
1810 0, /* nb_inplace_multiply */
1811 0, /* nb_inplace_remainder */
1812 0, /* nb_inplace_power */
1813 0, /* nb_inplace_lshift */
1814 0, /* nb_inplace_rshift */
1815 0, /* nb_inplace_and */
1816 0, /* nb_inplace_xor */
1817 0, /* nb_inplace_or */
1818 float_floor_div, /* nb_floor_divide */
1819 float_div, /* nb_true_divide */
1820 0, /* nb_inplace_floor_divide */
1821 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001822};
1823
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1826 "float",
1827 sizeof(PyFloatObject),
1828 0,
1829 (destructor)float_dealloc, /* tp_dealloc */
1830 0, /* tp_print */
1831 0, /* tp_getattr */
1832 0, /* tp_setattr */
1833 0, /* tp_reserved */
1834 (reprfunc)float_repr, /* tp_repr */
1835 &float_as_number, /* tp_as_number */
1836 0, /* tp_as_sequence */
1837 0, /* tp_as_mapping */
1838 (hashfunc)float_hash, /* tp_hash */
1839 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001840 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyObject_GenericGetAttr, /* tp_getattro */
1842 0, /* tp_setattro */
1843 0, /* tp_as_buffer */
1844 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1845 float_doc, /* tp_doc */
1846 0, /* tp_traverse */
1847 0, /* tp_clear */
1848 float_richcompare, /* tp_richcompare */
1849 0, /* tp_weaklistoffset */
1850 0, /* tp_iter */
1851 0, /* tp_iternext */
1852 float_methods, /* tp_methods */
1853 0, /* tp_members */
1854 float_getset, /* tp_getset */
1855 0, /* tp_base */
1856 0, /* tp_dict */
1857 0, /* tp_descr_get */
1858 0, /* tp_descr_set */
1859 0, /* tp_dictoffset */
1860 0, /* tp_init */
1861 0, /* tp_alloc */
1862 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001863};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001864
Victor Stinner1c8f0592013-07-22 22:24:54 +02001865int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001866_PyFloat_Init(void)
1867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 /* We attempt to determine if this machine is using IEEE
1869 floating point formats by peering at the bits of some
1870 carefully chosen values. If it looks like we are on an
1871 IEEE platform, the float packing/unpacking routines can
1872 just copy bits, if not they resort to arithmetic & shifts
1873 and masks. The shifts & masks approach works on all finite
1874 values, but what happens to infinities, NaNs and signed
1875 zeroes on packing is an accident, and attempting to unpack
1876 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 Note that if we're on some whacked-out platform which uses
1879 IEEE formats but isn't strictly little-endian or big-
1880 endian, we will fall back to the portable shifts & masks
1881 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001882
1883#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 {
1885 double x = 9006104071832581.0;
1886 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1887 detected_double_format = ieee_big_endian_format;
1888 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1889 detected_double_format = ieee_little_endian_format;
1890 else
1891 detected_double_format = unknown_format;
1892 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001893#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001895#endif
1896
1897#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 {
1899 float y = 16711938.0;
1900 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1901 detected_float_format = ieee_big_endian_format;
1902 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1903 detected_float_format = ieee_little_endian_format;
1904 else
1905 detected_float_format = unknown_format;
1906 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001909#endif
1910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 double_format = detected_double_format;
1912 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001915 if (FloatInfoType.tp_name == NULL) {
1916 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1917 return 0;
1918 }
1919 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001920}
1921
Georg Brandl2ee470f2008-07-16 12:55:28 +00001922int
1923PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001924{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001925 PyFloatObject *f = free_list, *next;
1926 int i = numfree;
1927 while (f) {
1928 next = (PyFloatObject*) Py_TYPE(f);
1929 PyObject_FREE(f);
1930 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001932 free_list = NULL;
1933 numfree = 0;
1934 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001935}
1936
1937void
1938PyFloat_Fini(void)
1939{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001940 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001941}
Tim Peters9905b942003-03-20 20:53:32 +00001942
David Malcolm49526f42012-06-22 14:55:41 -04001943/* Print summary info about the state of the optimized allocator */
1944void
1945_PyFloat_DebugMallocStats(FILE *out)
1946{
1947 _PyDebugAllocatorStats(out,
1948 "free PyFloatObject",
1949 numfree, sizeof(PyFloatObject));
1950}
1951
1952
Tim Peters9905b942003-03-20 20:53:32 +00001953/*----------------------------------------------------------------------------
1954 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001955 */
1956int
1957_PyFloat_Pack4(double x, unsigned char *p, int le)
1958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 if (float_format == unknown_format) {
1960 unsigned char sign;
1961 int e;
1962 double f;
1963 unsigned int fbits;
1964 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 if (le) {
1967 p += 3;
1968 incr = -1;
1969 }
Tim Peters9905b942003-03-20 20:53:32 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (x < 0) {
1972 sign = 1;
1973 x = -x;
1974 }
1975 else
1976 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 /* Normalize f to be in the range [1.0, 2.0) */
1981 if (0.5 <= f && f < 1.0) {
1982 f *= 2.0;
1983 e--;
1984 }
1985 else if (f == 0.0)
1986 e = 0;
1987 else {
1988 PyErr_SetString(PyExc_SystemError,
1989 "frexp() result out of range");
1990 return -1;
1991 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (e >= 128)
1994 goto Overflow;
1995 else if (e < -126) {
1996 /* Gradual underflow */
1997 f = ldexp(f, 126 + e);
1998 e = 0;
1999 }
2000 else if (!(e == 0 && f == 0.0)) {
2001 e += 127;
2002 f -= 1.0; /* Get rid of leading 1 */
2003 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 f *= 8388608.0; /* 2**23 */
2006 fbits = (unsigned int)(f + 0.5); /* Round */
2007 assert(fbits <= 8388608);
2008 if (fbits >> 23) {
2009 /* The carry propagated out of a string of 23 1 bits. */
2010 fbits = 0;
2011 ++e;
2012 if (e >= 255)
2013 goto Overflow;
2014 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* First byte */
2017 *p = (sign << 7) | (e >> 1);
2018 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Second byte */
2021 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2022 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Third byte */
2025 *p = (fbits >> 8) & 0xFF;
2026 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* Fourth byte */
2029 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* Done */
2032 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 }
2035 else {
2036 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002037 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2041 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if ((float_format == ieee_little_endian_format && !le)
2044 || (float_format == ieee_big_endian_format && le)) {
2045 p += 3;
2046 incr = -1;
2047 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 for (i = 0; i < 4; i++) {
2050 *p = *s++;
2051 p += incr;
2052 }
2053 return 0;
2054 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002055 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyErr_SetString(PyExc_OverflowError,
2057 "float too large to pack with f format");
2058 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002059}
2060
2061int
2062_PyFloat_Pack8(double x, unsigned char *p, int le)
2063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (double_format == unknown_format) {
2065 unsigned char sign;
2066 int e;
2067 double f;
2068 unsigned int fhi, flo;
2069 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (le) {
2072 p += 7;
2073 incr = -1;
2074 }
Tim Peters9905b942003-03-20 20:53:32 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (x < 0) {
2077 sign = 1;
2078 x = -x;
2079 }
2080 else
2081 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* Normalize f to be in the range [1.0, 2.0) */
2086 if (0.5 <= f && f < 1.0) {
2087 f *= 2.0;
2088 e--;
2089 }
2090 else if (f == 0.0)
2091 e = 0;
2092 else {
2093 PyErr_SetString(PyExc_SystemError,
2094 "frexp() result out of range");
2095 return -1;
2096 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (e >= 1024)
2099 goto Overflow;
2100 else if (e < -1022) {
2101 /* Gradual underflow */
2102 f = ldexp(f, 1022 + e);
2103 e = 0;
2104 }
2105 else if (!(e == 0 && f == 0.0)) {
2106 e += 1023;
2107 f -= 1.0; /* Get rid of leading 1 */
2108 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2111 f *= 268435456.0; /* 2**28 */
2112 fhi = (unsigned int)f; /* Truncate */
2113 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 f -= (double)fhi;
2116 f *= 16777216.0; /* 2**24 */
2117 flo = (unsigned int)(f + 0.5); /* Round */
2118 assert(flo <= 16777216);
2119 if (flo >> 24) {
2120 /* The carry propagated out of a string of 24 1 bits. */
2121 flo = 0;
2122 ++fhi;
2123 if (fhi >> 28) {
2124 /* And it also progagated out of the next 28 bits. */
2125 fhi = 0;
2126 ++e;
2127 if (e >= 2047)
2128 goto Overflow;
2129 }
2130 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* First byte */
2133 *p = (sign << 7) | (e >> 4);
2134 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* Second byte */
2137 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2138 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 /* Third byte */
2141 *p = (fhi >> 16) & 0xFF;
2142 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 /* Fourth byte */
2145 *p = (fhi >> 8) & 0xFF;
2146 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* Fifth byte */
2149 *p = fhi & 0xFF;
2150 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 /* Sixth byte */
2153 *p = (flo >> 16) & 0xFF;
2154 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 /* Seventh byte */
2157 *p = (flo >> 8) & 0xFF;
2158 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* Eighth byte */
2161 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002162 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* Done */
2165 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Overflow:
2168 PyErr_SetString(PyExc_OverflowError,
2169 "float too large to pack with d format");
2170 return -1;
2171 }
2172 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002173 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if ((double_format == ieee_little_endian_format && !le)
2177 || (double_format == ieee_big_endian_format && le)) {
2178 p += 7;
2179 incr = -1;
2180 }
2181
2182 for (i = 0; i < 8; i++) {
2183 *p = *s++;
2184 p += incr;
2185 }
2186 return 0;
2187 }
Tim Peters9905b942003-03-20 20:53:32 +00002188}
2189
2190double
2191_PyFloat_Unpack4(const unsigned char *p, int le)
2192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (float_format == unknown_format) {
2194 unsigned char sign;
2195 int e;
2196 unsigned int f;
2197 double x;
2198 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (le) {
2201 p += 3;
2202 incr = -1;
2203 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* First byte */
2206 sign = (*p >> 7) & 1;
2207 e = (*p & 0x7F) << 1;
2208 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* Second byte */
2211 e |= (*p >> 7) & 1;
2212 f = (*p & 0x7F) << 16;
2213 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (e == 255) {
2216 PyErr_SetString(
2217 PyExc_ValueError,
2218 "can't unpack IEEE 754 special value "
2219 "on non-IEEE platform");
2220 return -1;
2221 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Third byte */
2224 f |= *p << 8;
2225 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Fourth byte */
2228 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* XXX This sadly ignores Inf/NaN issues */
2233 if (e == 0)
2234 e = -126;
2235 else {
2236 x += 1.0;
2237 e -= 127;
2238 }
2239 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (sign)
2242 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 return x;
2245 }
2246 else {
2247 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if ((float_format == ieee_little_endian_format && !le)
2250 || (float_format == ieee_big_endian_format && le)) {
2251 char buf[4];
2252 char *d = &buf[3];
2253 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 for (i = 0; i < 4; i++) {
2256 *d-- = *p++;
2257 }
2258 memcpy(&x, buf, 4);
2259 }
2260 else {
2261 memcpy(&x, p, 4);
2262 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 return x;
2265 }
Tim Peters9905b942003-03-20 20:53:32 +00002266}
2267
2268double
2269_PyFloat_Unpack8(const unsigned char *p, int le)
2270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (double_format == unknown_format) {
2272 unsigned char sign;
2273 int e;
2274 unsigned int fhi, flo;
2275 double x;
2276 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 if (le) {
2279 p += 7;
2280 incr = -1;
2281 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* First byte */
2284 sign = (*p >> 7) & 1;
2285 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* Second byte */
2290 e |= (*p >> 4) & 0xF;
2291 fhi = (*p & 0xF) << 24;
2292 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (e == 2047) {
2295 PyErr_SetString(
2296 PyExc_ValueError,
2297 "can't unpack IEEE 754 special value "
2298 "on non-IEEE platform");
2299 return -1.0;
2300 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Third byte */
2303 fhi |= *p << 16;
2304 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Fourth byte */
2307 fhi |= *p << 8;
2308 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Fifth byte */
2311 fhi |= *p;
2312 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Sixth byte */
2315 flo = *p << 16;
2316 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* Seventh byte */
2319 flo |= *p << 8;
2320 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* Eighth byte */
2323 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2326 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (e == 0)
2329 e = -1022;
2330 else {
2331 x += 1.0;
2332 e -= 1023;
2333 }
2334 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (sign)
2337 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 return x;
2340 }
2341 else {
2342 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if ((double_format == ieee_little_endian_format && !le)
2345 || (double_format == ieee_big_endian_format && le)) {
2346 char buf[8];
2347 char *d = &buf[7];
2348 int i;
2349
2350 for (i = 0; i < 8; i++) {
2351 *d-- = *p++;
2352 }
2353 memcpy(&x, buf, 8);
2354 }
2355 else {
2356 memcpy(&x, p, 8);
2357 }
2358
2359 return x;
2360 }
Tim Peters9905b942003-03-20 20:53:32 +00002361}