blob: d92bec35b5f8819270bd9152ad11cbd8bdc1b6dd [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 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000147 else if (PyBytes_Check(v)) {
148 s = PyBytes_AS_STRING(v);
149 len = PyBytes_GET_SIZE(v);
150 }
151 else if (PyByteArray_Check(v)) {
152 s = PyByteArray_AS_STRING(v);
153 len = PyByteArray_GET_SIZE(v);
154 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200155 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
156 s = (const char *)view.buf;
157 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000158 /* Copy to NUL-terminated buffer. */
159 s_buffer = PyBytes_FromStringAndSize(s, len);
160 if (s_buffer == NULL) {
161 PyBuffer_Release(&view);
162 return NULL;
163 }
164 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200165 }
166 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200167 PyErr_Format(PyExc_TypeError,
168 "float() argument must be a string or a number, not '%.200s'",
169 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return NULL;
171 }
172 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000173 /* strip space */
174 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000176 while (s < last - 1 && Py_ISSPACE(last[-1]))
177 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* We don't care about overflow or underflow. If the platform
179 * supports them, infinities and signed zeroes (on underflow) are
180 * fine. */
181 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 if (end != last) {
183 PyErr_Format(PyExc_ValueError,
184 "could not convert string to float: "
185 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 result = NULL;
187 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000188 else if (x == -1.0 && PyErr_Occurred())
189 result = NULL;
190 else
191 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000192
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200193 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000194 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196}
197
Guido van Rossum234f9421993-06-17 12:35:49 +0000198static void
Fred Drakefd99de62000-07-09 05:02:18 +0000199float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000202 if (numfree >= PyFloat_MAXFREELIST) {
203 PyObject_FREE(op);
204 return;
205 }
206 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_TYPE(op) = (struct _typeobject *)free_list;
208 free_list = op;
209 }
210 else
211 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000212}
213
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214double
Fred Drakefd99de62000-07-09 05:02:18 +0000215PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyNumberMethods *nb;
218 PyFloatObject *fo;
219 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (op && PyFloat_Check(op))
222 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (op == NULL) {
225 PyErr_BadArgument();
226 return -1;
227 }
Tim Petersd2364e82001-11-01 20:09:42 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
230 PyErr_SetString(PyExc_TypeError, "a float is required");
231 return -1;
232 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 fo = (PyFloatObject*) (*nb->nb_float) (op);
235 if (fo == NULL)
236 return -1;
237 if (!PyFloat_Check(fo)) {
Benjamin Petersona9157232015-03-06 09:08:44 -0500238 Py_DECREF(fo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyErr_SetString(PyExc_TypeError,
240 "nb_float should return float object");
241 return -1;
242 }
Tim Petersd2364e82001-11-01 20:09:42 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 val = PyFloat_AS_DOUBLE(fo);
245 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248}
249
Neil Schemenauer32117e52001-01-04 01:44:34 +0000250/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000251 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000252 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300253 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000254 stored in obj, and returned from the function invoking this macro.
255*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256#define CONVERT_TO_DOUBLE(obj, dbl) \
257 if (PyFloat_Check(obj)) \
258 dbl = PyFloat_AS_DOUBLE(obj); \
259 else if (convert_to_double(&(obj), &(dbl)) < 0) \
260 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000261
Eric Smith0923d1d2009-04-16 20:16:10 +0000262/* Methods */
263
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000265convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000266{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200267 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (PyLong_Check(obj)) {
270 *dbl = PyLong_AsDouble(obj);
271 if (*dbl == -1.0 && PyErr_Occurred()) {
272 *v = NULL;
273 return -1;
274 }
275 }
276 else {
277 Py_INCREF(Py_NotImplemented);
278 *v = Py_NotImplemented;
279 return -1;
280 }
281 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000282}
283
Eric Smith0923d1d2009-04-16 20:16:10 +0000284static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000285float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000286{
287 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200288 char *buf;
289
290 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
291 'r', 0,
292 Py_DTSF_ADD_DOT_0,
293 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000294 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000295 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200296 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000297 PyMem_Free(buf);
298 return result;
299}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000300
Tim Peters307fa782004-09-23 08:06:40 +0000301/* Comparison is pretty much a nightmare. When comparing float to float,
302 * we do it as straightforwardly (and long-windedly) as conceivable, so
303 * that, e.g., Python x == y delivers the same result as the platform
304 * C x == y when x and/or y is a NaN.
305 * When mixing float with an integer type, there's no good *uniform* approach.
306 * Converting the double to an integer obviously doesn't work, since we
307 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300308 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000309 * 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 +0200310 * 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 +0000311 * 63 bits of precision, but a C double probably has only 53), and then
312 * we can falsely claim equality when low-order integer bits are lost by
313 * coercion to double. So this part is painful too.
314 */
315
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000316static PyObject*
317float_richcompare(PyObject *v, PyObject *w, int op)
318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 double i, j;
320 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 assert(PyFloat_Check(v));
323 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 /* Switch on the type of w. Set i and j to doubles to be compared,
326 * and op to the richcomp to use.
327 */
328 if (PyFloat_Check(w))
329 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 else if (!Py_IS_FINITE(i)) {
332 if (PyLong_Check(w))
333 /* If i is an infinity, its magnitude exceeds any
334 * finite integer, so it doesn't matter which int we
335 * compare i with. If i is a NaN, similarly.
336 */
337 j = 0.0;
338 else
339 goto Unimplemented;
340 }
Tim Peters307fa782004-09-23 08:06:40 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 else if (PyLong_Check(w)) {
343 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
344 int wsign = _PyLong_Sign(w);
345 size_t nbits;
346 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (vsign != wsign) {
349 /* Magnitudes are irrelevant -- the signs alone
350 * determine the outcome.
351 */
352 i = (double)vsign;
353 j = (double)wsign;
354 goto Compare;
355 }
356 /* The signs are the same. */
357 /* Convert w to a double if it fits. In particular, 0 fits. */
358 nbits = _PyLong_NumBits(w);
359 if (nbits == (size_t)-1 && PyErr_Occurred()) {
360 /* This long is so large that size_t isn't big enough
361 * to hold the # of bits. Replace with little doubles
362 * that give the same outcome -- w is so large that
363 * its magnitude must exceed the magnitude of any
364 * finite float.
365 */
366 PyErr_Clear();
367 i = (double)vsign;
368 assert(wsign != 0);
369 j = wsign * 2.0;
370 goto Compare;
371 }
372 if (nbits <= 48) {
373 j = PyLong_AsDouble(w);
374 /* It's impossible that <= 48 bits overflowed. */
375 assert(j != -1.0 || ! PyErr_Occurred());
376 goto Compare;
377 }
378 assert(wsign != 0); /* else nbits was 0 */
379 assert(vsign != 0); /* if vsign were 0, then since wsign is
380 * not 0, we would have taken the
381 * vsign != wsign branch at the start */
382 /* We want to work with non-negative numbers. */
383 if (vsign < 0) {
384 /* "Multiply both sides" by -1; this also swaps the
385 * comparator.
386 */
387 i = -i;
388 op = _Py_SwappedOp[op];
389 }
390 assert(i > 0.0);
391 (void) frexp(i, &exponent);
392 /* exponent is the # of bits in v before the radix point;
393 * we know that nbits (the # of bits in w) > 48 at this point
394 */
395 if (exponent < 0 || (size_t)exponent < nbits) {
396 i = 1.0;
397 j = 2.0;
398 goto Compare;
399 }
400 if ((size_t)exponent > nbits) {
401 i = 2.0;
402 j = 1.0;
403 goto Compare;
404 }
405 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300406 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 * outcome.
408 */
409 {
410 double fracpart;
411 double intpart;
412 PyObject *result = NULL;
413 PyObject *one = NULL;
414 PyObject *vv = NULL;
415 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (wsign < 0) {
418 ww = PyNumber_Negative(w);
419 if (ww == NULL)
420 goto Error;
421 }
422 else
423 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 fracpart = modf(i, &intpart);
426 vv = PyLong_FromDouble(intpart);
427 if (vv == NULL)
428 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (fracpart != 0.0) {
431 /* Shift left, and or a 1 bit into vv
432 * to represent the lost fraction.
433 */
434 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 one = PyLong_FromLong(1);
437 if (one == NULL)
438 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 temp = PyNumber_Lshift(ww, one);
441 if (temp == NULL)
442 goto Error;
443 Py_DECREF(ww);
444 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 temp = PyNumber_Lshift(vv, one);
447 if (temp == NULL)
448 goto Error;
449 Py_DECREF(vv);
450 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 temp = PyNumber_Or(vv, one);
453 if (temp == NULL)
454 goto Error;
455 Py_DECREF(vv);
456 vv = temp;
457 }
Tim Peters307fa782004-09-23 08:06:40 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 r = PyObject_RichCompareBool(vv, ww, op);
460 if (r < 0)
461 goto Error;
462 result = PyBool_FromLong(r);
463 Error:
464 Py_XDECREF(vv);
465 Py_XDECREF(ww);
466 Py_XDECREF(one);
467 return result;
468 }
469 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000470
Serhiy Storchaka95949422013-08-27 19:40:23 +0300471 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000473
474 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyFPE_START_PROTECT("richcompare", return NULL)
476 switch (op) {
477 case Py_EQ:
478 r = i == j;
479 break;
480 case Py_NE:
481 r = i != j;
482 break;
483 case Py_LE:
484 r = i <= j;
485 break;
486 case Py_GE:
487 r = i >= j;
488 break;
489 case Py_LT:
490 r = i < j;
491 break;
492 case Py_GT:
493 r = i > j;
494 break;
495 }
496 PyFPE_END_PROTECT(r)
497 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000498
499 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500500 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000501}
502
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000503static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000504float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000507}
508
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000510float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 double a,b;
513 CONVERT_TO_DOUBLE(v, a);
514 CONVERT_TO_DOUBLE(w, b);
515 PyFPE_START_PROTECT("add", return 0)
516 a = a + b;
517 PyFPE_END_PROTECT(a)
518 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519}
520
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000522float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 double a,b;
525 CONVERT_TO_DOUBLE(v, a);
526 CONVERT_TO_DOUBLE(w, b);
527 PyFPE_START_PROTECT("subtract", return 0)
528 a = a - b;
529 PyFPE_END_PROTECT(a)
530 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000531}
532
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000534float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 double a,b;
537 CONVERT_TO_DOUBLE(v, a);
538 CONVERT_TO_DOUBLE(w, b);
539 PyFPE_START_PROTECT("multiply", return 0)
540 a = a * b;
541 PyFPE_END_PROTECT(a)
542 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543}
544
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000546float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 double a,b;
549 CONVERT_TO_DOUBLE(v, a);
550 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (b == 0.0) {
552 PyErr_SetString(PyExc_ZeroDivisionError,
553 "float division by zero");
554 return NULL;
555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyFPE_START_PROTECT("divide", return 0)
557 a = a / b;
558 PyFPE_END_PROTECT(a)
559 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 double vx, wx;
566 double mod;
567 CONVERT_TO_DOUBLE(v, vx);
568 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (wx == 0.0) {
570 PyErr_SetString(PyExc_ZeroDivisionError,
571 "float modulo");
572 return NULL;
573 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyFPE_START_PROTECT("modulo", return 0)
575 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000576 if (mod) {
577 /* ensure the remainder has the same sign as the denominator */
578 if ((wx < 0) != (mod < 0)) {
579 mod += wx;
580 }
581 }
582 else {
583 /* the remainder is zero, and in the presence of signed zeroes
584 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000585 it has the same sign as the denominator. */
586 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
588 PyFPE_END_PROTECT(mod)
589 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590}
591
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000593float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 double vx, wx;
596 double div, mod, floordiv;
597 CONVERT_TO_DOUBLE(v, vx);
598 CONVERT_TO_DOUBLE(w, wx);
599 if (wx == 0.0) {
600 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
601 return NULL;
602 }
603 PyFPE_START_PROTECT("divmod", return 0)
604 mod = fmod(vx, wx);
605 /* fmod is typically exact, so vx-mod is *mathematically* an
606 exact multiple of wx. But this is fp arithmetic, and fp
607 vx - mod is an approximation; the result is that div may
608 not be an exact integral value after the division, although
609 it will always be very close to one.
610 */
611 div = (vx - mod) / wx;
612 if (mod) {
613 /* ensure the remainder has the same sign as the denominator */
614 if ((wx < 0) != (mod < 0)) {
615 mod += wx;
616 div -= 1.0;
617 }
618 }
619 else {
620 /* the remainder is zero, and in the presence of signed zeroes
621 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000622 it has the same sign as the denominator. */
623 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 }
625 /* snap quotient to nearest integral value */
626 if (div) {
627 floordiv = floor(div);
628 if (div - floordiv > 0.5)
629 floordiv += 1.0;
630 }
631 else {
632 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000633 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
635 PyFPE_END_PROTECT(floordiv)
636 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000640float_floor_div(PyObject *v, PyObject *w)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 t = float_divmod(v, w);
645 if (t == NULL || t == Py_NotImplemented)
646 return t;
647 assert(PyTuple_CheckExact(t));
648 r = PyTuple_GET_ITEM(t, 0);
649 Py_INCREF(r);
650 Py_DECREF(t);
651 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000652}
653
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000654/* determine whether x is an odd integer or not; assumes that
655 x is not an infinity or nan. */
656#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
657
Tim Peters63a35712001-12-11 19:57:24 +0000658static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000659float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 double iv, iw, ix;
662 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if ((PyObject *)z != Py_None) {
665 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
666 "allowed unless all arguments are integers");
667 return NULL;
668 }
Tim Peters32f453e2001-09-03 08:35:41 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 CONVERT_TO_DOUBLE(v, iv);
671 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 /* Sort out special cases here instead of relying on pow() */
674 if (iw == 0) { /* v**0 is 1, even 0**0 */
675 return PyFloat_FromDouble(1.0);
676 }
677 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
678 return PyFloat_FromDouble(iv);
679 }
680 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
681 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
682 }
683 if (Py_IS_INFINITY(iw)) {
684 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
685 * abs(v) > 1 (including case where v infinite)
686 *
687 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
688 * abs(v) > 1 (including case where v infinite)
689 */
690 iv = fabs(iv);
691 if (iv == 1.0)
692 return PyFloat_FromDouble(1.0);
693 else if ((iw > 0.0) == (iv > 1.0))
694 return PyFloat_FromDouble(fabs(iw)); /* return inf */
695 else
696 return PyFloat_FromDouble(0.0);
697 }
698 if (Py_IS_INFINITY(iv)) {
699 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
700 * both cases, we need to add the appropriate sign if w is
701 * an odd integer.
702 */
703 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
704 if (iw > 0.0)
705 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
706 else
707 return PyFloat_FromDouble(iw_is_odd ?
708 copysign(0.0, iv) : 0.0);
709 }
710 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
711 (already dealt with above), and an error
712 if w is negative. */
713 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
714 if (iw < 0.0) {
715 PyErr_SetString(PyExc_ZeroDivisionError,
716 "0.0 cannot be raised to a "
717 "negative power");
718 return NULL;
719 }
720 /* use correct sign if iw is odd */
721 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
722 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (iv < 0.0) {
725 /* Whether this is an error is a mess, and bumps into libm
726 * bugs so we have to figure it out ourselves.
727 */
728 if (iw != floor(iw)) {
729 /* Negative numbers raised to fractional powers
730 * become complex.
731 */
732 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
733 }
734 /* iw is an exact integer, albeit perhaps a very large
735 * one. Replace iv by its absolute value and remember
736 * to negate the pow result if iw is odd.
737 */
738 iv = -iv;
739 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
740 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
743 /* (-1) ** large_integer also ends up here. Here's an
744 * extract from the comments for the previous
745 * implementation explaining why this special case is
746 * necessary:
747 *
748 * -1 raised to an exact integer should never be exceptional.
749 * Alas, some libms (chiefly glibc as of early 2003) return
750 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
751 * happen to be representable in a *C* integer. That's a
752 * bug.
753 */
754 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
755 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Now iv and iw are finite, iw is nonzero, and iv is
758 * positive and not equal to 1.0. We finally allow
759 * the platform pow to step in and do the rest.
760 */
761 errno = 0;
762 PyFPE_START_PROTECT("pow", return NULL)
763 ix = pow(iv, iw);
764 PyFPE_END_PROTECT(ix)
765 Py_ADJUST_ERANGE1(ix);
766 if (negate_result)
767 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (errno != 0) {
770 /* We don't expect any errno value other than ERANGE, but
771 * the range of libm bugs appears unbounded.
772 */
773 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
774 PyExc_ValueError);
775 return NULL;
776 }
777 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778}
779
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000780#undef DOUBLE_IS_ODD_INTEGER
781
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000782static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000783float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786}
787
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000789float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792}
793
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000794static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000795float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000798}
799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000801float_is_integer(PyObject *v)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 double x = PyFloat_AsDouble(v);
804 PyObject *o;
805
806 if (x == -1.0 && PyErr_Occurred())
807 return NULL;
808 if (!Py_IS_FINITE(x))
809 Py_RETURN_FALSE;
810 errno = 0;
811 PyFPE_START_PROTECT("is_integer", return NULL)
812 o = (floor(x) == x) ? Py_True : Py_False;
813 PyFPE_END_PROTECT(x)
814 if (errno != 0) {
815 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
816 PyExc_ValueError);
817 return NULL;
818 }
819 Py_INCREF(o);
820 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000821}
822
823#if 0
824static PyObject *
825float_is_inf(PyObject *v)
826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 double x = PyFloat_AsDouble(v);
828 if (x == -1.0 && PyErr_Occurred())
829 return NULL;
830 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000831}
832
833static PyObject *
834float_is_nan(PyObject *v)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 double x = PyFloat_AsDouble(v);
837 if (x == -1.0 && PyErr_Occurred())
838 return NULL;
839 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000840}
841
842static PyObject *
843float_is_finite(PyObject *v)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 double x = PyFloat_AsDouble(v);
846 if (x == -1.0 && PyErr_Occurred())
847 return NULL;
848 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000849}
850#endif
851
852static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000853float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 double x = PyFloat_AsDouble(v);
856 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 (void)modf(x, &wholepart);
859 /* Try to get out cheap if this fits in a Python int. The attempt
860 * to cast to long must be protected, as C doesn't define what
861 * happens if the double is too big to fit in a long. Some rare
862 * systems raise an exception then (RISCOS was mentioned as one,
863 * and someone using a non-default option on Sun also bumped into
864 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
865 * still be vulnerable: if a long has more bits of precision than
866 * a double, casting MIN/MAX to double may yield an approximation,
867 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
868 * yield true from the C expression wholepart<=LONG_MAX, despite
869 * that wholepart is actually greater than LONG_MAX.
870 */
871 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
872 const long aslong = (long)wholepart;
873 return PyLong_FromLong(aslong);
874 }
875 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000876}
877
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000878/* double_round: rounds a finite double to the closest multiple of
879 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
880 ndigits <= 323). Returns a Python float, or sets a Python error and
881 returns NULL on failure (OverflowError and memory errors are possible). */
882
883#ifndef PY_NO_SHORT_FLOAT_REPR
884/* version of double_round that uses the correctly-rounded string<->double
885 conversions from Python/dtoa.c */
886
887static PyObject *
888double_round(double x, int ndigits) {
889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 double rounded;
891 Py_ssize_t buflen, mybuflen=100;
892 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
893 int decpt, sign;
894 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000895 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000898 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000900 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (buf == NULL) {
902 PyErr_NoMemory();
903 return NULL;
904 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
907 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
908 buflen = buf_end - buf;
909 if (buflen + 8 > mybuflen) {
910 mybuflen = buflen+8;
911 mybuf = (char *)PyMem_Malloc(mybuflen);
912 if (mybuf == NULL) {
913 PyErr_NoMemory();
914 goto exit;
915 }
916 }
917 /* copy buf to mybuf, adding exponent, sign and leading 0 */
918 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
919 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* and convert the resulting string back to a double */
922 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000923 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000925 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (errno == ERANGE && fabs(rounded) >= 1.)
927 PyErr_SetString(PyExc_OverflowError,
928 "rounded value too large to represent");
929 else
930 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* done computing value; now clean up */
933 if (mybuf != shortbuf)
934 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000935 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 _Py_dg_freedtoa(buf);
937 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000938}
939
940#else /* PY_NO_SHORT_FLOAT_REPR */
941
942/* fallback version, to be used when correctly rounded binary<->decimal
943 conversions aren't available */
944
945static PyObject *
946double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 double pow1, pow2, y, z;
948 if (ndigits >= 0) {
949 if (ndigits > 22) {
950 /* pow1 and pow2 are each safe from overflow, but
951 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
952 pow1 = pow(10.0, (double)(ndigits-22));
953 pow2 = 1e22;
954 }
955 else {
956 pow1 = pow(10.0, (double)ndigits);
957 pow2 = 1.0;
958 }
959 y = (x*pow1)*pow2;
960 /* if y overflows, then rounded value is exactly x */
961 if (!Py_IS_FINITE(y))
962 return PyFloat_FromDouble(x);
963 }
964 else {
965 pow1 = pow(10.0, (double)-ndigits);
966 pow2 = 1.0; /* unused; silences a gcc compiler warning */
967 y = x / pow1;
968 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 z = round(y);
971 if (fabs(y-z) == 0.5)
972 /* halfway between two integers; use round-half-even */
973 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (ndigits >= 0)
976 z = (z / pow2) / pow1;
977 else
978 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 /* if computation resulted in overflow, raise OverflowError */
981 if (!Py_IS_FINITE(z)) {
982 PyErr_SetString(PyExc_OverflowError,
983 "overflow occurred during round");
984 return NULL;
985 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000988}
989
990#endif /* PY_NO_SHORT_FLOAT_REPR */
991
992/* round a Python float v to the closest multiple of 10**-ndigits */
993
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000994static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000995float_round(PyObject *v, PyObject *args)
996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 double x, rounded;
998 PyObject *o_ndigits = NULL;
999 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 x = PyFloat_AsDouble(v);
1002 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1003 return NULL;
Steve Dowercb39d1f2015-04-15 16:10:59 -04001004 if (o_ndigits == NULL || o_ndigits == Py_None) {
1005 /* single-argument round or with None ndigits:
1006 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 rounded = round(x);
1008 if (fabs(x-rounded) == 0.5)
1009 /* halfway case: round to even */
1010 rounded = 2.0*round(x/2.0);
1011 return PyLong_FromDouble(rounded);
1012 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* interpret second argument as a Py_ssize_t; clips on overflow */
1015 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1016 if (ndigits == -1 && PyErr_Occurred())
1017 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* nans and infinities round to themselves */
1020 if (!Py_IS_FINITE(x))
1021 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1024 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1025 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1027#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (ndigits > NDIGITS_MAX)
1029 /* return x */
1030 return PyFloat_FromDouble(x);
1031 else if (ndigits < NDIGITS_MIN)
1032 /* return 0.0, but with sign of x */
1033 return PyFloat_FromDouble(0.0*x);
1034 else
1035 /* finite x, and ndigits is not unreasonably large */
1036 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001037#undef NDIGITS_MAX
1038#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001039}
1040
1041static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001042float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (PyFloat_CheckExact(v))
1045 Py_INCREF(v);
1046 else
1047 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1048 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001049}
1050
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001051/* turn ASCII hex characters into integer values and vice versa */
1052
1053static char
1054char_from_hex(int x)
1055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001057 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001058}
1059
1060static int
1061hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 int x;
1063 switch(c) {
1064 case '0':
1065 x = 0;
1066 break;
1067 case '1':
1068 x = 1;
1069 break;
1070 case '2':
1071 x = 2;
1072 break;
1073 case '3':
1074 x = 3;
1075 break;
1076 case '4':
1077 x = 4;
1078 break;
1079 case '5':
1080 x = 5;
1081 break;
1082 case '6':
1083 x = 6;
1084 break;
1085 case '7':
1086 x = 7;
1087 break;
1088 case '8':
1089 x = 8;
1090 break;
1091 case '9':
1092 x = 9;
1093 break;
1094 case 'a':
1095 case 'A':
1096 x = 10;
1097 break;
1098 case 'b':
1099 case 'B':
1100 x = 11;
1101 break;
1102 case 'c':
1103 case 'C':
1104 x = 12;
1105 break;
1106 case 'd':
1107 case 'D':
1108 x = 13;
1109 break;
1110 case 'e':
1111 case 'E':
1112 x = 14;
1113 break;
1114 case 'f':
1115 case 'F':
1116 x = 15;
1117 break;
1118 default:
1119 x = -1;
1120 break;
1121 }
1122 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001123}
1124
1125/* convert a float to a hexadecimal string */
1126
1127/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1128 of the form 4k+1. */
1129#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1130
1131static PyObject *
1132float_hex(PyObject *v)
1133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 double x, m;
1135 int e, shift, i, si, esign;
1136 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1137 trailing NUL byte. */
1138 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001143 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001146 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return PyUnicode_FromString("-0x0.0p+0");
1148 else
1149 return PyUnicode_FromString("0x0.0p+0");
1150 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001153 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 m = ldexp(m, shift);
1155 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 si = 0;
1158 s[si] = char_from_hex((int)m);
1159 si++;
1160 m -= (int)m;
1161 s[si] = '.';
1162 si++;
1163 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1164 m *= 16.0;
1165 s[si] = char_from_hex((int)m);
1166 si++;
1167 m -= (int)m;
1168 }
1169 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (e < 0) {
1172 esign = (int)'-';
1173 e = -e;
1174 }
1175 else
1176 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (x < 0.0)
1179 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1180 else
1181 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001182}
1183
1184PyDoc_STRVAR(float_hex_doc,
1185"float.hex() -> string\n\
1186\n\
1187Return a hexadecimal representation of a floating-point number.\n\
1188>>> (-0.1).hex()\n\
1189'-0x1.999999999999ap-4'\n\
1190>>> 3.14159.hex()\n\
1191'0x1.921f9f01b866ep+1'");
1192
1193/* Convert a hexadecimal string to a float. */
1194
1195static PyObject *
1196float_fromhex(PyObject *cls, PyObject *arg)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *result_as_float, *result;
1199 double x;
1200 long exp, top_exp, lsb, key_digit;
1201 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1202 int half_eps, digit, round_up, negate=0;
1203 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /*
1206 * For the sake of simplicity and correctness, we impose an artificial
1207 * limit on ndigits, the total number of hex digits in the coefficient
1208 * The limit is chosen to ensure that, writing exp for the exponent,
1209 *
1210 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1211 * guaranteed to overflow (provided it's nonzero)
1212 *
1213 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1214 * guaranteed to underflow to 0.
1215 *
1216 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1217 * overflow in the calculation of exp and top_exp below.
1218 *
1219 * More specifically, ndigits is assumed to satisfy the following
1220 * inequalities:
1221 *
1222 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1223 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1224 *
1225 * If either of these inequalities is not satisfied, a ValueError is
1226 * raised. Otherwise, write x for the value of the hex string, and
1227 * assume x is nonzero. Then
1228 *
1229 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1230 *
1231 * Now if exp > LONG_MAX/2 then:
1232 *
1233 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1234 * = DBL_MAX_EXP
1235 *
1236 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1237 * double, so overflows. If exp < LONG_MIN/2, then
1238 *
1239 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1240 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1241 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1242 *
1243 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1244 * when converted to a C double.
1245 *
1246 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1247 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1248 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 s = _PyUnicode_AsStringAndSize(arg, &length);
1251 if (s == NULL)
1252 return NULL;
1253 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /********************
1256 * Parse the string *
1257 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* leading whitespace */
1260 while (Py_ISSPACE(*s))
1261 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* infinities and nans */
1264 x = _Py_parse_inf_or_nan(s, &coeff_end);
1265 if (coeff_end != s) {
1266 s = coeff_end;
1267 goto finished;
1268 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* optional sign */
1271 if (*s == '-') {
1272 s++;
1273 negate = 1;
1274 }
1275 else if (*s == '+')
1276 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* [0x] */
1279 s_store = s;
1280 if (*s == '0') {
1281 s++;
1282 if (*s == 'x' || *s == 'X')
1283 s++;
1284 else
1285 s = s_store;
1286 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* coefficient: <integer> [. <fraction>] */
1289 coeff_start = s;
1290 while (hex_from_char(*s) >= 0)
1291 s++;
1292 s_store = s;
1293 if (*s == '.') {
1294 s++;
1295 while (hex_from_char(*s) >= 0)
1296 s++;
1297 coeff_end = s-1;
1298 }
1299 else
1300 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* ndigits = total # of hex digits; fdigits = # after point */
1303 ndigits = coeff_end - coeff_start;
1304 fdigits = coeff_end - s_store;
1305 if (ndigits == 0)
1306 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001307 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1308 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 /* [p <exponent>] */
1312 if (*s == 'p' || *s == 'P') {
1313 s++;
1314 exp_start = s;
1315 if (*s == '-' || *s == '+')
1316 s++;
1317 if (!('0' <= *s && *s <= '9'))
1318 goto parse_error;
1319 s++;
1320 while ('0' <= *s && *s <= '9')
1321 s++;
1322 exp = strtol(exp_start, NULL, 10);
1323 }
1324 else
1325 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001326
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1329 coeff_end-(j) : \
1330 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /*******************************************
1333 * Compute rounded value of the hex string *
1334 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* Discard leading zeros, and catch extreme overflow and underflow */
1337 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1338 ndigits--;
1339 if (ndigits == 0 || exp < LONG_MIN/2) {
1340 x = 0.0;
1341 goto finished;
1342 }
1343 if (exp > LONG_MAX/2)
1344 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* Adjust exponent for fractional part. */
1347 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1350 top_exp = exp + 4*((long)ndigits - 1);
1351 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1352 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 /* catch almost all nonextreme cases of overflow and underflow here */
1355 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1356 x = 0.0;
1357 goto finished;
1358 }
1359 if (top_exp > DBL_MAX_EXP)
1360 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* lsb = exponent of least significant bit of the *rounded* value.
1363 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001364 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 x = 0.0;
1367 if (exp >= lsb) {
1368 /* no rounding required */
1369 for (i = ndigits-1; i >= 0; i--)
1370 x = 16.0*x + HEX_DIGIT(i);
1371 x = ldexp(x, (int)(exp));
1372 goto finished;
1373 }
1374 /* rounding required. key_digit is the index of the hex digit
1375 containing the first bit to be rounded away. */
1376 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1377 key_digit = (lsb - exp - 1) / 4;
1378 for (i = ndigits-1; i > key_digit; i--)
1379 x = 16.0*x + HEX_DIGIT(i);
1380 digit = HEX_DIGIT(key_digit);
1381 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1384 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1385 if ((digit & half_eps) != 0) {
1386 round_up = 0;
1387 if ((digit & (3*half_eps-1)) != 0 ||
1388 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1389 round_up = 1;
1390 else
1391 for (i = key_digit-1; i >= 0; i--)
1392 if (HEX_DIGIT(i) != 0) {
1393 round_up = 1;
1394 break;
1395 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001396 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 x += 2*half_eps;
1398 if (top_exp == DBL_MAX_EXP &&
1399 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1400 /* overflow corner case: pre-rounded value <
1401 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1402 goto overflow_error;
1403 }
1404 }
1405 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406
1407 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* optional trailing whitespace leading to the end of the string */
1409 while (Py_ISSPACE(*s))
1410 s++;
1411 if (s != s_end)
1412 goto parse_error;
1413 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1414 if (result_as_float == NULL)
1415 return NULL;
1416 result = PyObject_CallObject(cls, result_as_float);
1417 Py_DECREF(result_as_float);
1418 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001419
1420 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 PyErr_SetString(PyExc_OverflowError,
1422 "hexadecimal value too large to represent as a float");
1423 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001424
1425 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyErr_SetString(PyExc_ValueError,
1427 "invalid hexadecimal floating-point string");
1428 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001429
1430 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyErr_SetString(PyExc_ValueError,
1432 "hexadecimal string too long to convert");
1433 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434}
1435
1436PyDoc_STRVAR(float_fromhex_doc,
1437"float.fromhex(string) -> float\n\
1438\n\
1439Create a floating-point number from a hexadecimal string.\n\
1440>>> float.fromhex('0x1.ffffp10')\n\
14412047.984375\n\
1442>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001443-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
1445
Christian Heimes26855632008-01-27 23:50:43 +00001446static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001447float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 double self;
1450 double float_part;
1451 int exponent;
1452 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *prev;
1455 PyObject *py_exponent = NULL;
1456 PyObject *numerator = NULL;
1457 PyObject *denominator = NULL;
1458 PyObject *result_pair = NULL;
1459 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001460
1461#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 prev = obj; \
1463 obj = call; \
1464 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (Py_IS_INFINITY(self)) {
1469 PyErr_SetString(PyExc_OverflowError,
1470 "Cannot pass infinity to float.as_integer_ratio.");
1471 return NULL;
1472 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (Py_IS_NAN(self)) {
1474 PyErr_SetString(PyExc_ValueError,
1475 "Cannot pass NaN to float.as_integer_ratio.");
1476 return NULL;
1477 }
Christian Heimes26855632008-01-27 23:50:43 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1480 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1481 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1484 float_part *= 2.0;
1485 exponent--;
1486 }
1487 /* self == float_part * 2**exponent exactly and float_part is integral.
1488 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1489 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 numerator = PyLong_FromDouble(float_part);
1492 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 /* fold in 2**exponent */
1495 denominator = PyLong_FromLong(1);
1496 py_exponent = PyLong_FromLong(labs((long)exponent));
1497 if (py_exponent == NULL) goto error;
1498 INPLACE_UPDATE(py_exponent,
1499 long_methods->nb_lshift(denominator, py_exponent));
1500 if (py_exponent == NULL) goto error;
1501 if (exponent > 0) {
1502 INPLACE_UPDATE(numerator,
1503 long_methods->nb_multiply(numerator, py_exponent));
1504 if (numerator == NULL) goto error;
1505 }
1506 else {
1507 Py_DECREF(denominator);
1508 denominator = py_exponent;
1509 py_exponent = NULL;
1510 }
1511
1512 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001513
1514#undef INPLACE_UPDATE
1515error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 Py_XDECREF(py_exponent);
1517 Py_XDECREF(denominator);
1518 Py_XDECREF(numerator);
1519 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001520}
1521
1522PyDoc_STRVAR(float_as_integer_ratio_doc,
1523"float.as_integer_ratio() -> (int, int)\n"
1524"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001525"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001526"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001527"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001528"\n"
1529">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001530"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001531">>> (0.0).as_integer_ratio()\n"
1532"(0, 1)\n"
1533">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001534"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001535
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001536
Jeremy Hylton938ace62002-07-17 16:30:39 +00001537static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001538float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1539
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540static PyObject *
1541float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyObject *x = Py_False; /* Integer zero */
1544 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (type != &PyFloat_Type)
1547 return float_subtype_new(type, args, kwds); /* Wimp out */
1548 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1549 return NULL;
1550 /* If it's a string, but not a string subclass, use
1551 PyFloat_FromString. */
1552 if (PyUnicode_CheckExact(x))
1553 return PyFloat_FromString(x);
1554 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555}
1556
Guido van Rossumbef14172001-08-29 15:47:46 +00001557/* Wimpy, slow approach to tp_new calls for subtypes of float:
1558 first create a regular float from whatever arguments we got,
1559 then allocate a subtype instance and initialize its ob_fval
1560 from the regular float. The regular float is then thrown away.
1561*/
1562static PyObject *
1563float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 assert(PyType_IsSubtype(type, &PyFloat_Type));
1568 tmp = float_new(&PyFloat_Type, args, kwds);
1569 if (tmp == NULL)
1570 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001571 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 newobj = type->tp_alloc(type, 0);
1573 if (newobj == NULL) {
1574 Py_DECREF(tmp);
1575 return NULL;
1576 }
1577 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1578 Py_DECREF(tmp);
1579 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001580}
1581
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001582static PyObject *
1583float_getnewargs(PyFloatObject *v)
1584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001586}
1587
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001588/* this is for the benefit of the pack/unpack routines below */
1589
1590typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001592} float_format_type;
1593
1594static float_format_type double_format, float_format;
1595static float_format_type detected_double_format, detected_float_format;
1596
1597static PyObject *
1598float_getformat(PyTypeObject *v, PyObject* arg)
1599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 char* s;
1601 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (!PyUnicode_Check(arg)) {
1604 PyErr_Format(PyExc_TypeError,
1605 "__getformat__() argument must be string, not %.500s",
1606 Py_TYPE(arg)->tp_name);
1607 return NULL;
1608 }
1609 s = _PyUnicode_AsString(arg);
1610 if (s == NULL)
1611 return NULL;
1612 if (strcmp(s, "double") == 0) {
1613 r = double_format;
1614 }
1615 else if (strcmp(s, "float") == 0) {
1616 r = float_format;
1617 }
1618 else {
1619 PyErr_SetString(PyExc_ValueError,
1620 "__getformat__() argument 1 must be "
1621 "'double' or 'float'");
1622 return NULL;
1623 }
1624
1625 switch (r) {
1626 case unknown_format:
1627 return PyUnicode_FromString("unknown");
1628 case ieee_little_endian_format:
1629 return PyUnicode_FromString("IEEE, little-endian");
1630 case ieee_big_endian_format:
1631 return PyUnicode_FromString("IEEE, big-endian");
1632 default:
1633 Py_FatalError("insane float_format or double_format");
1634 return NULL;
1635 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001636}
1637
1638PyDoc_STRVAR(float_getformat_doc,
1639"float.__getformat__(typestr) -> string\n"
1640"\n"
1641"You probably don't want to use this function. It exists mainly to be\n"
1642"used in Python's test suite.\n"
1643"\n"
1644"typestr must be 'double' or 'float'. This function returns whichever of\n"
1645"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1646"format of floating point numbers used by the C type named by typestr.");
1647
1648static PyObject *
1649float_setformat(PyTypeObject *v, PyObject* args)
1650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 char* typestr;
1652 char* format;
1653 float_format_type f;
1654 float_format_type detected;
1655 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1658 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (strcmp(typestr, "double") == 0) {
1661 p = &double_format;
1662 detected = detected_double_format;
1663 }
1664 else if (strcmp(typestr, "float") == 0) {
1665 p = &float_format;
1666 detected = detected_float_format;
1667 }
1668 else {
1669 PyErr_SetString(PyExc_ValueError,
1670 "__setformat__() argument 1 must "
1671 "be 'double' or 'float'");
1672 return NULL;
1673 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (strcmp(format, "unknown") == 0) {
1676 f = unknown_format;
1677 }
1678 else if (strcmp(format, "IEEE, little-endian") == 0) {
1679 f = ieee_little_endian_format;
1680 }
1681 else if (strcmp(format, "IEEE, big-endian") == 0) {
1682 f = ieee_big_endian_format;
1683 }
1684 else {
1685 PyErr_SetString(PyExc_ValueError,
1686 "__setformat__() argument 2 must be "
1687 "'unknown', 'IEEE, little-endian' or "
1688 "'IEEE, big-endian'");
1689 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (f != unknown_format && f != detected) {
1694 PyErr_Format(PyExc_ValueError,
1695 "can only set %s format to 'unknown' or the "
1696 "detected platform value", typestr);
1697 return NULL;
1698 }
1699
1700 *p = f;
1701 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001702}
1703
1704PyDoc_STRVAR(float_setformat_doc,
1705"float.__setformat__(typestr, fmt) -> None\n"
1706"\n"
1707"You probably don't want to use this function. It exists mainly to be\n"
1708"used in Python's test suite.\n"
1709"\n"
1710"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1711"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1712"one of the latter two if it appears to match the underlying C reality.\n"
1713"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001714"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001715"This affects how floats are converted to and from binary strings.");
1716
Guido van Rossumb43daf72007-08-01 18:08:08 +00001717static PyObject *
1718float_getzero(PyObject *v, void *closure)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001721}
1722
Eric Smith8c663262007-08-25 02:26:07 +00001723static PyObject *
1724float__format__(PyObject *self, PyObject *args)
1725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 _PyUnicodeWriter writer;
1728 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1731 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732
Victor Stinner8f674cc2013-04-17 23:02:17 +02001733 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001734 ret = _PyFloat_FormatAdvancedWriter(
1735 &writer,
1736 self,
1737 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1738 if (ret == -1) {
1739 _PyUnicodeWriter_Dealloc(&writer);
1740 return NULL;
1741 }
1742 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001743}
1744
1745PyDoc_STRVAR(float__format__doc,
1746"float.__format__(format_spec) -> string\n"
1747"\n"
1748"Formats the float according to format_spec.");
1749
1750
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001751static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001753 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001755 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001757 "Return the Integral closest to x, rounding half toward even.\n"
1758 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1760 float_as_integer_ratio_doc},
1761 {"fromhex", (PyCFunction)float_fromhex,
1762 METH_O|METH_CLASS, float_fromhex_doc},
1763 {"hex", (PyCFunction)float_hex,
1764 METH_NOARGS, float_hex_doc},
1765 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001766 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001767#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001769 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001771 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001773 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001774#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1776 {"__getformat__", (PyCFunction)float_getformat,
1777 METH_O|METH_CLASS, float_getformat_doc},
1778 {"__setformat__", (PyCFunction)float_setformat,
1779 METH_VARARGS|METH_CLASS, float_setformat_doc},
1780 {"__format__", (PyCFunction)float__format__,
1781 METH_VARARGS, float__format__doc},
1782 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001783};
1784
Guido van Rossumb43daf72007-08-01 18:08:08 +00001785static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001787 (getter)float_float, (setter)NULL,
1788 "the real part of a complex number",
1789 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001791 (getter)float_getzero, (setter)NULL,
1792 "the imaginary part of a complex number",
1793 NULL},
1794 {NULL} /* Sentinel */
1795};
1796
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001797PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798"float(x) -> floating point number\n\
1799\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801
1802
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001803static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 float_add, /*nb_add*/
1805 float_sub, /*nb_subtract*/
1806 float_mul, /*nb_multiply*/
1807 float_rem, /*nb_remainder*/
1808 float_divmod, /*nb_divmod*/
1809 float_pow, /*nb_power*/
1810 (unaryfunc)float_neg, /*nb_negative*/
1811 (unaryfunc)float_float, /*nb_positive*/
1812 (unaryfunc)float_abs, /*nb_absolute*/
1813 (inquiry)float_bool, /*nb_bool*/
1814 0, /*nb_invert*/
1815 0, /*nb_lshift*/
1816 0, /*nb_rshift*/
1817 0, /*nb_and*/
1818 0, /*nb_xor*/
1819 0, /*nb_or*/
1820 float_trunc, /*nb_int*/
1821 0, /*nb_reserved*/
1822 float_float, /*nb_float*/
1823 0, /* nb_inplace_add */
1824 0, /* nb_inplace_subtract */
1825 0, /* nb_inplace_multiply */
1826 0, /* nb_inplace_remainder */
1827 0, /* nb_inplace_power */
1828 0, /* nb_inplace_lshift */
1829 0, /* nb_inplace_rshift */
1830 0, /* nb_inplace_and */
1831 0, /* nb_inplace_xor */
1832 0, /* nb_inplace_or */
1833 float_floor_div, /* nb_floor_divide */
1834 float_div, /* nb_true_divide */
1835 0, /* nb_inplace_floor_divide */
1836 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001837};
1838
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001839PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1841 "float",
1842 sizeof(PyFloatObject),
1843 0,
1844 (destructor)float_dealloc, /* tp_dealloc */
1845 0, /* tp_print */
1846 0, /* tp_getattr */
1847 0, /* tp_setattr */
1848 0, /* tp_reserved */
1849 (reprfunc)float_repr, /* tp_repr */
1850 &float_as_number, /* tp_as_number */
1851 0, /* tp_as_sequence */
1852 0, /* tp_as_mapping */
1853 (hashfunc)float_hash, /* tp_hash */
1854 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001855 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 PyObject_GenericGetAttr, /* tp_getattro */
1857 0, /* tp_setattro */
1858 0, /* tp_as_buffer */
1859 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1860 float_doc, /* tp_doc */
1861 0, /* tp_traverse */
1862 0, /* tp_clear */
1863 float_richcompare, /* tp_richcompare */
1864 0, /* tp_weaklistoffset */
1865 0, /* tp_iter */
1866 0, /* tp_iternext */
1867 float_methods, /* tp_methods */
1868 0, /* tp_members */
1869 float_getset, /* tp_getset */
1870 0, /* tp_base */
1871 0, /* tp_dict */
1872 0, /* tp_descr_get */
1873 0, /* tp_descr_set */
1874 0, /* tp_dictoffset */
1875 0, /* tp_init */
1876 0, /* tp_alloc */
1877 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001879
Victor Stinner1c8f0592013-07-22 22:24:54 +02001880int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001881_PyFloat_Init(void)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* We attempt to determine if this machine is using IEEE
1884 floating point formats by peering at the bits of some
1885 carefully chosen values. If it looks like we are on an
1886 IEEE platform, the float packing/unpacking routines can
1887 just copy bits, if not they resort to arithmetic & shifts
1888 and masks. The shifts & masks approach works on all finite
1889 values, but what happens to infinities, NaNs and signed
1890 zeroes on packing is an accident, and attempting to unpack
1891 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 Note that if we're on some whacked-out platform which uses
1894 IEEE formats but isn't strictly little-endian or big-
1895 endian, we will fall back to the portable shifts & masks
1896 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001897
1898#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 {
1900 double x = 9006104071832581.0;
1901 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1902 detected_double_format = ieee_big_endian_format;
1903 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1904 detected_double_format = ieee_little_endian_format;
1905 else
1906 detected_double_format = unknown_format;
1907 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001910#endif
1911
1912#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 {
1914 float y = 16711938.0;
1915 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1916 detected_float_format = ieee_big_endian_format;
1917 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1918 detected_float_format = ieee_little_endian_format;
1919 else
1920 detected_float_format = unknown_format;
1921 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001922#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924#endif
1925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 double_format = detected_double_format;
1927 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001930 if (FloatInfoType.tp_name == NULL) {
1931 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1932 return 0;
1933 }
1934 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001935}
1936
Georg Brandl2ee470f2008-07-16 12:55:28 +00001937int
1938PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001939{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001940 PyFloatObject *f = free_list, *next;
1941 int i = numfree;
1942 while (f) {
1943 next = (PyFloatObject*) Py_TYPE(f);
1944 PyObject_FREE(f);
1945 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001947 free_list = NULL;
1948 numfree = 0;
1949 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001950}
1951
1952void
1953PyFloat_Fini(void)
1954{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001955 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001956}
Tim Peters9905b942003-03-20 20:53:32 +00001957
David Malcolm49526f42012-06-22 14:55:41 -04001958/* Print summary info about the state of the optimized allocator */
1959void
1960_PyFloat_DebugMallocStats(FILE *out)
1961{
1962 _PyDebugAllocatorStats(out,
1963 "free PyFloatObject",
1964 numfree, sizeof(PyFloatObject));
1965}
1966
1967
Tim Peters9905b942003-03-20 20:53:32 +00001968/*----------------------------------------------------------------------------
1969 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001970 */
1971int
1972_PyFloat_Pack4(double x, unsigned char *p, int le)
1973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (float_format == unknown_format) {
1975 unsigned char sign;
1976 int e;
1977 double f;
1978 unsigned int fbits;
1979 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (le) {
1982 p += 3;
1983 incr = -1;
1984 }
Tim Peters9905b942003-03-20 20:53:32 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (x < 0) {
1987 sign = 1;
1988 x = -x;
1989 }
1990 else
1991 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 /* Normalize f to be in the range [1.0, 2.0) */
1996 if (0.5 <= f && f < 1.0) {
1997 f *= 2.0;
1998 e--;
1999 }
2000 else if (f == 0.0)
2001 e = 0;
2002 else {
2003 PyErr_SetString(PyExc_SystemError,
2004 "frexp() result out of range");
2005 return -1;
2006 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (e >= 128)
2009 goto Overflow;
2010 else if (e < -126) {
2011 /* Gradual underflow */
2012 f = ldexp(f, 126 + e);
2013 e = 0;
2014 }
2015 else if (!(e == 0 && f == 0.0)) {
2016 e += 127;
2017 f -= 1.0; /* Get rid of leading 1 */
2018 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 f *= 8388608.0; /* 2**23 */
2021 fbits = (unsigned int)(f + 0.5); /* Round */
2022 assert(fbits <= 8388608);
2023 if (fbits >> 23) {
2024 /* The carry propagated out of a string of 23 1 bits. */
2025 fbits = 0;
2026 ++e;
2027 if (e >= 255)
2028 goto Overflow;
2029 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* First byte */
2032 *p = (sign << 7) | (e >> 1);
2033 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* Second byte */
2036 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2037 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* Third byte */
2040 *p = (fbits >> 8) & 0xFF;
2041 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 /* Fourth byte */
2044 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* Done */
2047 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 }
2050 else {
2051 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002052 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2056 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if ((float_format == ieee_little_endian_format && !le)
2059 || (float_format == ieee_big_endian_format && le)) {
2060 p += 3;
2061 incr = -1;
2062 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 for (i = 0; i < 4; i++) {
2065 *p = *s++;
2066 p += incr;
2067 }
2068 return 0;
2069 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002070 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 PyErr_SetString(PyExc_OverflowError,
2072 "float too large to pack with f format");
2073 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002074}
2075
2076int
2077_PyFloat_Pack8(double x, unsigned char *p, int le)
2078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (double_format == unknown_format) {
2080 unsigned char sign;
2081 int e;
2082 double f;
2083 unsigned int fhi, flo;
2084 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 if (le) {
2087 p += 7;
2088 incr = -1;
2089 }
Tim Peters9905b942003-03-20 20:53:32 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 if (x < 0) {
2092 sign = 1;
2093 x = -x;
2094 }
2095 else
2096 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* Normalize f to be in the range [1.0, 2.0) */
2101 if (0.5 <= f && f < 1.0) {
2102 f *= 2.0;
2103 e--;
2104 }
2105 else if (f == 0.0)
2106 e = 0;
2107 else {
2108 PyErr_SetString(PyExc_SystemError,
2109 "frexp() result out of range");
2110 return -1;
2111 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (e >= 1024)
2114 goto Overflow;
2115 else if (e < -1022) {
2116 /* Gradual underflow */
2117 f = ldexp(f, 1022 + e);
2118 e = 0;
2119 }
2120 else if (!(e == 0 && f == 0.0)) {
2121 e += 1023;
2122 f -= 1.0; /* Get rid of leading 1 */
2123 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2126 f *= 268435456.0; /* 2**28 */
2127 fhi = (unsigned int)f; /* Truncate */
2128 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 f -= (double)fhi;
2131 f *= 16777216.0; /* 2**24 */
2132 flo = (unsigned int)(f + 0.5); /* Round */
2133 assert(flo <= 16777216);
2134 if (flo >> 24) {
2135 /* The carry propagated out of a string of 24 1 bits. */
2136 flo = 0;
2137 ++fhi;
2138 if (fhi >> 28) {
2139 /* And it also progagated out of the next 28 bits. */
2140 fhi = 0;
2141 ++e;
2142 if (e >= 2047)
2143 goto Overflow;
2144 }
2145 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 /* First byte */
2148 *p = (sign << 7) | (e >> 4);
2149 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Second byte */
2152 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2153 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* Third byte */
2156 *p = (fhi >> 16) & 0xFF;
2157 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 /* Fourth byte */
2160 *p = (fhi >> 8) & 0xFF;
2161 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Fifth byte */
2164 *p = fhi & 0xFF;
2165 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Sixth byte */
2168 *p = (flo >> 16) & 0xFF;
2169 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Seventh byte */
2172 *p = (flo >> 8) & 0xFF;
2173 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* Eighth byte */
2176 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002177 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Done */
2180 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 Overflow:
2183 PyErr_SetString(PyExc_OverflowError,
2184 "float too large to pack with d format");
2185 return -1;
2186 }
2187 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002188 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if ((double_format == ieee_little_endian_format && !le)
2192 || (double_format == ieee_big_endian_format && le)) {
2193 p += 7;
2194 incr = -1;
2195 }
2196
2197 for (i = 0; i < 8; i++) {
2198 *p = *s++;
2199 p += incr;
2200 }
2201 return 0;
2202 }
Tim Peters9905b942003-03-20 20:53:32 +00002203}
2204
2205double
2206_PyFloat_Unpack4(const unsigned char *p, int le)
2207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (float_format == unknown_format) {
2209 unsigned char sign;
2210 int e;
2211 unsigned int f;
2212 double x;
2213 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (le) {
2216 p += 3;
2217 incr = -1;
2218 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* First byte */
2221 sign = (*p >> 7) & 1;
2222 e = (*p & 0x7F) << 1;
2223 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Second byte */
2226 e |= (*p >> 7) & 1;
2227 f = (*p & 0x7F) << 16;
2228 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (e == 255) {
2231 PyErr_SetString(
2232 PyExc_ValueError,
2233 "can't unpack IEEE 754 special value "
2234 "on non-IEEE platform");
2235 return -1;
2236 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Third byte */
2239 f |= *p << 8;
2240 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Fourth byte */
2243 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* XXX This sadly ignores Inf/NaN issues */
2248 if (e == 0)
2249 e = -126;
2250 else {
2251 x += 1.0;
2252 e -= 127;
2253 }
2254 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 if (sign)
2257 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 return x;
2260 }
2261 else {
2262 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if ((float_format == ieee_little_endian_format && !le)
2265 || (float_format == ieee_big_endian_format && le)) {
2266 char buf[4];
2267 char *d = &buf[3];
2268 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 for (i = 0; i < 4; i++) {
2271 *d-- = *p++;
2272 }
2273 memcpy(&x, buf, 4);
2274 }
2275 else {
2276 memcpy(&x, p, 4);
2277 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 return x;
2280 }
Tim Peters9905b942003-03-20 20:53:32 +00002281}
2282
2283double
2284_PyFloat_Unpack8(const unsigned char *p, int le)
2285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (double_format == unknown_format) {
2287 unsigned char sign;
2288 int e;
2289 unsigned int fhi, flo;
2290 double x;
2291 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 if (le) {
2294 p += 7;
2295 incr = -1;
2296 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* First byte */
2299 sign = (*p >> 7) & 1;
2300 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* Second byte */
2305 e |= (*p >> 4) & 0xF;
2306 fhi = (*p & 0xF) << 24;
2307 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (e == 2047) {
2310 PyErr_SetString(
2311 PyExc_ValueError,
2312 "can't unpack IEEE 754 special value "
2313 "on non-IEEE platform");
2314 return -1.0;
2315 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Third byte */
2318 fhi |= *p << 16;
2319 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Fourth byte */
2322 fhi |= *p << 8;
2323 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Fifth byte */
2326 fhi |= *p;
2327 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Sixth byte */
2330 flo = *p << 16;
2331 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* Seventh byte */
2334 flo |= *p << 8;
2335 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Eighth byte */
2338 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2341 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 if (e == 0)
2344 e = -1022;
2345 else {
2346 x += 1.0;
2347 e -= 1023;
2348 }
2349 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (sign)
2352 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 return x;
2355 }
2356 else {
2357 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if ((double_format == ieee_little_endian_format && !le)
2360 || (double_format == ieee_big_endian_format && le)) {
2361 char buf[8];
2362 char *d = &buf[7];
2363 int i;
2364
2365 for (i = 0; i < 8; i++) {
2366 *d-- = *p++;
2367 }
2368 memcpy(&x, buf, 8);
2369 }
2370 else {
2371 memcpy(&x, p, 8);
2372 }
2373
2374 return x;
2375 }
Tim Peters9905b942003-03-20 20:53:32 +00002376}