blob: 1d369f98beea8ff4ff79c4c2a375cfadc8281206 [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;
989 if (o_ndigits == NULL) {
990 /* single-argument round: round to nearest integer */
991 rounded = round(x);
992 if (fabs(x-rounded) == 0.5)
993 /* halfway case: round to even */
994 rounded = 2.0*round(x/2.0);
995 return PyLong_FromDouble(rounded);
996 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* interpret second argument as a Py_ssize_t; clips on overflow */
999 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1000 if (ndigits == -1 && PyErr_Occurred())
1001 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 /* nans and infinities round to themselves */
1004 if (!Py_IS_FINITE(x))
1005 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1008 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1009 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001010#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1011#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (ndigits > NDIGITS_MAX)
1013 /* return x */
1014 return PyFloat_FromDouble(x);
1015 else if (ndigits < NDIGITS_MIN)
1016 /* return 0.0, but with sign of x */
1017 return PyFloat_FromDouble(0.0*x);
1018 else
1019 /* finite x, and ndigits is not unreasonably large */
1020 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001021#undef NDIGITS_MAX
1022#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001023}
1024
1025static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001026float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (PyFloat_CheckExact(v))
1029 Py_INCREF(v);
1030 else
1031 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1032 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001033}
1034
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001035/* turn ASCII hex characters into integer values and vice versa */
1036
1037static char
1038char_from_hex(int x)
1039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001041 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001042}
1043
1044static int
1045hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 int x;
1047 switch(c) {
1048 case '0':
1049 x = 0;
1050 break;
1051 case '1':
1052 x = 1;
1053 break;
1054 case '2':
1055 x = 2;
1056 break;
1057 case '3':
1058 x = 3;
1059 break;
1060 case '4':
1061 x = 4;
1062 break;
1063 case '5':
1064 x = 5;
1065 break;
1066 case '6':
1067 x = 6;
1068 break;
1069 case '7':
1070 x = 7;
1071 break;
1072 case '8':
1073 x = 8;
1074 break;
1075 case '9':
1076 x = 9;
1077 break;
1078 case 'a':
1079 case 'A':
1080 x = 10;
1081 break;
1082 case 'b':
1083 case 'B':
1084 x = 11;
1085 break;
1086 case 'c':
1087 case 'C':
1088 x = 12;
1089 break;
1090 case 'd':
1091 case 'D':
1092 x = 13;
1093 break;
1094 case 'e':
1095 case 'E':
1096 x = 14;
1097 break;
1098 case 'f':
1099 case 'F':
1100 x = 15;
1101 break;
1102 default:
1103 x = -1;
1104 break;
1105 }
1106 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001107}
1108
1109/* convert a float to a hexadecimal string */
1110
1111/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1112 of the form 4k+1. */
1113#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1114
1115static PyObject *
1116float_hex(PyObject *v)
1117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 double x, m;
1119 int e, shift, i, si, esign;
1120 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1121 trailing NUL byte. */
1122 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001127 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001130 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return PyUnicode_FromString("-0x0.0p+0");
1132 else
1133 return PyUnicode_FromString("0x0.0p+0");
1134 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001137 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 m = ldexp(m, shift);
1139 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 si = 0;
1142 s[si] = char_from_hex((int)m);
1143 si++;
1144 m -= (int)m;
1145 s[si] = '.';
1146 si++;
1147 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1148 m *= 16.0;
1149 s[si] = char_from_hex((int)m);
1150 si++;
1151 m -= (int)m;
1152 }
1153 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (e < 0) {
1156 esign = (int)'-';
1157 e = -e;
1158 }
1159 else
1160 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (x < 0.0)
1163 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1164 else
1165 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001166}
1167
1168PyDoc_STRVAR(float_hex_doc,
1169"float.hex() -> string\n\
1170\n\
1171Return a hexadecimal representation of a floating-point number.\n\
1172>>> (-0.1).hex()\n\
1173'-0x1.999999999999ap-4'\n\
1174>>> 3.14159.hex()\n\
1175'0x1.921f9f01b866ep+1'");
1176
1177/* Convert a hexadecimal string to a float. */
1178
1179static PyObject *
1180float_fromhex(PyObject *cls, PyObject *arg)
1181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 PyObject *result_as_float, *result;
1183 double x;
1184 long exp, top_exp, lsb, key_digit;
1185 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1186 int half_eps, digit, round_up, negate=0;
1187 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 /*
1190 * For the sake of simplicity and correctness, we impose an artificial
1191 * limit on ndigits, the total number of hex digits in the coefficient
1192 * The limit is chosen to ensure that, writing exp for the exponent,
1193 *
1194 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1195 * guaranteed to overflow (provided it's nonzero)
1196 *
1197 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1198 * guaranteed to underflow to 0.
1199 *
1200 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1201 * overflow in the calculation of exp and top_exp below.
1202 *
1203 * More specifically, ndigits is assumed to satisfy the following
1204 * inequalities:
1205 *
1206 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1207 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1208 *
1209 * If either of these inequalities is not satisfied, a ValueError is
1210 * raised. Otherwise, write x for the value of the hex string, and
1211 * assume x is nonzero. Then
1212 *
1213 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1214 *
1215 * Now if exp > LONG_MAX/2 then:
1216 *
1217 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1218 * = DBL_MAX_EXP
1219 *
1220 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1221 * double, so overflows. If exp < LONG_MIN/2, then
1222 *
1223 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1224 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1225 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1226 *
1227 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1228 * when converted to a C double.
1229 *
1230 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1231 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1232 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 s = _PyUnicode_AsStringAndSize(arg, &length);
1235 if (s == NULL)
1236 return NULL;
1237 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /********************
1240 * Parse the string *
1241 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 /* leading whitespace */
1244 while (Py_ISSPACE(*s))
1245 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 /* infinities and nans */
1248 x = _Py_parse_inf_or_nan(s, &coeff_end);
1249 if (coeff_end != s) {
1250 s = coeff_end;
1251 goto finished;
1252 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 /* optional sign */
1255 if (*s == '-') {
1256 s++;
1257 negate = 1;
1258 }
1259 else if (*s == '+')
1260 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 /* [0x] */
1263 s_store = s;
1264 if (*s == '0') {
1265 s++;
1266 if (*s == 'x' || *s == 'X')
1267 s++;
1268 else
1269 s = s_store;
1270 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* coefficient: <integer> [. <fraction>] */
1273 coeff_start = s;
1274 while (hex_from_char(*s) >= 0)
1275 s++;
1276 s_store = s;
1277 if (*s == '.') {
1278 s++;
1279 while (hex_from_char(*s) >= 0)
1280 s++;
1281 coeff_end = s-1;
1282 }
1283 else
1284 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /* ndigits = total # of hex digits; fdigits = # after point */
1287 ndigits = coeff_end - coeff_start;
1288 fdigits = coeff_end - s_store;
1289 if (ndigits == 0)
1290 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001291 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1292 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 /* [p <exponent>] */
1296 if (*s == 'p' || *s == 'P') {
1297 s++;
1298 exp_start = s;
1299 if (*s == '-' || *s == '+')
1300 s++;
1301 if (!('0' <= *s && *s <= '9'))
1302 goto parse_error;
1303 s++;
1304 while ('0' <= *s && *s <= '9')
1305 s++;
1306 exp = strtol(exp_start, NULL, 10);
1307 }
1308 else
1309 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001311/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1313 coeff_end-(j) : \
1314 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /*******************************************
1317 * Compute rounded value of the hex string *
1318 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* Discard leading zeros, and catch extreme overflow and underflow */
1321 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1322 ndigits--;
1323 if (ndigits == 0 || exp < LONG_MIN/2) {
1324 x = 0.0;
1325 goto finished;
1326 }
1327 if (exp > LONG_MAX/2)
1328 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* Adjust exponent for fractional part. */
1331 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1334 top_exp = exp + 4*((long)ndigits - 1);
1335 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1336 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* catch almost all nonextreme cases of overflow and underflow here */
1339 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1340 x = 0.0;
1341 goto finished;
1342 }
1343 if (top_exp > DBL_MAX_EXP)
1344 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* lsb = exponent of least significant bit of the *rounded* value.
1347 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001348 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 x = 0.0;
1351 if (exp >= lsb) {
1352 /* no rounding required */
1353 for (i = ndigits-1; i >= 0; i--)
1354 x = 16.0*x + HEX_DIGIT(i);
1355 x = ldexp(x, (int)(exp));
1356 goto finished;
1357 }
1358 /* rounding required. key_digit is the index of the hex digit
1359 containing the first bit to be rounded away. */
1360 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1361 key_digit = (lsb - exp - 1) / 4;
1362 for (i = ndigits-1; i > key_digit; i--)
1363 x = 16.0*x + HEX_DIGIT(i);
1364 digit = HEX_DIGIT(key_digit);
1365 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1368 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1369 if ((digit & half_eps) != 0) {
1370 round_up = 0;
1371 if ((digit & (3*half_eps-1)) != 0 ||
1372 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1373 round_up = 1;
1374 else
1375 for (i = key_digit-1; i >= 0; i--)
1376 if (HEX_DIGIT(i) != 0) {
1377 round_up = 1;
1378 break;
1379 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001380 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 x += 2*half_eps;
1382 if (top_exp == DBL_MAX_EXP &&
1383 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1384 /* overflow corner case: pre-rounded value <
1385 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1386 goto overflow_error;
1387 }
1388 }
1389 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001390
1391 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* optional trailing whitespace leading to the end of the string */
1393 while (Py_ISSPACE(*s))
1394 s++;
1395 if (s != s_end)
1396 goto parse_error;
1397 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1398 if (result_as_float == NULL)
1399 return NULL;
1400 result = PyObject_CallObject(cls, result_as_float);
1401 Py_DECREF(result_as_float);
1402 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001403
1404 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyErr_SetString(PyExc_OverflowError,
1406 "hexadecimal value too large to represent as a float");
1407 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001408
1409 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyErr_SetString(PyExc_ValueError,
1411 "invalid hexadecimal floating-point string");
1412 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001413
1414 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyErr_SetString(PyExc_ValueError,
1416 "hexadecimal string too long to convert");
1417 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001418}
1419
1420PyDoc_STRVAR(float_fromhex_doc,
1421"float.fromhex(string) -> float\n\
1422\n\
1423Create a floating-point number from a hexadecimal string.\n\
1424>>> float.fromhex('0x1.ffffp10')\n\
14252047.984375\n\
1426>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001427-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001428
1429
Christian Heimes26855632008-01-27 23:50:43 +00001430static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001431float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 double self;
1434 double float_part;
1435 int exponent;
1436 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 PyObject *prev;
1439 PyObject *py_exponent = NULL;
1440 PyObject *numerator = NULL;
1441 PyObject *denominator = NULL;
1442 PyObject *result_pair = NULL;
1443 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001444
1445#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 prev = obj; \
1447 obj = call; \
1448 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (Py_IS_INFINITY(self)) {
1453 PyErr_SetString(PyExc_OverflowError,
1454 "Cannot pass infinity to float.as_integer_ratio.");
1455 return NULL;
1456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (Py_IS_NAN(self)) {
1458 PyErr_SetString(PyExc_ValueError,
1459 "Cannot pass NaN to float.as_integer_ratio.");
1460 return NULL;
1461 }
Christian Heimes26855632008-01-27 23:50:43 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1464 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1465 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1468 float_part *= 2.0;
1469 exponent--;
1470 }
1471 /* self == float_part * 2**exponent exactly and float_part is integral.
1472 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1473 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 numerator = PyLong_FromDouble(float_part);
1476 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 /* fold in 2**exponent */
1479 denominator = PyLong_FromLong(1);
1480 py_exponent = PyLong_FromLong(labs((long)exponent));
1481 if (py_exponent == NULL) goto error;
1482 INPLACE_UPDATE(py_exponent,
1483 long_methods->nb_lshift(denominator, py_exponent));
1484 if (py_exponent == NULL) goto error;
1485 if (exponent > 0) {
1486 INPLACE_UPDATE(numerator,
1487 long_methods->nb_multiply(numerator, py_exponent));
1488 if (numerator == NULL) goto error;
1489 }
1490 else {
1491 Py_DECREF(denominator);
1492 denominator = py_exponent;
1493 py_exponent = NULL;
1494 }
1495
1496 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001497
1498#undef INPLACE_UPDATE
1499error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_XDECREF(py_exponent);
1501 Py_XDECREF(denominator);
1502 Py_XDECREF(numerator);
1503 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001504}
1505
1506PyDoc_STRVAR(float_as_integer_ratio_doc,
1507"float.as_integer_ratio() -> (int, int)\n"
1508"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001509"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001510"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001511"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001512"\n"
1513">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001514"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001515">>> (0.0).as_integer_ratio()\n"
1516"(0, 1)\n"
1517">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001518"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001519
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001520
Jeremy Hylton938ace62002-07-17 16:30:39 +00001521static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001522float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1523
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524static PyObject *
1525float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 PyObject *x = Py_False; /* Integer zero */
1528 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (type != &PyFloat_Type)
1531 return float_subtype_new(type, args, kwds); /* Wimp out */
1532 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1533 return NULL;
1534 /* If it's a string, but not a string subclass, use
1535 PyFloat_FromString. */
1536 if (PyUnicode_CheckExact(x))
1537 return PyFloat_FromString(x);
1538 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539}
1540
Guido van Rossumbef14172001-08-29 15:47:46 +00001541/* Wimpy, slow approach to tp_new calls for subtypes of float:
1542 first create a regular float from whatever arguments we got,
1543 then allocate a subtype instance and initialize its ob_fval
1544 from the regular float. The regular float is then thrown away.
1545*/
1546static PyObject *
1547float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 assert(PyType_IsSubtype(type, &PyFloat_Type));
1552 tmp = float_new(&PyFloat_Type, args, kwds);
1553 if (tmp == NULL)
1554 return NULL;
1555 assert(PyFloat_CheckExact(tmp));
1556 newobj = type->tp_alloc(type, 0);
1557 if (newobj == NULL) {
1558 Py_DECREF(tmp);
1559 return NULL;
1560 }
1561 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1562 Py_DECREF(tmp);
1563 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001564}
1565
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001566static PyObject *
1567float_getnewargs(PyFloatObject *v)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001570}
1571
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001572/* this is for the benefit of the pack/unpack routines below */
1573
1574typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001576} float_format_type;
1577
1578static float_format_type double_format, float_format;
1579static float_format_type detected_double_format, detected_float_format;
1580
1581static PyObject *
1582float_getformat(PyTypeObject *v, PyObject* arg)
1583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 char* s;
1585 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if (!PyUnicode_Check(arg)) {
1588 PyErr_Format(PyExc_TypeError,
1589 "__getformat__() argument must be string, not %.500s",
1590 Py_TYPE(arg)->tp_name);
1591 return NULL;
1592 }
1593 s = _PyUnicode_AsString(arg);
1594 if (s == NULL)
1595 return NULL;
1596 if (strcmp(s, "double") == 0) {
1597 r = double_format;
1598 }
1599 else if (strcmp(s, "float") == 0) {
1600 r = float_format;
1601 }
1602 else {
1603 PyErr_SetString(PyExc_ValueError,
1604 "__getformat__() argument 1 must be "
1605 "'double' or 'float'");
1606 return NULL;
1607 }
1608
1609 switch (r) {
1610 case unknown_format:
1611 return PyUnicode_FromString("unknown");
1612 case ieee_little_endian_format:
1613 return PyUnicode_FromString("IEEE, little-endian");
1614 case ieee_big_endian_format:
1615 return PyUnicode_FromString("IEEE, big-endian");
1616 default:
1617 Py_FatalError("insane float_format or double_format");
1618 return NULL;
1619 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620}
1621
1622PyDoc_STRVAR(float_getformat_doc,
1623"float.__getformat__(typestr) -> string\n"
1624"\n"
1625"You probably don't want to use this function. It exists mainly to be\n"
1626"used in Python's test suite.\n"
1627"\n"
1628"typestr must be 'double' or 'float'. This function returns whichever of\n"
1629"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1630"format of floating point numbers used by the C type named by typestr.");
1631
1632static PyObject *
1633float_setformat(PyTypeObject *v, PyObject* args)
1634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 char* typestr;
1636 char* format;
1637 float_format_type f;
1638 float_format_type detected;
1639 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1642 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 if (strcmp(typestr, "double") == 0) {
1645 p = &double_format;
1646 detected = detected_double_format;
1647 }
1648 else if (strcmp(typestr, "float") == 0) {
1649 p = &float_format;
1650 detected = detected_float_format;
1651 }
1652 else {
1653 PyErr_SetString(PyExc_ValueError,
1654 "__setformat__() argument 1 must "
1655 "be 'double' or 'float'");
1656 return NULL;
1657 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (strcmp(format, "unknown") == 0) {
1660 f = unknown_format;
1661 }
1662 else if (strcmp(format, "IEEE, little-endian") == 0) {
1663 f = ieee_little_endian_format;
1664 }
1665 else if (strcmp(format, "IEEE, big-endian") == 0) {
1666 f = ieee_big_endian_format;
1667 }
1668 else {
1669 PyErr_SetString(PyExc_ValueError,
1670 "__setformat__() argument 2 must be "
1671 "'unknown', 'IEEE, little-endian' or "
1672 "'IEEE, big-endian'");
1673 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 if (f != unknown_format && f != detected) {
1678 PyErr_Format(PyExc_ValueError,
1679 "can only set %s format to 'unknown' or the "
1680 "detected platform value", typestr);
1681 return NULL;
1682 }
1683
1684 *p = f;
1685 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001686}
1687
1688PyDoc_STRVAR(float_setformat_doc,
1689"float.__setformat__(typestr, fmt) -> None\n"
1690"\n"
1691"You probably don't want to use this function. It exists mainly to be\n"
1692"used in Python's test suite.\n"
1693"\n"
1694"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1695"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1696"one of the latter two if it appears to match the underlying C reality.\n"
1697"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001698"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001699"This affects how floats are converted to and from binary strings.");
1700
Guido van Rossumb43daf72007-08-01 18:08:08 +00001701static PyObject *
1702float_getzero(PyObject *v, void *closure)
1703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001705}
1706
Eric Smith8c663262007-08-25 02:26:07 +00001707static PyObject *
1708float__format__(PyObject *self, PyObject *args)
1709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001711 _PyUnicodeWriter writer;
1712 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1715 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001716
Victor Stinner8f674cc2013-04-17 23:02:17 +02001717 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001718 ret = _PyFloat_FormatAdvancedWriter(
1719 &writer,
1720 self,
1721 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1722 if (ret == -1) {
1723 _PyUnicodeWriter_Dealloc(&writer);
1724 return NULL;
1725 }
1726 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001727}
1728
1729PyDoc_STRVAR(float__format__doc,
1730"float.__format__(format_spec) -> string\n"
1731"\n"
1732"Formats the float according to format_spec.");
1733
1734
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001735static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001737 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001739 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001741 "Return the Integral closest to x, rounding half toward even.\n"
1742 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1744 float_as_integer_ratio_doc},
1745 {"fromhex", (PyCFunction)float_fromhex,
1746 METH_O|METH_CLASS, float_fromhex_doc},
1747 {"hex", (PyCFunction)float_hex,
1748 METH_NOARGS, float_hex_doc},
1749 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001750 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001751#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001753 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001755 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001757 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001758#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1760 {"__getformat__", (PyCFunction)float_getformat,
1761 METH_O|METH_CLASS, float_getformat_doc},
1762 {"__setformat__", (PyCFunction)float_setformat,
1763 METH_VARARGS|METH_CLASS, float_setformat_doc},
1764 {"__format__", (PyCFunction)float__format__,
1765 METH_VARARGS, float__format__doc},
1766 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001767};
1768
Guido van Rossumb43daf72007-08-01 18:08:08 +00001769static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001771 (getter)float_float, (setter)NULL,
1772 "the real part of a complex number",
1773 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001775 (getter)float_getzero, (setter)NULL,
1776 "the imaginary part of a complex number",
1777 NULL},
1778 {NULL} /* Sentinel */
1779};
1780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001781PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782"float(x) -> floating point number\n\
1783\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001784Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785
1786
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001787static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 float_add, /*nb_add*/
1789 float_sub, /*nb_subtract*/
1790 float_mul, /*nb_multiply*/
1791 float_rem, /*nb_remainder*/
1792 float_divmod, /*nb_divmod*/
1793 float_pow, /*nb_power*/
1794 (unaryfunc)float_neg, /*nb_negative*/
1795 (unaryfunc)float_float, /*nb_positive*/
1796 (unaryfunc)float_abs, /*nb_absolute*/
1797 (inquiry)float_bool, /*nb_bool*/
1798 0, /*nb_invert*/
1799 0, /*nb_lshift*/
1800 0, /*nb_rshift*/
1801 0, /*nb_and*/
1802 0, /*nb_xor*/
1803 0, /*nb_or*/
1804 float_trunc, /*nb_int*/
1805 0, /*nb_reserved*/
1806 float_float, /*nb_float*/
1807 0, /* nb_inplace_add */
1808 0, /* nb_inplace_subtract */
1809 0, /* nb_inplace_multiply */
1810 0, /* nb_inplace_remainder */
1811 0, /* nb_inplace_power */
1812 0, /* nb_inplace_lshift */
1813 0, /* nb_inplace_rshift */
1814 0, /* nb_inplace_and */
1815 0, /* nb_inplace_xor */
1816 0, /* nb_inplace_or */
1817 float_floor_div, /* nb_floor_divide */
1818 float_div, /* nb_true_divide */
1819 0, /* nb_inplace_floor_divide */
1820 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001821};
1822
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001823PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1825 "float",
1826 sizeof(PyFloatObject),
1827 0,
1828 (destructor)float_dealloc, /* tp_dealloc */
1829 0, /* tp_print */
1830 0, /* tp_getattr */
1831 0, /* tp_setattr */
1832 0, /* tp_reserved */
1833 (reprfunc)float_repr, /* tp_repr */
1834 &float_as_number, /* tp_as_number */
1835 0, /* tp_as_sequence */
1836 0, /* tp_as_mapping */
1837 (hashfunc)float_hash, /* tp_hash */
1838 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001839 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 PyObject_GenericGetAttr, /* tp_getattro */
1841 0, /* tp_setattro */
1842 0, /* tp_as_buffer */
1843 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1844 float_doc, /* tp_doc */
1845 0, /* tp_traverse */
1846 0, /* tp_clear */
1847 float_richcompare, /* tp_richcompare */
1848 0, /* tp_weaklistoffset */
1849 0, /* tp_iter */
1850 0, /* tp_iternext */
1851 float_methods, /* tp_methods */
1852 0, /* tp_members */
1853 float_getset, /* tp_getset */
1854 0, /* tp_base */
1855 0, /* tp_dict */
1856 0, /* tp_descr_get */
1857 0, /* tp_descr_set */
1858 0, /* tp_dictoffset */
1859 0, /* tp_init */
1860 0, /* tp_alloc */
1861 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001862};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001863
Victor Stinner1c8f0592013-07-22 22:24:54 +02001864int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001865_PyFloat_Init(void)
1866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 /* We attempt to determine if this machine is using IEEE
1868 floating point formats by peering at the bits of some
1869 carefully chosen values. If it looks like we are on an
1870 IEEE platform, the float packing/unpacking routines can
1871 just copy bits, if not they resort to arithmetic & shifts
1872 and masks. The shifts & masks approach works on all finite
1873 values, but what happens to infinities, NaNs and signed
1874 zeroes on packing is an accident, and attempting to unpack
1875 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 Note that if we're on some whacked-out platform which uses
1878 IEEE formats but isn't strictly little-endian or big-
1879 endian, we will fall back to the portable shifts & masks
1880 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001881
1882#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 {
1884 double x = 9006104071832581.0;
1885 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1886 detected_double_format = ieee_big_endian_format;
1887 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1888 detected_double_format = ieee_little_endian_format;
1889 else
1890 detected_double_format = unknown_format;
1891 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001894#endif
1895
1896#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 {
1898 float y = 16711938.0;
1899 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1900 detected_float_format = ieee_big_endian_format;
1901 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1902 detected_float_format = ieee_little_endian_format;
1903 else
1904 detected_float_format = unknown_format;
1905 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908#endif
1909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 double_format = detected_double_format;
1911 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001914 if (FloatInfoType.tp_name == NULL) {
1915 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1916 return 0;
1917 }
1918 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919}
1920
Georg Brandl2ee470f2008-07-16 12:55:28 +00001921int
1922PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001923{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001924 PyFloatObject *f = free_list, *next;
1925 int i = numfree;
1926 while (f) {
1927 next = (PyFloatObject*) Py_TYPE(f);
1928 PyObject_FREE(f);
1929 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001931 free_list = NULL;
1932 numfree = 0;
1933 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001934}
1935
1936void
1937PyFloat_Fini(void)
1938{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001939 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001940}
Tim Peters9905b942003-03-20 20:53:32 +00001941
David Malcolm49526f42012-06-22 14:55:41 -04001942/* Print summary info about the state of the optimized allocator */
1943void
1944_PyFloat_DebugMallocStats(FILE *out)
1945{
1946 _PyDebugAllocatorStats(out,
1947 "free PyFloatObject",
1948 numfree, sizeof(PyFloatObject));
1949}
1950
1951
Tim Peters9905b942003-03-20 20:53:32 +00001952/*----------------------------------------------------------------------------
1953 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001954 */
1955int
1956_PyFloat_Pack4(double x, unsigned char *p, int le)
1957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (float_format == unknown_format) {
1959 unsigned char sign;
1960 int e;
1961 double f;
1962 unsigned int fbits;
1963 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (le) {
1966 p += 3;
1967 incr = -1;
1968 }
Tim Peters9905b942003-03-20 20:53:32 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (x < 0) {
1971 sign = 1;
1972 x = -x;
1973 }
1974 else
1975 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 /* Normalize f to be in the range [1.0, 2.0) */
1980 if (0.5 <= f && f < 1.0) {
1981 f *= 2.0;
1982 e--;
1983 }
1984 else if (f == 0.0)
1985 e = 0;
1986 else {
1987 PyErr_SetString(PyExc_SystemError,
1988 "frexp() result out of range");
1989 return -1;
1990 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if (e >= 128)
1993 goto Overflow;
1994 else if (e < -126) {
1995 /* Gradual underflow */
1996 f = ldexp(f, 126 + e);
1997 e = 0;
1998 }
1999 else if (!(e == 0 && f == 0.0)) {
2000 e += 127;
2001 f -= 1.0; /* Get rid of leading 1 */
2002 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 f *= 8388608.0; /* 2**23 */
2005 fbits = (unsigned int)(f + 0.5); /* Round */
2006 assert(fbits <= 8388608);
2007 if (fbits >> 23) {
2008 /* The carry propagated out of a string of 23 1 bits. */
2009 fbits = 0;
2010 ++e;
2011 if (e >= 255)
2012 goto Overflow;
2013 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* First byte */
2016 *p = (sign << 7) | (e >> 1);
2017 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 /* Second byte */
2020 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2021 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 /* Third byte */
2024 *p = (fbits >> 8) & 0xFF;
2025 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* Fourth byte */
2028 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Done */
2031 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 }
2034 else {
2035 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002036 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2040 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if ((float_format == ieee_little_endian_format && !le)
2043 || (float_format == ieee_big_endian_format && le)) {
2044 p += 3;
2045 incr = -1;
2046 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 for (i = 0; i < 4; i++) {
2049 *p = *s++;
2050 p += incr;
2051 }
2052 return 0;
2053 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002054 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 PyErr_SetString(PyExc_OverflowError,
2056 "float too large to pack with f format");
2057 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002058}
2059
2060int
2061_PyFloat_Pack8(double x, unsigned char *p, int le)
2062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (double_format == unknown_format) {
2064 unsigned char sign;
2065 int e;
2066 double f;
2067 unsigned int fhi, flo;
2068 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (le) {
2071 p += 7;
2072 incr = -1;
2073 }
Tim Peters9905b942003-03-20 20:53:32 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (x < 0) {
2076 sign = 1;
2077 x = -x;
2078 }
2079 else
2080 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Normalize f to be in the range [1.0, 2.0) */
2085 if (0.5 <= f && f < 1.0) {
2086 f *= 2.0;
2087 e--;
2088 }
2089 else if (f == 0.0)
2090 e = 0;
2091 else {
2092 PyErr_SetString(PyExc_SystemError,
2093 "frexp() result out of range");
2094 return -1;
2095 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (e >= 1024)
2098 goto Overflow;
2099 else if (e < -1022) {
2100 /* Gradual underflow */
2101 f = ldexp(f, 1022 + e);
2102 e = 0;
2103 }
2104 else if (!(e == 0 && f == 0.0)) {
2105 e += 1023;
2106 f -= 1.0; /* Get rid of leading 1 */
2107 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2110 f *= 268435456.0; /* 2**28 */
2111 fhi = (unsigned int)f; /* Truncate */
2112 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 f -= (double)fhi;
2115 f *= 16777216.0; /* 2**24 */
2116 flo = (unsigned int)(f + 0.5); /* Round */
2117 assert(flo <= 16777216);
2118 if (flo >> 24) {
2119 /* The carry propagated out of a string of 24 1 bits. */
2120 flo = 0;
2121 ++fhi;
2122 if (fhi >> 28) {
2123 /* And it also progagated out of the next 28 bits. */
2124 fhi = 0;
2125 ++e;
2126 if (e >= 2047)
2127 goto Overflow;
2128 }
2129 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 /* First byte */
2132 *p = (sign << 7) | (e >> 4);
2133 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* Second byte */
2136 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2137 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 /* Third byte */
2140 *p = (fhi >> 16) & 0xFF;
2141 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* Fourth byte */
2144 *p = (fhi >> 8) & 0xFF;
2145 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 /* Fifth byte */
2148 *p = fhi & 0xFF;
2149 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Sixth byte */
2152 *p = (flo >> 16) & 0xFF;
2153 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* Seventh byte */
2156 *p = (flo >> 8) & 0xFF;
2157 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 /* Eighth byte */
2160 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002161 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Done */
2164 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 Overflow:
2167 PyErr_SetString(PyExc_OverflowError,
2168 "float too large to pack with d format");
2169 return -1;
2170 }
2171 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002172 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if ((double_format == ieee_little_endian_format && !le)
2176 || (double_format == ieee_big_endian_format && le)) {
2177 p += 7;
2178 incr = -1;
2179 }
2180
2181 for (i = 0; i < 8; i++) {
2182 *p = *s++;
2183 p += incr;
2184 }
2185 return 0;
2186 }
Tim Peters9905b942003-03-20 20:53:32 +00002187}
2188
2189double
2190_PyFloat_Unpack4(const unsigned char *p, int le)
2191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (float_format == unknown_format) {
2193 unsigned char sign;
2194 int e;
2195 unsigned int f;
2196 double x;
2197 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 if (le) {
2200 p += 3;
2201 incr = -1;
2202 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 /* First byte */
2205 sign = (*p >> 7) & 1;
2206 e = (*p & 0x7F) << 1;
2207 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 /* Second byte */
2210 e |= (*p >> 7) & 1;
2211 f = (*p & 0x7F) << 16;
2212 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (e == 255) {
2215 PyErr_SetString(
2216 PyExc_ValueError,
2217 "can't unpack IEEE 754 special value "
2218 "on non-IEEE platform");
2219 return -1;
2220 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Third byte */
2223 f |= *p << 8;
2224 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Fourth byte */
2227 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* XXX This sadly ignores Inf/NaN issues */
2232 if (e == 0)
2233 e = -126;
2234 else {
2235 x += 1.0;
2236 e -= 127;
2237 }
2238 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 if (sign)
2241 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return x;
2244 }
2245 else {
2246 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if ((float_format == ieee_little_endian_format && !le)
2249 || (float_format == ieee_big_endian_format && le)) {
2250 char buf[4];
2251 char *d = &buf[3];
2252 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 for (i = 0; i < 4; i++) {
2255 *d-- = *p++;
2256 }
2257 memcpy(&x, buf, 4);
2258 }
2259 else {
2260 memcpy(&x, p, 4);
2261 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 return x;
2264 }
Tim Peters9905b942003-03-20 20:53:32 +00002265}
2266
2267double
2268_PyFloat_Unpack8(const unsigned char *p, int le)
2269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (double_format == unknown_format) {
2271 unsigned char sign;
2272 int e;
2273 unsigned int fhi, flo;
2274 double x;
2275 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (le) {
2278 p += 7;
2279 incr = -1;
2280 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* First byte */
2283 sign = (*p >> 7) & 1;
2284 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* Second byte */
2289 e |= (*p >> 4) & 0xF;
2290 fhi = (*p & 0xF) << 24;
2291 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 if (e == 2047) {
2294 PyErr_SetString(
2295 PyExc_ValueError,
2296 "can't unpack IEEE 754 special value "
2297 "on non-IEEE platform");
2298 return -1.0;
2299 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Third byte */
2302 fhi |= *p << 16;
2303 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Fourth byte */
2306 fhi |= *p << 8;
2307 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Fifth byte */
2310 fhi |= *p;
2311 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Sixth byte */
2314 flo = *p << 16;
2315 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Seventh byte */
2318 flo |= *p << 8;
2319 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Eighth byte */
2322 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2325 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (e == 0)
2328 e = -1022;
2329 else {
2330 x += 1.0;
2331 e -= 1023;
2332 }
2333 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (sign)
2336 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 return x;
2339 }
2340 else {
2341 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 if ((double_format == ieee_little_endian_format && !le)
2344 || (double_format == ieee_big_endian_format && le)) {
2345 char buf[8];
2346 char *d = &buf[7];
2347 int i;
2348
2349 for (i = 0; i < 8; i++) {
2350 *d-- = *p++;
2351 }
2352 memcpy(&x, buf, 8);
2353 }
2354 else {
2355 memcpy(&x, p, 8);
2356 }
2357
2358 return x;
2359 }
Tim Peters9905b942003-03-20 20:53:32 +00002360}