blob: 9c1b714af328f9f544bf6f352cc5b9a87f9e6a49 [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;
1004 if (o_ndigits == NULL) {
1005 /* single-argument round: round to nearest integer */
1006 rounded = round(x);
1007 if (fabs(x-rounded) == 0.5)
1008 /* halfway case: round to even */
1009 rounded = 2.0*round(x/2.0);
1010 return PyLong_FromDouble(rounded);
1011 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* interpret second argument as a Py_ssize_t; clips on overflow */
1014 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1015 if (ndigits == -1 && PyErr_Occurred())
1016 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* nans and infinities round to themselves */
1019 if (!Py_IS_FINITE(x))
1020 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1023 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1024 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001025#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1026#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (ndigits > NDIGITS_MAX)
1028 /* return x */
1029 return PyFloat_FromDouble(x);
1030 else if (ndigits < NDIGITS_MIN)
1031 /* return 0.0, but with sign of x */
1032 return PyFloat_FromDouble(0.0*x);
1033 else
1034 /* finite x, and ndigits is not unreasonably large */
1035 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001036#undef NDIGITS_MAX
1037#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001038}
1039
1040static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001041float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (PyFloat_CheckExact(v))
1044 Py_INCREF(v);
1045 else
1046 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1047 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001048}
1049
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001050/* turn ASCII hex characters into integer values and vice versa */
1051
1052static char
1053char_from_hex(int x)
1054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001056 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001057}
1058
1059static int
1060hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 int x;
1062 switch(c) {
1063 case '0':
1064 x = 0;
1065 break;
1066 case '1':
1067 x = 1;
1068 break;
1069 case '2':
1070 x = 2;
1071 break;
1072 case '3':
1073 x = 3;
1074 break;
1075 case '4':
1076 x = 4;
1077 break;
1078 case '5':
1079 x = 5;
1080 break;
1081 case '6':
1082 x = 6;
1083 break;
1084 case '7':
1085 x = 7;
1086 break;
1087 case '8':
1088 x = 8;
1089 break;
1090 case '9':
1091 x = 9;
1092 break;
1093 case 'a':
1094 case 'A':
1095 x = 10;
1096 break;
1097 case 'b':
1098 case 'B':
1099 x = 11;
1100 break;
1101 case 'c':
1102 case 'C':
1103 x = 12;
1104 break;
1105 case 'd':
1106 case 'D':
1107 x = 13;
1108 break;
1109 case 'e':
1110 case 'E':
1111 x = 14;
1112 break;
1113 case 'f':
1114 case 'F':
1115 x = 15;
1116 break;
1117 default:
1118 x = -1;
1119 break;
1120 }
1121 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001122}
1123
1124/* convert a float to a hexadecimal string */
1125
1126/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1127 of the form 4k+1. */
1128#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1129
1130static PyObject *
1131float_hex(PyObject *v)
1132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 double x, m;
1134 int e, shift, i, si, esign;
1135 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1136 trailing NUL byte. */
1137 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001142 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001145 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return PyUnicode_FromString("-0x0.0p+0");
1147 else
1148 return PyUnicode_FromString("0x0.0p+0");
1149 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001152 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 m = ldexp(m, shift);
1154 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 si = 0;
1157 s[si] = char_from_hex((int)m);
1158 si++;
1159 m -= (int)m;
1160 s[si] = '.';
1161 si++;
1162 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1163 m *= 16.0;
1164 s[si] = char_from_hex((int)m);
1165 si++;
1166 m -= (int)m;
1167 }
1168 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (e < 0) {
1171 esign = (int)'-';
1172 e = -e;
1173 }
1174 else
1175 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (x < 0.0)
1178 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1179 else
1180 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001181}
1182
1183PyDoc_STRVAR(float_hex_doc,
1184"float.hex() -> string\n\
1185\n\
1186Return a hexadecimal representation of a floating-point number.\n\
1187>>> (-0.1).hex()\n\
1188'-0x1.999999999999ap-4'\n\
1189>>> 3.14159.hex()\n\
1190'0x1.921f9f01b866ep+1'");
1191
1192/* Convert a hexadecimal string to a float. */
1193
1194static PyObject *
1195float_fromhex(PyObject *cls, PyObject *arg)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyObject *result_as_float, *result;
1198 double x;
1199 long exp, top_exp, lsb, key_digit;
1200 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1201 int half_eps, digit, round_up, negate=0;
1202 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /*
1205 * For the sake of simplicity and correctness, we impose an artificial
1206 * limit on ndigits, the total number of hex digits in the coefficient
1207 * The limit is chosen to ensure that, writing exp for the exponent,
1208 *
1209 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1210 * guaranteed to overflow (provided it's nonzero)
1211 *
1212 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1213 * guaranteed to underflow to 0.
1214 *
1215 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1216 * overflow in the calculation of exp and top_exp below.
1217 *
1218 * More specifically, ndigits is assumed to satisfy the following
1219 * inequalities:
1220 *
1221 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1222 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1223 *
1224 * If either of these inequalities is not satisfied, a ValueError is
1225 * raised. Otherwise, write x for the value of the hex string, and
1226 * assume x is nonzero. Then
1227 *
1228 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1229 *
1230 * Now if exp > LONG_MAX/2 then:
1231 *
1232 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1233 * = DBL_MAX_EXP
1234 *
1235 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1236 * double, so overflows. If exp < LONG_MIN/2, then
1237 *
1238 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1239 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1240 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1241 *
1242 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1243 * when converted to a C double.
1244 *
1245 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1246 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1247 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 s = _PyUnicode_AsStringAndSize(arg, &length);
1250 if (s == NULL)
1251 return NULL;
1252 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 /********************
1255 * Parse the string *
1256 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 /* leading whitespace */
1259 while (Py_ISSPACE(*s))
1260 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 /* infinities and nans */
1263 x = _Py_parse_inf_or_nan(s, &coeff_end);
1264 if (coeff_end != s) {
1265 s = coeff_end;
1266 goto finished;
1267 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* optional sign */
1270 if (*s == '-') {
1271 s++;
1272 negate = 1;
1273 }
1274 else if (*s == '+')
1275 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 /* [0x] */
1278 s_store = s;
1279 if (*s == '0') {
1280 s++;
1281 if (*s == 'x' || *s == 'X')
1282 s++;
1283 else
1284 s = s_store;
1285 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* coefficient: <integer> [. <fraction>] */
1288 coeff_start = s;
1289 while (hex_from_char(*s) >= 0)
1290 s++;
1291 s_store = s;
1292 if (*s == '.') {
1293 s++;
1294 while (hex_from_char(*s) >= 0)
1295 s++;
1296 coeff_end = s-1;
1297 }
1298 else
1299 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* ndigits = total # of hex digits; fdigits = # after point */
1302 ndigits = coeff_end - coeff_start;
1303 fdigits = coeff_end - s_store;
1304 if (ndigits == 0)
1305 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001306 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1307 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 /* [p <exponent>] */
1311 if (*s == 'p' || *s == 'P') {
1312 s++;
1313 exp_start = s;
1314 if (*s == '-' || *s == '+')
1315 s++;
1316 if (!('0' <= *s && *s <= '9'))
1317 goto parse_error;
1318 s++;
1319 while ('0' <= *s && *s <= '9')
1320 s++;
1321 exp = strtol(exp_start, NULL, 10);
1322 }
1323 else
1324 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001325
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001326/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1328 coeff_end-(j) : \
1329 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /*******************************************
1332 * Compute rounded value of the hex string *
1333 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* Discard leading zeros, and catch extreme overflow and underflow */
1336 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1337 ndigits--;
1338 if (ndigits == 0 || exp < LONG_MIN/2) {
1339 x = 0.0;
1340 goto finished;
1341 }
1342 if (exp > LONG_MAX/2)
1343 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 /* Adjust exponent for fractional part. */
1346 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1349 top_exp = exp + 4*((long)ndigits - 1);
1350 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1351 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* catch almost all nonextreme cases of overflow and underflow here */
1354 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1355 x = 0.0;
1356 goto finished;
1357 }
1358 if (top_exp > DBL_MAX_EXP)
1359 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /* lsb = exponent of least significant bit of the *rounded* value.
1362 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001363 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 x = 0.0;
1366 if (exp >= lsb) {
1367 /* no rounding required */
1368 for (i = ndigits-1; i >= 0; i--)
1369 x = 16.0*x + HEX_DIGIT(i);
1370 x = ldexp(x, (int)(exp));
1371 goto finished;
1372 }
1373 /* rounding required. key_digit is the index of the hex digit
1374 containing the first bit to be rounded away. */
1375 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1376 key_digit = (lsb - exp - 1) / 4;
1377 for (i = ndigits-1; i > key_digit; i--)
1378 x = 16.0*x + HEX_DIGIT(i);
1379 digit = HEX_DIGIT(key_digit);
1380 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1383 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1384 if ((digit & half_eps) != 0) {
1385 round_up = 0;
1386 if ((digit & (3*half_eps-1)) != 0 ||
1387 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1388 round_up = 1;
1389 else
1390 for (i = key_digit-1; i >= 0; i--)
1391 if (HEX_DIGIT(i) != 0) {
1392 round_up = 1;
1393 break;
1394 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001395 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 x += 2*half_eps;
1397 if (top_exp == DBL_MAX_EXP &&
1398 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1399 /* overflow corner case: pre-rounded value <
1400 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1401 goto overflow_error;
1402 }
1403 }
1404 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
1406 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 /* optional trailing whitespace leading to the end of the string */
1408 while (Py_ISSPACE(*s))
1409 s++;
1410 if (s != s_end)
1411 goto parse_error;
1412 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1413 if (result_as_float == NULL)
1414 return NULL;
1415 result = PyObject_CallObject(cls, result_as_float);
1416 Py_DECREF(result_as_float);
1417 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001418
1419 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyErr_SetString(PyExc_OverflowError,
1421 "hexadecimal value too large to represent as a float");
1422 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001423
1424 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyErr_SetString(PyExc_ValueError,
1426 "invalid hexadecimal floating-point string");
1427 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001428
1429 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyErr_SetString(PyExc_ValueError,
1431 "hexadecimal string too long to convert");
1432 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001433}
1434
1435PyDoc_STRVAR(float_fromhex_doc,
1436"float.fromhex(string) -> float\n\
1437\n\
1438Create a floating-point number from a hexadecimal string.\n\
1439>>> float.fromhex('0x1.ffffp10')\n\
14402047.984375\n\
1441>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001442-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001443
1444
Christian Heimes26855632008-01-27 23:50:43 +00001445static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001446float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 double self;
1449 double float_part;
1450 int exponent;
1451 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *prev;
1454 PyObject *py_exponent = NULL;
1455 PyObject *numerator = NULL;
1456 PyObject *denominator = NULL;
1457 PyObject *result_pair = NULL;
1458 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001459
1460#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 prev = obj; \
1462 obj = call; \
1463 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (Py_IS_INFINITY(self)) {
1468 PyErr_SetString(PyExc_OverflowError,
1469 "Cannot pass infinity to float.as_integer_ratio.");
1470 return NULL;
1471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (Py_IS_NAN(self)) {
1473 PyErr_SetString(PyExc_ValueError,
1474 "Cannot pass NaN to float.as_integer_ratio.");
1475 return NULL;
1476 }
Christian Heimes26855632008-01-27 23:50:43 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1479 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1480 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1483 float_part *= 2.0;
1484 exponent--;
1485 }
1486 /* self == float_part * 2**exponent exactly and float_part is integral.
1487 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1488 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 numerator = PyLong_FromDouble(float_part);
1491 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 /* fold in 2**exponent */
1494 denominator = PyLong_FromLong(1);
1495 py_exponent = PyLong_FromLong(labs((long)exponent));
1496 if (py_exponent == NULL) goto error;
1497 INPLACE_UPDATE(py_exponent,
1498 long_methods->nb_lshift(denominator, py_exponent));
1499 if (py_exponent == NULL) goto error;
1500 if (exponent > 0) {
1501 INPLACE_UPDATE(numerator,
1502 long_methods->nb_multiply(numerator, py_exponent));
1503 if (numerator == NULL) goto error;
1504 }
1505 else {
1506 Py_DECREF(denominator);
1507 denominator = py_exponent;
1508 py_exponent = NULL;
1509 }
1510
1511 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001512
1513#undef INPLACE_UPDATE
1514error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_XDECREF(py_exponent);
1516 Py_XDECREF(denominator);
1517 Py_XDECREF(numerator);
1518 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001519}
1520
1521PyDoc_STRVAR(float_as_integer_ratio_doc,
1522"float.as_integer_ratio() -> (int, int)\n"
1523"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001524"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001525"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001526"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001527"\n"
1528">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001529"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001530">>> (0.0).as_integer_ratio()\n"
1531"(0, 1)\n"
1532">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001533"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001534
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001535
Jeremy Hylton938ace62002-07-17 16:30:39 +00001536static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001537float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1538
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539static PyObject *
1540float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 PyObject *x = Py_False; /* Integer zero */
1543 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (type != &PyFloat_Type)
1546 return float_subtype_new(type, args, kwds); /* Wimp out */
1547 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1548 return NULL;
1549 /* If it's a string, but not a string subclass, use
1550 PyFloat_FromString. */
1551 if (PyUnicode_CheckExact(x))
1552 return PyFloat_FromString(x);
1553 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554}
1555
Guido van Rossumbef14172001-08-29 15:47:46 +00001556/* Wimpy, slow approach to tp_new calls for subtypes of float:
1557 first create a regular float from whatever arguments we got,
1558 then allocate a subtype instance and initialize its ob_fval
1559 from the regular float. The regular float is then thrown away.
1560*/
1561static PyObject *
1562float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 assert(PyType_IsSubtype(type, &PyFloat_Type));
1567 tmp = float_new(&PyFloat_Type, args, kwds);
1568 if (tmp == NULL)
1569 return NULL;
1570 assert(PyFloat_CheckExact(tmp));
1571 newobj = type->tp_alloc(type, 0);
1572 if (newobj == NULL) {
1573 Py_DECREF(tmp);
1574 return NULL;
1575 }
1576 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1577 Py_DECREF(tmp);
1578 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001579}
1580
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001581static PyObject *
1582float_getnewargs(PyFloatObject *v)
1583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001585}
1586
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001587/* this is for the benefit of the pack/unpack routines below */
1588
1589typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001591} float_format_type;
1592
1593static float_format_type double_format, float_format;
1594static float_format_type detected_double_format, detected_float_format;
1595
1596static PyObject *
1597float_getformat(PyTypeObject *v, PyObject* arg)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 char* s;
1600 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (!PyUnicode_Check(arg)) {
1603 PyErr_Format(PyExc_TypeError,
1604 "__getformat__() argument must be string, not %.500s",
1605 Py_TYPE(arg)->tp_name);
1606 return NULL;
1607 }
1608 s = _PyUnicode_AsString(arg);
1609 if (s == NULL)
1610 return NULL;
1611 if (strcmp(s, "double") == 0) {
1612 r = double_format;
1613 }
1614 else if (strcmp(s, "float") == 0) {
1615 r = float_format;
1616 }
1617 else {
1618 PyErr_SetString(PyExc_ValueError,
1619 "__getformat__() argument 1 must be "
1620 "'double' or 'float'");
1621 return NULL;
1622 }
1623
1624 switch (r) {
1625 case unknown_format:
1626 return PyUnicode_FromString("unknown");
1627 case ieee_little_endian_format:
1628 return PyUnicode_FromString("IEEE, little-endian");
1629 case ieee_big_endian_format:
1630 return PyUnicode_FromString("IEEE, big-endian");
1631 default:
1632 Py_FatalError("insane float_format or double_format");
1633 return NULL;
1634 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001635}
1636
1637PyDoc_STRVAR(float_getformat_doc,
1638"float.__getformat__(typestr) -> string\n"
1639"\n"
1640"You probably don't want to use this function. It exists mainly to be\n"
1641"used in Python's test suite.\n"
1642"\n"
1643"typestr must be 'double' or 'float'. This function returns whichever of\n"
1644"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1645"format of floating point numbers used by the C type named by typestr.");
1646
1647static PyObject *
1648float_setformat(PyTypeObject *v, PyObject* args)
1649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 char* typestr;
1651 char* format;
1652 float_format_type f;
1653 float_format_type detected;
1654 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1657 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (strcmp(typestr, "double") == 0) {
1660 p = &double_format;
1661 detected = detected_double_format;
1662 }
1663 else if (strcmp(typestr, "float") == 0) {
1664 p = &float_format;
1665 detected = detected_float_format;
1666 }
1667 else {
1668 PyErr_SetString(PyExc_ValueError,
1669 "__setformat__() argument 1 must "
1670 "be 'double' or 'float'");
1671 return NULL;
1672 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (strcmp(format, "unknown") == 0) {
1675 f = unknown_format;
1676 }
1677 else if (strcmp(format, "IEEE, little-endian") == 0) {
1678 f = ieee_little_endian_format;
1679 }
1680 else if (strcmp(format, "IEEE, big-endian") == 0) {
1681 f = ieee_big_endian_format;
1682 }
1683 else {
1684 PyErr_SetString(PyExc_ValueError,
1685 "__setformat__() argument 2 must be "
1686 "'unknown', 'IEEE, little-endian' or "
1687 "'IEEE, big-endian'");
1688 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (f != unknown_format && f != detected) {
1693 PyErr_Format(PyExc_ValueError,
1694 "can only set %s format to 'unknown' or the "
1695 "detected platform value", typestr);
1696 return NULL;
1697 }
1698
1699 *p = f;
1700 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001701}
1702
1703PyDoc_STRVAR(float_setformat_doc,
1704"float.__setformat__(typestr, fmt) -> None\n"
1705"\n"
1706"You probably don't want to use this function. It exists mainly to be\n"
1707"used in Python's test suite.\n"
1708"\n"
1709"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1710"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1711"one of the latter two if it appears to match the underlying C reality.\n"
1712"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001713"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001714"This affects how floats are converted to and from binary strings.");
1715
Guido van Rossumb43daf72007-08-01 18:08:08 +00001716static PyObject *
1717float_getzero(PyObject *v, void *closure)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001720}
1721
Eric Smith8c663262007-08-25 02:26:07 +00001722static PyObject *
1723float__format__(PyObject *self, PyObject *args)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 _PyUnicodeWriter writer;
1727 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1730 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001731
Victor Stinner8f674cc2013-04-17 23:02:17 +02001732 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 ret = _PyFloat_FormatAdvancedWriter(
1734 &writer,
1735 self,
1736 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1737 if (ret == -1) {
1738 _PyUnicodeWriter_Dealloc(&writer);
1739 return NULL;
1740 }
1741 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001742}
1743
1744PyDoc_STRVAR(float__format__doc,
1745"float.__format__(format_spec) -> string\n"
1746"\n"
1747"Formats the float according to format_spec.");
1748
1749
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001750static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001752 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001754 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001756 "Return the Integral closest to x, rounding half toward even.\n"
1757 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1759 float_as_integer_ratio_doc},
1760 {"fromhex", (PyCFunction)float_fromhex,
1761 METH_O|METH_CLASS, float_fromhex_doc},
1762 {"hex", (PyCFunction)float_hex,
1763 METH_NOARGS, float_hex_doc},
1764 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001765 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001766#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001768 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001770 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001772 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001773#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1775 {"__getformat__", (PyCFunction)float_getformat,
1776 METH_O|METH_CLASS, float_getformat_doc},
1777 {"__setformat__", (PyCFunction)float_setformat,
1778 METH_VARARGS|METH_CLASS, float_setformat_doc},
1779 {"__format__", (PyCFunction)float__format__,
1780 METH_VARARGS, float__format__doc},
1781 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001782};
1783
Guido van Rossumb43daf72007-08-01 18:08:08 +00001784static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001786 (getter)float_float, (setter)NULL,
1787 "the real part of a complex number",
1788 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001790 (getter)float_getzero, (setter)NULL,
1791 "the imaginary part of a complex number",
1792 NULL},
1793 {NULL} /* Sentinel */
1794};
1795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797"float(x) -> floating point number\n\
1798\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001799Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800
1801
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001802static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 float_add, /*nb_add*/
1804 float_sub, /*nb_subtract*/
1805 float_mul, /*nb_multiply*/
1806 float_rem, /*nb_remainder*/
1807 float_divmod, /*nb_divmod*/
1808 float_pow, /*nb_power*/
1809 (unaryfunc)float_neg, /*nb_negative*/
1810 (unaryfunc)float_float, /*nb_positive*/
1811 (unaryfunc)float_abs, /*nb_absolute*/
1812 (inquiry)float_bool, /*nb_bool*/
1813 0, /*nb_invert*/
1814 0, /*nb_lshift*/
1815 0, /*nb_rshift*/
1816 0, /*nb_and*/
1817 0, /*nb_xor*/
1818 0, /*nb_or*/
1819 float_trunc, /*nb_int*/
1820 0, /*nb_reserved*/
1821 float_float, /*nb_float*/
1822 0, /* nb_inplace_add */
1823 0, /* nb_inplace_subtract */
1824 0, /* nb_inplace_multiply */
1825 0, /* nb_inplace_remainder */
1826 0, /* nb_inplace_power */
1827 0, /* nb_inplace_lshift */
1828 0, /* nb_inplace_rshift */
1829 0, /* nb_inplace_and */
1830 0, /* nb_inplace_xor */
1831 0, /* nb_inplace_or */
1832 float_floor_div, /* nb_floor_divide */
1833 float_div, /* nb_true_divide */
1834 0, /* nb_inplace_floor_divide */
1835 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001836};
1837
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001838PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1840 "float",
1841 sizeof(PyFloatObject),
1842 0,
1843 (destructor)float_dealloc, /* tp_dealloc */
1844 0, /* tp_print */
1845 0, /* tp_getattr */
1846 0, /* tp_setattr */
1847 0, /* tp_reserved */
1848 (reprfunc)float_repr, /* tp_repr */
1849 &float_as_number, /* tp_as_number */
1850 0, /* tp_as_sequence */
1851 0, /* tp_as_mapping */
1852 (hashfunc)float_hash, /* tp_hash */
1853 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001854 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 PyObject_GenericGetAttr, /* tp_getattro */
1856 0, /* tp_setattro */
1857 0, /* tp_as_buffer */
1858 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1859 float_doc, /* tp_doc */
1860 0, /* tp_traverse */
1861 0, /* tp_clear */
1862 float_richcompare, /* tp_richcompare */
1863 0, /* tp_weaklistoffset */
1864 0, /* tp_iter */
1865 0, /* tp_iternext */
1866 float_methods, /* tp_methods */
1867 0, /* tp_members */
1868 float_getset, /* tp_getset */
1869 0, /* tp_base */
1870 0, /* tp_dict */
1871 0, /* tp_descr_get */
1872 0, /* tp_descr_set */
1873 0, /* tp_dictoffset */
1874 0, /* tp_init */
1875 0, /* tp_alloc */
1876 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001877};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001878
Victor Stinner1c8f0592013-07-22 22:24:54 +02001879int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001880_PyFloat_Init(void)
1881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* We attempt to determine if this machine is using IEEE
1883 floating point formats by peering at the bits of some
1884 carefully chosen values. If it looks like we are on an
1885 IEEE platform, the float packing/unpacking routines can
1886 just copy bits, if not they resort to arithmetic & shifts
1887 and masks. The shifts & masks approach works on all finite
1888 values, but what happens to infinities, NaNs and signed
1889 zeroes on packing is an accident, and attempting to unpack
1890 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 Note that if we're on some whacked-out platform which uses
1893 IEEE formats but isn't strictly little-endian or big-
1894 endian, we will fall back to the portable shifts & masks
1895 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001896
1897#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 {
1899 double x = 9006104071832581.0;
1900 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1901 detected_double_format = ieee_big_endian_format;
1902 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1903 detected_double_format = ieee_little_endian_format;
1904 else
1905 detected_double_format = unknown_format;
1906 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001909#endif
1910
1911#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 {
1913 float y = 16711938.0;
1914 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1915 detected_float_format = ieee_big_endian_format;
1916 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1917 detected_float_format = ieee_little_endian_format;
1918 else
1919 detected_float_format = unknown_format;
1920 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001921#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001923#endif
1924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 double_format = detected_double_format;
1926 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001929 if (FloatInfoType.tp_name == NULL) {
1930 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1931 return 0;
1932 }
1933 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001934}
1935
Georg Brandl2ee470f2008-07-16 12:55:28 +00001936int
1937PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001938{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001939 PyFloatObject *f = free_list, *next;
1940 int i = numfree;
1941 while (f) {
1942 next = (PyFloatObject*) Py_TYPE(f);
1943 PyObject_FREE(f);
1944 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001946 free_list = NULL;
1947 numfree = 0;
1948 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001949}
1950
1951void
1952PyFloat_Fini(void)
1953{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001954 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001955}
Tim Peters9905b942003-03-20 20:53:32 +00001956
David Malcolm49526f42012-06-22 14:55:41 -04001957/* Print summary info about the state of the optimized allocator */
1958void
1959_PyFloat_DebugMallocStats(FILE *out)
1960{
1961 _PyDebugAllocatorStats(out,
1962 "free PyFloatObject",
1963 numfree, sizeof(PyFloatObject));
1964}
1965
1966
Tim Peters9905b942003-03-20 20:53:32 +00001967/*----------------------------------------------------------------------------
1968 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001969 */
1970int
1971_PyFloat_Pack4(double x, unsigned char *p, int le)
1972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (float_format == unknown_format) {
1974 unsigned char sign;
1975 int e;
1976 double f;
1977 unsigned int fbits;
1978 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (le) {
1981 p += 3;
1982 incr = -1;
1983 }
Tim Peters9905b942003-03-20 20:53:32 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (x < 0) {
1986 sign = 1;
1987 x = -x;
1988 }
1989 else
1990 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* Normalize f to be in the range [1.0, 2.0) */
1995 if (0.5 <= f && f < 1.0) {
1996 f *= 2.0;
1997 e--;
1998 }
1999 else if (f == 0.0)
2000 e = 0;
2001 else {
2002 PyErr_SetString(PyExc_SystemError,
2003 "frexp() result out of range");
2004 return -1;
2005 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (e >= 128)
2008 goto Overflow;
2009 else if (e < -126) {
2010 /* Gradual underflow */
2011 f = ldexp(f, 126 + e);
2012 e = 0;
2013 }
2014 else if (!(e == 0 && f == 0.0)) {
2015 e += 127;
2016 f -= 1.0; /* Get rid of leading 1 */
2017 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 f *= 8388608.0; /* 2**23 */
2020 fbits = (unsigned int)(f + 0.5); /* Round */
2021 assert(fbits <= 8388608);
2022 if (fbits >> 23) {
2023 /* The carry propagated out of a string of 23 1 bits. */
2024 fbits = 0;
2025 ++e;
2026 if (e >= 255)
2027 goto Overflow;
2028 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* First byte */
2031 *p = (sign << 7) | (e >> 1);
2032 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 /* Second byte */
2035 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2036 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* Third byte */
2039 *p = (fbits >> 8) & 0xFF;
2040 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 /* Fourth byte */
2043 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 /* Done */
2046 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 }
2049 else {
2050 float y = (float)x;
2051 const char *s = (char*)&y;
2052 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2055 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if ((float_format == ieee_little_endian_format && !le)
2058 || (float_format == ieee_big_endian_format && le)) {
2059 p += 3;
2060 incr = -1;
2061 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 for (i = 0; i < 4; i++) {
2064 *p = *s++;
2065 p += incr;
2066 }
2067 return 0;
2068 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002069 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyErr_SetString(PyExc_OverflowError,
2071 "float too large to pack with f format");
2072 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002073}
2074
2075int
2076_PyFloat_Pack8(double x, unsigned char *p, int le)
2077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 if (double_format == unknown_format) {
2079 unsigned char sign;
2080 int e;
2081 double f;
2082 unsigned int fhi, flo;
2083 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (le) {
2086 p += 7;
2087 incr = -1;
2088 }
Tim Peters9905b942003-03-20 20:53:32 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (x < 0) {
2091 sign = 1;
2092 x = -x;
2093 }
2094 else
2095 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* Normalize f to be in the range [1.0, 2.0) */
2100 if (0.5 <= f && f < 1.0) {
2101 f *= 2.0;
2102 e--;
2103 }
2104 else if (f == 0.0)
2105 e = 0;
2106 else {
2107 PyErr_SetString(PyExc_SystemError,
2108 "frexp() result out of range");
2109 return -1;
2110 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (e >= 1024)
2113 goto Overflow;
2114 else if (e < -1022) {
2115 /* Gradual underflow */
2116 f = ldexp(f, 1022 + e);
2117 e = 0;
2118 }
2119 else if (!(e == 0 && f == 0.0)) {
2120 e += 1023;
2121 f -= 1.0; /* Get rid of leading 1 */
2122 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2125 f *= 268435456.0; /* 2**28 */
2126 fhi = (unsigned int)f; /* Truncate */
2127 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 f -= (double)fhi;
2130 f *= 16777216.0; /* 2**24 */
2131 flo = (unsigned int)(f + 0.5); /* Round */
2132 assert(flo <= 16777216);
2133 if (flo >> 24) {
2134 /* The carry propagated out of a string of 24 1 bits. */
2135 flo = 0;
2136 ++fhi;
2137 if (fhi >> 28) {
2138 /* And it also progagated out of the next 28 bits. */
2139 fhi = 0;
2140 ++e;
2141 if (e >= 2047)
2142 goto Overflow;
2143 }
2144 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* First byte */
2147 *p = (sign << 7) | (e >> 4);
2148 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 /* Second byte */
2151 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2152 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 /* Third byte */
2155 *p = (fhi >> 16) & 0xFF;
2156 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 /* Fourth byte */
2159 *p = (fhi >> 8) & 0xFF;
2160 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 /* Fifth byte */
2163 *p = fhi & 0xFF;
2164 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* Sixth byte */
2167 *p = (flo >> 16) & 0xFF;
2168 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* Seventh byte */
2171 *p = (flo >> 8) & 0xFF;
2172 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Eighth byte */
2175 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002176 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 /* Done */
2179 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 Overflow:
2182 PyErr_SetString(PyExc_OverflowError,
2183 "float too large to pack with d format");
2184 return -1;
2185 }
2186 else {
2187 const char *s = (char*)&x;
2188 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if ((double_format == ieee_little_endian_format && !le)
2191 || (double_format == ieee_big_endian_format && le)) {
2192 p += 7;
2193 incr = -1;
2194 }
2195
2196 for (i = 0; i < 8; i++) {
2197 *p = *s++;
2198 p += incr;
2199 }
2200 return 0;
2201 }
Tim Peters9905b942003-03-20 20:53:32 +00002202}
2203
2204double
2205_PyFloat_Unpack4(const unsigned char *p, int le)
2206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (float_format == unknown_format) {
2208 unsigned char sign;
2209 int e;
2210 unsigned int f;
2211 double x;
2212 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (le) {
2215 p += 3;
2216 incr = -1;
2217 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* First byte */
2220 sign = (*p >> 7) & 1;
2221 e = (*p & 0x7F) << 1;
2222 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Second byte */
2225 e |= (*p >> 7) & 1;
2226 f = (*p & 0x7F) << 16;
2227 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 if (e == 255) {
2230 PyErr_SetString(
2231 PyExc_ValueError,
2232 "can't unpack IEEE 754 special value "
2233 "on non-IEEE platform");
2234 return -1;
2235 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Third byte */
2238 f |= *p << 8;
2239 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Fourth byte */
2242 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* XXX This sadly ignores Inf/NaN issues */
2247 if (e == 0)
2248 e = -126;
2249 else {
2250 x += 1.0;
2251 e -= 127;
2252 }
2253 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (sign)
2256 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return x;
2259 }
2260 else {
2261 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if ((float_format == ieee_little_endian_format && !le)
2264 || (float_format == ieee_big_endian_format && le)) {
2265 char buf[4];
2266 char *d = &buf[3];
2267 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 for (i = 0; i < 4; i++) {
2270 *d-- = *p++;
2271 }
2272 memcpy(&x, buf, 4);
2273 }
2274 else {
2275 memcpy(&x, p, 4);
2276 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 return x;
2279 }
Tim Peters9905b942003-03-20 20:53:32 +00002280}
2281
2282double
2283_PyFloat_Unpack8(const unsigned char *p, int le)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (double_format == unknown_format) {
2286 unsigned char sign;
2287 int e;
2288 unsigned int fhi, flo;
2289 double x;
2290 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (le) {
2293 p += 7;
2294 incr = -1;
2295 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* First byte */
2298 sign = (*p >> 7) & 1;
2299 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* Second byte */
2304 e |= (*p >> 4) & 0xF;
2305 fhi = (*p & 0xF) << 24;
2306 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 if (e == 2047) {
2309 PyErr_SetString(
2310 PyExc_ValueError,
2311 "can't unpack IEEE 754 special value "
2312 "on non-IEEE platform");
2313 return -1.0;
2314 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* Third byte */
2317 fhi |= *p << 16;
2318 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Fourth byte */
2321 fhi |= *p << 8;
2322 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Fifth byte */
2325 fhi |= *p;
2326 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 /* Sixth byte */
2329 flo = *p << 16;
2330 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Seventh byte */
2333 flo |= *p << 8;
2334 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* Eighth byte */
2337 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2340 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 if (e == 0)
2343 e = -1022;
2344 else {
2345 x += 1.0;
2346 e -= 1023;
2347 }
2348 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (sign)
2351 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return x;
2354 }
2355 else {
2356 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 if ((double_format == ieee_little_endian_format && !le)
2359 || (double_format == ieee_big_endian_format && le)) {
2360 char buf[8];
2361 char *d = &buf[7];
2362 int i;
2363
2364 for (i = 0; i < 8; i++) {
2365 *d-- = *p++;
2366 }
2367 memcpy(&x, buf, 8);
2368 }
2369 else {
2370 memcpy(&x, p, 8);
2371 }
2372
2373 return x;
2374 }
Tim Peters9905b942003-03-20 20:53:32 +00002375}