blob: eb60659615fbec5f08436e61388bfa5342580151 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Guido van Rossum6923e131990-11-02 17:50:43 +000012
Mark Dickinsond19052c2010-06-27 18:19:09 +000013/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000014 free_list is a singly-linked list of available PyFloatObjects, linked
15 via abuse of their ob_type members.
16*/
17
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000018#ifndef PyFloat_MAXFREELIST
19#define PyFloat_MAXFREELIST 100
20#endif
21static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000022static PyFloatObject *free_list = NULL;
23
Christian Heimes93852662007-12-01 12:22:32 +000024double
25PyFloat_GetMax(void)
26{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000028}
29
30double
31PyFloat_GetMin(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
Christian Heimesd32ed6f2008-01-14 18:49:24 +000036static PyTypeObject FloatInfoType;
37
38PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000039"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000040\n\
41A structseq holding information about the float type. It contains low level\n\
42information about the precision and internal representation. Please study\n\
43your system's :file:`float.h` for more information.");
44
45static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 {"max", "DBL_MAX -- maximum representable finite float"},
47 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
48 "is representable"},
49 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
50 "is representable"},
51 {"min", "DBL_MIN -- Minimum positive normalizer float"},
52 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
53 "is a normalized float"},
54 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
55 "a normalized"},
56 {"dig", "DBL_DIG -- digits"},
57 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
58 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
59 "representable float"},
60 {"radix", "FLT_RADIX -- radix of exponent"},
61 {"rounds", "FLT_ROUNDS -- addition rounds"},
62 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000063};
64
65static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 "sys.float_info", /* name */
67 floatinfo__doc__, /* doc */
68 floatinfo_fields, /* fields */
69 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000070};
71
Christian Heimes93852662007-12-01 12:22:32 +000072PyObject *
73PyFloat_GetInfo(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject* floatinfo;
76 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 floatinfo = PyStructSequence_New(&FloatInfoType);
79 if (floatinfo == NULL) {
80 return NULL;
81 }
Christian Heimes93852662007-12-01 12:22:32 +000082
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000085#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 SetDblFlag(DBL_MAX);
89 SetIntFlag(DBL_MAX_EXP);
90 SetIntFlag(DBL_MAX_10_EXP);
91 SetDblFlag(DBL_MIN);
92 SetIntFlag(DBL_MIN_EXP);
93 SetIntFlag(DBL_MIN_10_EXP);
94 SetIntFlag(DBL_DIG);
95 SetIntFlag(DBL_MANT_DIG);
96 SetDblFlag(DBL_EPSILON);
97 SetIntFlag(FLT_RADIX);
98 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +000099#undef SetIntFlag
100#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101
102 if (PyErr_Occurred()) {
103 Py_CLEAR(floatinfo);
104 return NULL;
105 }
106 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000107}
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200112 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000113 if (op != NULL) {
114 free_list = (PyFloatObject *) Py_TYPE(op);
115 numfree--;
116 } else {
117 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
118 if (!op)
119 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
121 /* Inline PyObject_New */
Christian Heimesd3afe782013-12-04 09:27:47 +0100122 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 op->ob_fval = fval;
124 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125}
126
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000127PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000128PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 const char *s, *last, *end;
131 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000132 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200134 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200138 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000140 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200141 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000142 if (s == NULL) {
143 Py_DECREF(s_buffer);
144 return NULL;
145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000147 else if (PyBytes_Check(v)) {
148 s = PyBytes_AS_STRING(v);
149 len = PyBytes_GET_SIZE(v);
150 }
151 else if (PyByteArray_Check(v)) {
152 s = PyByteArray_AS_STRING(v);
153 len = PyByteArray_GET_SIZE(v);
154 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200155 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
156 s = (const char *)view.buf;
157 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000158 /* Copy to NUL-terminated buffer. */
159 s_buffer = PyBytes_FromStringAndSize(s, len);
160 if (s_buffer == NULL) {
161 PyBuffer_Release(&view);
162 return NULL;
163 }
164 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200165 }
166 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200167 PyErr_Format(PyExc_TypeError,
168 "float() argument must be a string or a number, not '%.200s'",
169 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return NULL;
171 }
172 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000173 /* strip space */
174 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000176 while (s < last - 1 && Py_ISSPACE(last[-1]))
177 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* We don't care about overflow or underflow. If the platform
179 * supports them, infinities and signed zeroes (on underflow) are
180 * fine. */
181 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 if (end != last) {
183 PyErr_Format(PyExc_ValueError,
184 "could not convert string to float: "
185 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 result = NULL;
187 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000188 else if (x == -1.0 && PyErr_Occurred())
189 result = NULL;
190 else
191 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000192
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200193 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000194 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196}
197
Guido van Rossum234f9421993-06-17 12:35:49 +0000198static void
Fred Drakefd99de62000-07-09 05:02:18 +0000199float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000202 if (numfree >= PyFloat_MAXFREELIST) {
203 PyObject_FREE(op);
204 return;
205 }
206 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_TYPE(op) = (struct _typeobject *)free_list;
208 free_list = op;
209 }
210 else
211 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000212}
213
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214double
Fred Drakefd99de62000-07-09 05:02:18 +0000215PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyNumberMethods *nb;
218 PyFloatObject *fo;
219 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (op && PyFloat_Check(op))
222 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (op == NULL) {
225 PyErr_BadArgument();
226 return -1;
227 }
Tim Petersd2364e82001-11-01 20:09:42 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
230 PyErr_SetString(PyExc_TypeError, "a float is required");
231 return -1;
232 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 fo = (PyFloatObject*) (*nb->nb_float) (op);
235 if (fo == NULL)
236 return -1;
237 if (!PyFloat_Check(fo)) {
Benjamin Petersona9157232015-03-06 09:08:44 -0500238 Py_DECREF(fo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyErr_SetString(PyExc_TypeError,
240 "nb_float should return float object");
241 return -1;
242 }
Tim Petersd2364e82001-11-01 20:09:42 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 val = PyFloat_AS_DOUBLE(fo);
245 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248}
249
Neil Schemenauer32117e52001-01-04 01:44:34 +0000250/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000251 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000252 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300253 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000254 stored in obj, and returned from the function invoking this macro.
255*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256#define CONVERT_TO_DOUBLE(obj, dbl) \
257 if (PyFloat_Check(obj)) \
258 dbl = PyFloat_AS_DOUBLE(obj); \
259 else if (convert_to_double(&(obj), &(dbl)) < 0) \
260 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000261
Eric Smith0923d1d2009-04-16 20:16:10 +0000262/* Methods */
263
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000265convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000266{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200267 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (PyLong_Check(obj)) {
270 *dbl = PyLong_AsDouble(obj);
271 if (*dbl == -1.0 && PyErr_Occurred()) {
272 *v = NULL;
273 return -1;
274 }
275 }
276 else {
277 Py_INCREF(Py_NotImplemented);
278 *v = Py_NotImplemented;
279 return -1;
280 }
281 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000282}
283
Eric Smith0923d1d2009-04-16 20:16:10 +0000284static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000285float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000286{
287 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200288 char *buf;
289
290 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
291 'r', 0,
292 Py_DTSF_ADD_DOT_0,
293 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000294 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000295 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200296 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000297 PyMem_Free(buf);
298 return result;
299}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000300
Tim Peters307fa782004-09-23 08:06:40 +0000301/* Comparison is pretty much a nightmare. When comparing float to float,
302 * we do it as straightforwardly (and long-windedly) as conceivable, so
303 * that, e.g., Python x == y delivers the same result as the platform
304 * C x == y when x and/or y is a NaN.
305 * When mixing float with an integer type, there's no good *uniform* approach.
306 * Converting the double to an integer obviously doesn't work, since we
307 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300308 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000309 * large to fit in the dynamic range of a C double); (2) even a C long may have
Ezio Melotti3f5db392013-01-27 06:20:14 +0200310 * more bits than fit in a C double (e.g., on a 64-bit box long may have
Tim Peters307fa782004-09-23 08:06:40 +0000311 * 63 bits of precision, but a C double probably has only 53), and then
312 * we can falsely claim equality when low-order integer bits are lost by
313 * coercion to double. So this part is painful too.
314 */
315
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000316static PyObject*
317float_richcompare(PyObject *v, PyObject *w, int op)
318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 double i, j;
320 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 assert(PyFloat_Check(v));
323 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 /* Switch on the type of w. Set i and j to doubles to be compared,
326 * and op to the richcomp to use.
327 */
328 if (PyFloat_Check(w))
329 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 else if (!Py_IS_FINITE(i)) {
332 if (PyLong_Check(w))
333 /* If i is an infinity, its magnitude exceeds any
334 * finite integer, so it doesn't matter which int we
335 * compare i with. If i is a NaN, similarly.
336 */
337 j = 0.0;
338 else
339 goto Unimplemented;
340 }
Tim Peters307fa782004-09-23 08:06:40 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 else if (PyLong_Check(w)) {
343 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
344 int wsign = _PyLong_Sign(w);
345 size_t nbits;
346 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (vsign != wsign) {
349 /* Magnitudes are irrelevant -- the signs alone
350 * determine the outcome.
351 */
352 i = (double)vsign;
353 j = (double)wsign;
354 goto Compare;
355 }
356 /* The signs are the same. */
357 /* Convert w to a double if it fits. In particular, 0 fits. */
358 nbits = _PyLong_NumBits(w);
359 if (nbits == (size_t)-1 && PyErr_Occurred()) {
360 /* This long is so large that size_t isn't big enough
361 * to hold the # of bits. Replace with little doubles
362 * that give the same outcome -- w is so large that
363 * its magnitude must exceed the magnitude of any
364 * finite float.
365 */
366 PyErr_Clear();
367 i = (double)vsign;
368 assert(wsign != 0);
369 j = wsign * 2.0;
370 goto Compare;
371 }
372 if (nbits <= 48) {
373 j = PyLong_AsDouble(w);
374 /* It's impossible that <= 48 bits overflowed. */
375 assert(j != -1.0 || ! PyErr_Occurred());
376 goto Compare;
377 }
378 assert(wsign != 0); /* else nbits was 0 */
379 assert(vsign != 0); /* if vsign were 0, then since wsign is
380 * not 0, we would have taken the
381 * vsign != wsign branch at the start */
382 /* We want to work with non-negative numbers. */
383 if (vsign < 0) {
384 /* "Multiply both sides" by -1; this also swaps the
385 * comparator.
386 */
387 i = -i;
388 op = _Py_SwappedOp[op];
389 }
390 assert(i > 0.0);
391 (void) frexp(i, &exponent);
392 /* exponent is the # of bits in v before the radix point;
393 * we know that nbits (the # of bits in w) > 48 at this point
394 */
395 if (exponent < 0 || (size_t)exponent < nbits) {
396 i = 1.0;
397 j = 2.0;
398 goto Compare;
399 }
400 if ((size_t)exponent > nbits) {
401 i = 2.0;
402 j = 1.0;
403 goto Compare;
404 }
405 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300406 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 * outcome.
408 */
409 {
410 double fracpart;
411 double intpart;
412 PyObject *result = NULL;
413 PyObject *one = NULL;
414 PyObject *vv = NULL;
415 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (wsign < 0) {
418 ww = PyNumber_Negative(w);
419 if (ww == NULL)
420 goto Error;
421 }
422 else
423 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 fracpart = modf(i, &intpart);
426 vv = PyLong_FromDouble(intpart);
427 if (vv == NULL)
428 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (fracpart != 0.0) {
431 /* Shift left, and or a 1 bit into vv
432 * to represent the lost fraction.
433 */
434 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 one = PyLong_FromLong(1);
437 if (one == NULL)
438 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 temp = PyNumber_Lshift(ww, one);
441 if (temp == NULL)
442 goto Error;
443 Py_DECREF(ww);
444 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 temp = PyNumber_Lshift(vv, one);
447 if (temp == NULL)
448 goto Error;
449 Py_DECREF(vv);
450 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 temp = PyNumber_Or(vv, one);
453 if (temp == NULL)
454 goto Error;
455 Py_DECREF(vv);
456 vv = temp;
457 }
Tim Peters307fa782004-09-23 08:06:40 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 r = PyObject_RichCompareBool(vv, ww, op);
460 if (r < 0)
461 goto Error;
462 result = PyBool_FromLong(r);
463 Error:
464 Py_XDECREF(vv);
465 Py_XDECREF(ww);
466 Py_XDECREF(one);
467 return result;
468 }
469 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000470
Serhiy Storchaka95949422013-08-27 19:40:23 +0300471 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000473
474 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyFPE_START_PROTECT("richcompare", return NULL)
476 switch (op) {
477 case Py_EQ:
478 r = i == j;
479 break;
480 case Py_NE:
481 r = i != j;
482 break;
483 case Py_LE:
484 r = i <= j;
485 break;
486 case Py_GE:
487 r = i >= j;
488 break;
489 case Py_LT:
490 r = i < j;
491 break;
492 case Py_GT:
493 r = i > j;
494 break;
495 }
496 PyFPE_END_PROTECT(r)
497 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000498
499 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500500 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000501}
502
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000503static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000504float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000507}
508
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000510float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 double a,b;
513 CONVERT_TO_DOUBLE(v, a);
514 CONVERT_TO_DOUBLE(w, b);
515 PyFPE_START_PROTECT("add", return 0)
516 a = a + b;
517 PyFPE_END_PROTECT(a)
518 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519}
520
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000522float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 double a,b;
525 CONVERT_TO_DOUBLE(v, a);
526 CONVERT_TO_DOUBLE(w, b);
527 PyFPE_START_PROTECT("subtract", return 0)
528 a = a - b;
529 PyFPE_END_PROTECT(a)
530 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000531}
532
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000534float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 double a,b;
537 CONVERT_TO_DOUBLE(v, a);
538 CONVERT_TO_DOUBLE(w, b);
539 PyFPE_START_PROTECT("multiply", return 0)
540 a = a * b;
541 PyFPE_END_PROTECT(a)
542 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543}
544
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000546float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 double a,b;
549 CONVERT_TO_DOUBLE(v, a);
550 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (b == 0.0) {
552 PyErr_SetString(PyExc_ZeroDivisionError,
553 "float division by zero");
554 return NULL;
555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyFPE_START_PROTECT("divide", return 0)
557 a = a / b;
558 PyFPE_END_PROTECT(a)
559 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 double vx, wx;
566 double mod;
567 CONVERT_TO_DOUBLE(v, vx);
568 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (wx == 0.0) {
570 PyErr_SetString(PyExc_ZeroDivisionError,
571 "float modulo");
572 return NULL;
573 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyFPE_START_PROTECT("modulo", return 0)
575 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000576 if (mod) {
577 /* ensure the remainder has the same sign as the denominator */
578 if ((wx < 0) != (mod < 0)) {
579 mod += wx;
580 }
581 }
582 else {
583 /* the remainder is zero, and in the presence of signed zeroes
584 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000585 it has the same sign as the denominator. */
586 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
588 PyFPE_END_PROTECT(mod)
589 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590}
591
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000593float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 double vx, wx;
596 double div, mod, floordiv;
597 CONVERT_TO_DOUBLE(v, vx);
598 CONVERT_TO_DOUBLE(w, wx);
599 if (wx == 0.0) {
600 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
601 return NULL;
602 }
603 PyFPE_START_PROTECT("divmod", return 0)
604 mod = fmod(vx, wx);
605 /* fmod is typically exact, so vx-mod is *mathematically* an
606 exact multiple of wx. But this is fp arithmetic, and fp
607 vx - mod is an approximation; the result is that div may
608 not be an exact integral value after the division, although
609 it will always be very close to one.
610 */
611 div = (vx - mod) / wx;
612 if (mod) {
613 /* ensure the remainder has the same sign as the denominator */
614 if ((wx < 0) != (mod < 0)) {
615 mod += wx;
616 div -= 1.0;
617 }
618 }
619 else {
620 /* the remainder is zero, and in the presence of signed zeroes
621 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000622 it has the same sign as the denominator. */
623 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 }
625 /* snap quotient to nearest integral value */
626 if (div) {
627 floordiv = floor(div);
628 if (div - floordiv > 0.5)
629 floordiv += 1.0;
630 }
631 else {
632 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000633 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
635 PyFPE_END_PROTECT(floordiv)
636 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000640float_floor_div(PyObject *v, PyObject *w)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 t = float_divmod(v, w);
645 if (t == NULL || t == Py_NotImplemented)
646 return t;
647 assert(PyTuple_CheckExact(t));
648 r = PyTuple_GET_ITEM(t, 0);
649 Py_INCREF(r);
650 Py_DECREF(t);
651 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000652}
653
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000654/* determine whether x is an odd integer or not; assumes that
655 x is not an infinity or nan. */
656#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
657
Tim Peters63a35712001-12-11 19:57:24 +0000658static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000659float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 double iv, iw, ix;
662 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if ((PyObject *)z != Py_None) {
665 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
666 "allowed unless all arguments are integers");
667 return NULL;
668 }
Tim Peters32f453e2001-09-03 08:35:41 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 CONVERT_TO_DOUBLE(v, iv);
671 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 /* Sort out special cases here instead of relying on pow() */
674 if (iw == 0) { /* v**0 is 1, even 0**0 */
675 return PyFloat_FromDouble(1.0);
676 }
677 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
678 return PyFloat_FromDouble(iv);
679 }
680 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
681 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
682 }
683 if (Py_IS_INFINITY(iw)) {
684 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
685 * abs(v) > 1 (including case where v infinite)
686 *
687 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
688 * abs(v) > 1 (including case where v infinite)
689 */
690 iv = fabs(iv);
691 if (iv == 1.0)
692 return PyFloat_FromDouble(1.0);
693 else if ((iw > 0.0) == (iv > 1.0))
694 return PyFloat_FromDouble(fabs(iw)); /* return inf */
695 else
696 return PyFloat_FromDouble(0.0);
697 }
698 if (Py_IS_INFINITY(iv)) {
699 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
700 * both cases, we need to add the appropriate sign if w is
701 * an odd integer.
702 */
703 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
704 if (iw > 0.0)
705 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
706 else
707 return PyFloat_FromDouble(iw_is_odd ?
708 copysign(0.0, iv) : 0.0);
709 }
710 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
711 (already dealt with above), and an error
712 if w is negative. */
713 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
714 if (iw < 0.0) {
715 PyErr_SetString(PyExc_ZeroDivisionError,
716 "0.0 cannot be raised to a "
717 "negative power");
718 return NULL;
719 }
720 /* use correct sign if iw is odd */
721 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
722 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (iv < 0.0) {
725 /* Whether this is an error is a mess, and bumps into libm
726 * bugs so we have to figure it out ourselves.
727 */
728 if (iw != floor(iw)) {
729 /* Negative numbers raised to fractional powers
730 * become complex.
731 */
732 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
733 }
734 /* iw is an exact integer, albeit perhaps a very large
735 * one. Replace iv by its absolute value and remember
736 * to negate the pow result if iw is odd.
737 */
738 iv = -iv;
739 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
740 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
743 /* (-1) ** large_integer also ends up here. Here's an
744 * extract from the comments for the previous
745 * implementation explaining why this special case is
746 * necessary:
747 *
748 * -1 raised to an exact integer should never be exceptional.
749 * Alas, some libms (chiefly glibc as of early 2003) return
750 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
751 * happen to be representable in a *C* integer. That's a
752 * bug.
753 */
754 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
755 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Now iv and iw are finite, iw is nonzero, and iv is
758 * positive and not equal to 1.0. We finally allow
759 * the platform pow to step in and do the rest.
760 */
761 errno = 0;
762 PyFPE_START_PROTECT("pow", return NULL)
763 ix = pow(iv, iw);
764 PyFPE_END_PROTECT(ix)
765 Py_ADJUST_ERANGE1(ix);
766 if (negate_result)
767 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (errno != 0) {
770 /* We don't expect any errno value other than ERANGE, but
771 * the range of libm bugs appears unbounded.
772 */
773 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
774 PyExc_ValueError);
775 return NULL;
776 }
777 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778}
779
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000780#undef DOUBLE_IS_ODD_INTEGER
781
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000782static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000783float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786}
787
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000789float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792}
793
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000794static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000795float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000798}
799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000801float_is_integer(PyObject *v)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 double x = PyFloat_AsDouble(v);
804 PyObject *o;
805
806 if (x == -1.0 && PyErr_Occurred())
807 return NULL;
808 if (!Py_IS_FINITE(x))
809 Py_RETURN_FALSE;
810 errno = 0;
811 PyFPE_START_PROTECT("is_integer", return NULL)
812 o = (floor(x) == x) ? Py_True : Py_False;
813 PyFPE_END_PROTECT(x)
814 if (errno != 0) {
815 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
816 PyExc_ValueError);
817 return NULL;
818 }
819 Py_INCREF(o);
820 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000821}
822
823#if 0
824static PyObject *
825float_is_inf(PyObject *v)
826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 double x = PyFloat_AsDouble(v);
828 if (x == -1.0 && PyErr_Occurred())
829 return NULL;
830 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000831}
832
833static PyObject *
834float_is_nan(PyObject *v)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 double x = PyFloat_AsDouble(v);
837 if (x == -1.0 && PyErr_Occurred())
838 return NULL;
839 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000840}
841
842static PyObject *
843float_is_finite(PyObject *v)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 double x = PyFloat_AsDouble(v);
846 if (x == -1.0 && PyErr_Occurred())
847 return NULL;
848 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000849}
850#endif
851
852static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000853float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 double x = PyFloat_AsDouble(v);
856 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 (void)modf(x, &wholepart);
859 /* Try to get out cheap if this fits in a Python int. The attempt
860 * to cast to long must be protected, as C doesn't define what
861 * happens if the double is too big to fit in a long. Some rare
862 * systems raise an exception then (RISCOS was mentioned as one,
863 * and someone using a non-default option on Sun also bumped into
864 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
865 * still be vulnerable: if a long has more bits of precision than
866 * a double, casting MIN/MAX to double may yield an approximation,
867 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
868 * yield true from the C expression wholepart<=LONG_MAX, despite
869 * that wholepart is actually greater than LONG_MAX.
870 */
871 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
872 const long aslong = (long)wholepart;
873 return PyLong_FromLong(aslong);
874 }
875 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000876}
877
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000878/* double_round: rounds a finite double to the closest multiple of
879 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
880 ndigits <= 323). Returns a Python float, or sets a Python error and
881 returns NULL on failure (OverflowError and memory errors are possible). */
882
883#ifndef PY_NO_SHORT_FLOAT_REPR
884/* version of double_round that uses the correctly-rounded string<->double
885 conversions from Python/dtoa.c */
886
887static PyObject *
888double_round(double x, int ndigits) {
889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 double rounded;
891 Py_ssize_t buflen, mybuflen=100;
892 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
893 int decpt, sign;
894 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000895 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000898 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000900 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (buf == NULL) {
902 PyErr_NoMemory();
903 return NULL;
904 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
907 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
908 buflen = buf_end - buf;
909 if (buflen + 8 > mybuflen) {
910 mybuflen = buflen+8;
911 mybuf = (char *)PyMem_Malloc(mybuflen);
912 if (mybuf == NULL) {
913 PyErr_NoMemory();
914 goto exit;
915 }
916 }
917 /* copy buf to mybuf, adding exponent, sign and leading 0 */
918 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
919 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* and convert the resulting string back to a double */
922 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000923 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000925 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (errno == ERANGE && fabs(rounded) >= 1.)
927 PyErr_SetString(PyExc_OverflowError,
928 "rounded value too large to represent");
929 else
930 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* done computing value; now clean up */
933 if (mybuf != shortbuf)
934 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000935 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 _Py_dg_freedtoa(buf);
937 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000938}
939
940#else /* PY_NO_SHORT_FLOAT_REPR */
941
942/* fallback version, to be used when correctly rounded binary<->decimal
943 conversions aren't available */
944
945static PyObject *
946double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 double pow1, pow2, y, z;
948 if (ndigits >= 0) {
949 if (ndigits > 22) {
950 /* pow1 and pow2 are each safe from overflow, but
951 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
952 pow1 = pow(10.0, (double)(ndigits-22));
953 pow2 = 1e22;
954 }
955 else {
956 pow1 = pow(10.0, (double)ndigits);
957 pow2 = 1.0;
958 }
959 y = (x*pow1)*pow2;
960 /* if y overflows, then rounded value is exactly x */
961 if (!Py_IS_FINITE(y))
962 return PyFloat_FromDouble(x);
963 }
964 else {
965 pow1 = pow(10.0, (double)-ndigits);
966 pow2 = 1.0; /* unused; silences a gcc compiler warning */
967 y = x / pow1;
968 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 z = round(y);
971 if (fabs(y-z) == 0.5)
972 /* halfway between two integers; use round-half-even */
973 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (ndigits >= 0)
976 z = (z / pow2) / pow1;
977 else
978 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 /* if computation resulted in overflow, raise OverflowError */
981 if (!Py_IS_FINITE(z)) {
982 PyErr_SetString(PyExc_OverflowError,
983 "overflow occurred during round");
984 return NULL;
985 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000988}
989
990#endif /* PY_NO_SHORT_FLOAT_REPR */
991
992/* round a Python float v to the closest multiple of 10**-ndigits */
993
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000994static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000995float_round(PyObject *v, PyObject *args)
996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 double x, rounded;
998 PyObject *o_ndigits = NULL;
999 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 x = PyFloat_AsDouble(v);
1002 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1003 return NULL;
Steve Dowercb39d1f2015-04-15 16:10:59 -04001004 if (o_ndigits == NULL || o_ndigits == Py_None) {
1005 /* single-argument round or with None ndigits:
1006 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 rounded = round(x);
1008 if (fabs(x-rounded) == 0.5)
1009 /* halfway case: round to even */
1010 rounded = 2.0*round(x/2.0);
1011 return PyLong_FromDouble(rounded);
1012 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* interpret second argument as a Py_ssize_t; clips on overflow */
1015 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1016 if (ndigits == -1 && PyErr_Occurred())
1017 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* nans and infinities round to themselves */
1020 if (!Py_IS_FINITE(x))
1021 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1024 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1025 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001026#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1027#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (ndigits > NDIGITS_MAX)
1029 /* return x */
1030 return PyFloat_FromDouble(x);
1031 else if (ndigits < NDIGITS_MIN)
1032 /* return 0.0, but with sign of x */
1033 return PyFloat_FromDouble(0.0*x);
1034 else
1035 /* finite x, and ndigits is not unreasonably large */
1036 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001037#undef NDIGITS_MAX
1038#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001039}
1040
1041static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001042float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (PyFloat_CheckExact(v))
1045 Py_INCREF(v);
1046 else
1047 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1048 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001049}
1050
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001051/* turn ASCII hex characters into integer values and vice versa */
1052
1053static char
1054char_from_hex(int x)
1055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001057 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001058}
1059
1060static int
1061hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 int x;
1063 switch(c) {
1064 case '0':
1065 x = 0;
1066 break;
1067 case '1':
1068 x = 1;
1069 break;
1070 case '2':
1071 x = 2;
1072 break;
1073 case '3':
1074 x = 3;
1075 break;
1076 case '4':
1077 x = 4;
1078 break;
1079 case '5':
1080 x = 5;
1081 break;
1082 case '6':
1083 x = 6;
1084 break;
1085 case '7':
1086 x = 7;
1087 break;
1088 case '8':
1089 x = 8;
1090 break;
1091 case '9':
1092 x = 9;
1093 break;
1094 case 'a':
1095 case 'A':
1096 x = 10;
1097 break;
1098 case 'b':
1099 case 'B':
1100 x = 11;
1101 break;
1102 case 'c':
1103 case 'C':
1104 x = 12;
1105 break;
1106 case 'd':
1107 case 'D':
1108 x = 13;
1109 break;
1110 case 'e':
1111 case 'E':
1112 x = 14;
1113 break;
1114 case 'f':
1115 case 'F':
1116 x = 15;
1117 break;
1118 default:
1119 x = -1;
1120 break;
1121 }
1122 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001123}
1124
1125/* convert a float to a hexadecimal string */
1126
1127/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1128 of the form 4k+1. */
1129#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1130
1131static PyObject *
1132float_hex(PyObject *v)
1133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 double x, m;
1135 int e, shift, i, si, esign;
1136 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1137 trailing NUL byte. */
1138 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001143 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001146 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return PyUnicode_FromString("-0x0.0p+0");
1148 else
1149 return PyUnicode_FromString("0x0.0p+0");
1150 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001153 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 m = ldexp(m, shift);
1155 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 si = 0;
1158 s[si] = char_from_hex((int)m);
1159 si++;
1160 m -= (int)m;
1161 s[si] = '.';
1162 si++;
1163 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1164 m *= 16.0;
1165 s[si] = char_from_hex((int)m);
1166 si++;
1167 m -= (int)m;
1168 }
1169 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (e < 0) {
1172 esign = (int)'-';
1173 e = -e;
1174 }
1175 else
1176 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (x < 0.0)
1179 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1180 else
1181 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001182}
1183
1184PyDoc_STRVAR(float_hex_doc,
1185"float.hex() -> string\n\
1186\n\
1187Return a hexadecimal representation of a floating-point number.\n\
1188>>> (-0.1).hex()\n\
1189'-0x1.999999999999ap-4'\n\
1190>>> 3.14159.hex()\n\
1191'0x1.921f9f01b866ep+1'");
1192
1193/* Convert a hexadecimal string to a float. */
1194
1195static PyObject *
1196float_fromhex(PyObject *cls, PyObject *arg)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *result_as_float, *result;
1199 double x;
1200 long exp, top_exp, lsb, key_digit;
1201 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1202 int half_eps, digit, round_up, negate=0;
1203 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /*
1206 * For the sake of simplicity and correctness, we impose an artificial
1207 * limit on ndigits, the total number of hex digits in the coefficient
1208 * The limit is chosen to ensure that, writing exp for the exponent,
1209 *
1210 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1211 * guaranteed to overflow (provided it's nonzero)
1212 *
1213 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1214 * guaranteed to underflow to 0.
1215 *
1216 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1217 * overflow in the calculation of exp and top_exp below.
1218 *
1219 * More specifically, ndigits is assumed to satisfy the following
1220 * inequalities:
1221 *
1222 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1223 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1224 *
1225 * If either of these inequalities is not satisfied, a ValueError is
1226 * raised. Otherwise, write x for the value of the hex string, and
1227 * assume x is nonzero. Then
1228 *
1229 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1230 *
1231 * Now if exp > LONG_MAX/2 then:
1232 *
1233 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1234 * = DBL_MAX_EXP
1235 *
1236 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1237 * double, so overflows. If exp < LONG_MIN/2, then
1238 *
1239 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1240 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1241 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1242 *
1243 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1244 * when converted to a C double.
1245 *
1246 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1247 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1248 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 s = _PyUnicode_AsStringAndSize(arg, &length);
1251 if (s == NULL)
1252 return NULL;
1253 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /********************
1256 * Parse the string *
1257 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* leading whitespace */
1260 while (Py_ISSPACE(*s))
1261 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* infinities and nans */
1264 x = _Py_parse_inf_or_nan(s, &coeff_end);
1265 if (coeff_end != s) {
1266 s = coeff_end;
1267 goto finished;
1268 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* optional sign */
1271 if (*s == '-') {
1272 s++;
1273 negate = 1;
1274 }
1275 else if (*s == '+')
1276 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* [0x] */
1279 s_store = s;
1280 if (*s == '0') {
1281 s++;
1282 if (*s == 'x' || *s == 'X')
1283 s++;
1284 else
1285 s = s_store;
1286 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* coefficient: <integer> [. <fraction>] */
1289 coeff_start = s;
1290 while (hex_from_char(*s) >= 0)
1291 s++;
1292 s_store = s;
1293 if (*s == '.') {
1294 s++;
1295 while (hex_from_char(*s) >= 0)
1296 s++;
1297 coeff_end = s-1;
1298 }
1299 else
1300 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* ndigits = total # of hex digits; fdigits = # after point */
1303 ndigits = coeff_end - coeff_start;
1304 fdigits = coeff_end - s_store;
1305 if (ndigits == 0)
1306 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001307 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1308 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 /* [p <exponent>] */
1312 if (*s == 'p' || *s == 'P') {
1313 s++;
1314 exp_start = s;
1315 if (*s == '-' || *s == '+')
1316 s++;
1317 if (!('0' <= *s && *s <= '9'))
1318 goto parse_error;
1319 s++;
1320 while ('0' <= *s && *s <= '9')
1321 s++;
1322 exp = strtol(exp_start, NULL, 10);
1323 }
1324 else
1325 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001326
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1329 coeff_end-(j) : \
1330 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /*******************************************
1333 * Compute rounded value of the hex string *
1334 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* Discard leading zeros, and catch extreme overflow and underflow */
1337 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1338 ndigits--;
1339 if (ndigits == 0 || exp < LONG_MIN/2) {
1340 x = 0.0;
1341 goto finished;
1342 }
1343 if (exp > LONG_MAX/2)
1344 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* Adjust exponent for fractional part. */
1347 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1350 top_exp = exp + 4*((long)ndigits - 1);
1351 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1352 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 /* catch almost all nonextreme cases of overflow and underflow here */
1355 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1356 x = 0.0;
1357 goto finished;
1358 }
1359 if (top_exp > DBL_MAX_EXP)
1360 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* lsb = exponent of least significant bit of the *rounded* value.
1363 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001364 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 x = 0.0;
1367 if (exp >= lsb) {
1368 /* no rounding required */
1369 for (i = ndigits-1; i >= 0; i--)
1370 x = 16.0*x + HEX_DIGIT(i);
1371 x = ldexp(x, (int)(exp));
1372 goto finished;
1373 }
1374 /* rounding required. key_digit is the index of the hex digit
1375 containing the first bit to be rounded away. */
1376 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1377 key_digit = (lsb - exp - 1) / 4;
1378 for (i = ndigits-1; i > key_digit; i--)
1379 x = 16.0*x + HEX_DIGIT(i);
1380 digit = HEX_DIGIT(key_digit);
1381 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1384 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1385 if ((digit & half_eps) != 0) {
1386 round_up = 0;
1387 if ((digit & (3*half_eps-1)) != 0 ||
1388 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1389 round_up = 1;
1390 else
1391 for (i = key_digit-1; i >= 0; i--)
1392 if (HEX_DIGIT(i) != 0) {
1393 round_up = 1;
1394 break;
1395 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001396 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 x += 2*half_eps;
1398 if (top_exp == DBL_MAX_EXP &&
1399 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1400 /* overflow corner case: pre-rounded value <
1401 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1402 goto overflow_error;
1403 }
1404 }
1405 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406
1407 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* optional trailing whitespace leading to the end of the string */
1409 while (Py_ISSPACE(*s))
1410 s++;
1411 if (s != s_end)
1412 goto parse_error;
1413 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1414 if (result_as_float == NULL)
1415 return NULL;
1416 result = PyObject_CallObject(cls, result_as_float);
1417 Py_DECREF(result_as_float);
1418 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001419
1420 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 PyErr_SetString(PyExc_OverflowError,
1422 "hexadecimal value too large to represent as a float");
1423 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001424
1425 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyErr_SetString(PyExc_ValueError,
1427 "invalid hexadecimal floating-point string");
1428 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001429
1430 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyErr_SetString(PyExc_ValueError,
1432 "hexadecimal string too long to convert");
1433 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001434}
1435
1436PyDoc_STRVAR(float_fromhex_doc,
1437"float.fromhex(string) -> float\n\
1438\n\
1439Create a floating-point number from a hexadecimal string.\n\
1440>>> float.fromhex('0x1.ffffp10')\n\
14412047.984375\n\
1442>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001443-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001444
1445
Christian Heimes26855632008-01-27 23:50:43 +00001446static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001447float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 double self;
1450 double float_part;
1451 int exponent;
1452 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (Py_IS_INFINITY(self)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001463 PyErr_SetString(PyExc_OverflowError,
1464 "cannot convert Infinity to integer ratio");
1465 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (Py_IS_NAN(self)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001468 PyErr_SetString(PyExc_ValueError,
1469 "cannot convert NaN to integer ratio");
1470 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 }
Christian Heimes26855632008-01-27 23:50:43 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1474 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1475 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1478 float_part *= 2.0;
1479 exponent--;
1480 }
1481 /* self == float_part * 2**exponent exactly and float_part is integral.
1482 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1483 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001486 if (numerator == NULL)
1487 goto error;
1488 denominator = PyLong_FromLong(1);
1489 if (denominator == NULL)
1490 goto error;
1491 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1492 if (py_exponent == NULL)
1493 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001497 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001498 long_methods->nb_lshift(numerator, py_exponent));
1499 if (numerator == NULL)
1500 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 }
1502 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001503 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001504 long_methods->nb_lshift(denominator, py_exponent));
1505 if (denominator == NULL)
1506 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 }
1508
1509 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001510
Christian Heimes26855632008-01-27 23:50:43 +00001511error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 Py_XDECREF(py_exponent);
1513 Py_XDECREF(denominator);
1514 Py_XDECREF(numerator);
1515 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001516}
1517
1518PyDoc_STRVAR(float_as_integer_ratio_doc,
1519"float.as_integer_ratio() -> (int, int)\n"
1520"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001521"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001522"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001523"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001524"\n"
1525">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001526"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001527">>> (0.0).as_integer_ratio()\n"
1528"(0, 1)\n"
1529">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001530"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001531
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001532
Jeremy Hylton938ace62002-07-17 16:30:39 +00001533static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001534float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1535
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536static PyObject *
1537float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 PyObject *x = Py_False; /* Integer zero */
1540 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (type != &PyFloat_Type)
1543 return float_subtype_new(type, args, kwds); /* Wimp out */
1544 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1545 return NULL;
1546 /* If it's a string, but not a string subclass, use
1547 PyFloat_FromString. */
1548 if (PyUnicode_CheckExact(x))
1549 return PyFloat_FromString(x);
1550 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551}
1552
Guido van Rossumbef14172001-08-29 15:47:46 +00001553/* Wimpy, slow approach to tp_new calls for subtypes of float:
1554 first create a regular float from whatever arguments we got,
1555 then allocate a subtype instance and initialize its ob_fval
1556 from the regular float. The regular float is then thrown away.
1557*/
1558static PyObject *
1559float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 assert(PyType_IsSubtype(type, &PyFloat_Type));
1564 tmp = float_new(&PyFloat_Type, args, kwds);
1565 if (tmp == NULL)
1566 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001567 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 newobj = type->tp_alloc(type, 0);
1569 if (newobj == NULL) {
1570 Py_DECREF(tmp);
1571 return NULL;
1572 }
1573 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1574 Py_DECREF(tmp);
1575 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001576}
1577
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001578static PyObject *
1579float_getnewargs(PyFloatObject *v)
1580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001582}
1583
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001584/* this is for the benefit of the pack/unpack routines below */
1585
1586typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001588} float_format_type;
1589
1590static float_format_type double_format, float_format;
1591static float_format_type detected_double_format, detected_float_format;
1592
1593static PyObject *
1594float_getformat(PyTypeObject *v, PyObject* arg)
1595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 char* s;
1597 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 if (!PyUnicode_Check(arg)) {
1600 PyErr_Format(PyExc_TypeError,
1601 "__getformat__() argument must be string, not %.500s",
1602 Py_TYPE(arg)->tp_name);
1603 return NULL;
1604 }
1605 s = _PyUnicode_AsString(arg);
1606 if (s == NULL)
1607 return NULL;
1608 if (strcmp(s, "double") == 0) {
1609 r = double_format;
1610 }
1611 else if (strcmp(s, "float") == 0) {
1612 r = float_format;
1613 }
1614 else {
1615 PyErr_SetString(PyExc_ValueError,
1616 "__getformat__() argument 1 must be "
1617 "'double' or 'float'");
1618 return NULL;
1619 }
1620
1621 switch (r) {
1622 case unknown_format:
1623 return PyUnicode_FromString("unknown");
1624 case ieee_little_endian_format:
1625 return PyUnicode_FromString("IEEE, little-endian");
1626 case ieee_big_endian_format:
1627 return PyUnicode_FromString("IEEE, big-endian");
1628 default:
1629 Py_FatalError("insane float_format or double_format");
1630 return NULL;
1631 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001632}
1633
1634PyDoc_STRVAR(float_getformat_doc,
1635"float.__getformat__(typestr) -> string\n"
1636"\n"
1637"You probably don't want to use this function. It exists mainly to be\n"
1638"used in Python's test suite.\n"
1639"\n"
1640"typestr must be 'double' or 'float'. This function returns whichever of\n"
1641"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1642"format of floating point numbers used by the C type named by typestr.");
1643
1644static PyObject *
1645float_setformat(PyTypeObject *v, PyObject* args)
1646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 char* typestr;
1648 char* format;
1649 float_format_type f;
1650 float_format_type detected;
1651 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1654 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (strcmp(typestr, "double") == 0) {
1657 p = &double_format;
1658 detected = detected_double_format;
1659 }
1660 else if (strcmp(typestr, "float") == 0) {
1661 p = &float_format;
1662 detected = detected_float_format;
1663 }
1664 else {
1665 PyErr_SetString(PyExc_ValueError,
1666 "__setformat__() argument 1 must "
1667 "be 'double' or 'float'");
1668 return NULL;
1669 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (strcmp(format, "unknown") == 0) {
1672 f = unknown_format;
1673 }
1674 else if (strcmp(format, "IEEE, little-endian") == 0) {
1675 f = ieee_little_endian_format;
1676 }
1677 else if (strcmp(format, "IEEE, big-endian") == 0) {
1678 f = ieee_big_endian_format;
1679 }
1680 else {
1681 PyErr_SetString(PyExc_ValueError,
1682 "__setformat__() argument 2 must be "
1683 "'unknown', 'IEEE, little-endian' or "
1684 "'IEEE, big-endian'");
1685 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (f != unknown_format && f != detected) {
1690 PyErr_Format(PyExc_ValueError,
1691 "can only set %s format to 'unknown' or the "
1692 "detected platform value", typestr);
1693 return NULL;
1694 }
1695
1696 *p = f;
1697 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001698}
1699
1700PyDoc_STRVAR(float_setformat_doc,
1701"float.__setformat__(typestr, fmt) -> None\n"
1702"\n"
1703"You probably don't want to use this function. It exists mainly to be\n"
1704"used in Python's test suite.\n"
1705"\n"
1706"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1707"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1708"one of the latter two if it appears to match the underlying C reality.\n"
1709"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001710"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711"This affects how floats are converted to and from binary strings.");
1712
Guido van Rossumb43daf72007-08-01 18:08:08 +00001713static PyObject *
1714float_getzero(PyObject *v, void *closure)
1715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001717}
1718
Eric Smith8c663262007-08-25 02:26:07 +00001719static PyObject *
1720float__format__(PyObject *self, PyObject *args)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723 _PyUnicodeWriter writer;
1724 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1727 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001728
Victor Stinner8f674cc2013-04-17 23:02:17 +02001729 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001730 ret = _PyFloat_FormatAdvancedWriter(
1731 &writer,
1732 self,
1733 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1734 if (ret == -1) {
1735 _PyUnicodeWriter_Dealloc(&writer);
1736 return NULL;
1737 }
1738 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001739}
1740
1741PyDoc_STRVAR(float__format__doc,
1742"float.__format__(format_spec) -> string\n"
1743"\n"
1744"Formats the float according to format_spec.");
1745
1746
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001747static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001749 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001751 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001753 "Return the Integral closest to x, rounding half toward even.\n"
1754 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1756 float_as_integer_ratio_doc},
1757 {"fromhex", (PyCFunction)float_fromhex,
1758 METH_O|METH_CLASS, float_fromhex_doc},
1759 {"hex", (PyCFunction)float_hex,
1760 METH_NOARGS, float_hex_doc},
1761 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001762 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001763#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001765 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001767 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001769 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001770#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1772 {"__getformat__", (PyCFunction)float_getformat,
1773 METH_O|METH_CLASS, float_getformat_doc},
1774 {"__setformat__", (PyCFunction)float_setformat,
1775 METH_VARARGS|METH_CLASS, float_setformat_doc},
1776 {"__format__", (PyCFunction)float__format__,
1777 METH_VARARGS, float__format__doc},
1778 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001779};
1780
Guido van Rossumb43daf72007-08-01 18:08:08 +00001781static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001783 (getter)float_float, (setter)NULL,
1784 "the real part of a complex number",
1785 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001787 (getter)float_getzero, (setter)NULL,
1788 "the imaginary part of a complex number",
1789 NULL},
1790 {NULL} /* Sentinel */
1791};
1792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001793PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794"float(x) -> floating point number\n\
1795\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797
1798
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001799static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 float_add, /*nb_add*/
1801 float_sub, /*nb_subtract*/
1802 float_mul, /*nb_multiply*/
1803 float_rem, /*nb_remainder*/
1804 float_divmod, /*nb_divmod*/
1805 float_pow, /*nb_power*/
1806 (unaryfunc)float_neg, /*nb_negative*/
1807 (unaryfunc)float_float, /*nb_positive*/
1808 (unaryfunc)float_abs, /*nb_absolute*/
1809 (inquiry)float_bool, /*nb_bool*/
1810 0, /*nb_invert*/
1811 0, /*nb_lshift*/
1812 0, /*nb_rshift*/
1813 0, /*nb_and*/
1814 0, /*nb_xor*/
1815 0, /*nb_or*/
1816 float_trunc, /*nb_int*/
1817 0, /*nb_reserved*/
1818 float_float, /*nb_float*/
1819 0, /* nb_inplace_add */
1820 0, /* nb_inplace_subtract */
1821 0, /* nb_inplace_multiply */
1822 0, /* nb_inplace_remainder */
1823 0, /* nb_inplace_power */
1824 0, /* nb_inplace_lshift */
1825 0, /* nb_inplace_rshift */
1826 0, /* nb_inplace_and */
1827 0, /* nb_inplace_xor */
1828 0, /* nb_inplace_or */
1829 float_floor_div, /* nb_floor_divide */
1830 float_div, /* nb_true_divide */
1831 0, /* nb_inplace_floor_divide */
1832 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001833};
1834
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001835PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1837 "float",
1838 sizeof(PyFloatObject),
1839 0,
1840 (destructor)float_dealloc, /* tp_dealloc */
1841 0, /* tp_print */
1842 0, /* tp_getattr */
1843 0, /* tp_setattr */
1844 0, /* tp_reserved */
1845 (reprfunc)float_repr, /* tp_repr */
1846 &float_as_number, /* tp_as_number */
1847 0, /* tp_as_sequence */
1848 0, /* tp_as_mapping */
1849 (hashfunc)float_hash, /* tp_hash */
1850 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001851 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 PyObject_GenericGetAttr, /* tp_getattro */
1853 0, /* tp_setattro */
1854 0, /* tp_as_buffer */
1855 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1856 float_doc, /* tp_doc */
1857 0, /* tp_traverse */
1858 0, /* tp_clear */
1859 float_richcompare, /* tp_richcompare */
1860 0, /* tp_weaklistoffset */
1861 0, /* tp_iter */
1862 0, /* tp_iternext */
1863 float_methods, /* tp_methods */
1864 0, /* tp_members */
1865 float_getset, /* tp_getset */
1866 0, /* tp_base */
1867 0, /* tp_dict */
1868 0, /* tp_descr_get */
1869 0, /* tp_descr_set */
1870 0, /* tp_dictoffset */
1871 0, /* tp_init */
1872 0, /* tp_alloc */
1873 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001874};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001875
Victor Stinner1c8f0592013-07-22 22:24:54 +02001876int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001877_PyFloat_Init(void)
1878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 /* We attempt to determine if this machine is using IEEE
1880 floating point formats by peering at the bits of some
1881 carefully chosen values. If it looks like we are on an
1882 IEEE platform, the float packing/unpacking routines can
1883 just copy bits, if not they resort to arithmetic & shifts
1884 and masks. The shifts & masks approach works on all finite
1885 values, but what happens to infinities, NaNs and signed
1886 zeroes on packing is an accident, and attempting to unpack
1887 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 Note that if we're on some whacked-out platform which uses
1890 IEEE formats but isn't strictly little-endian or big-
1891 endian, we will fall back to the portable shifts & masks
1892 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001893
1894#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 {
1896 double x = 9006104071832581.0;
1897 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1898 detected_double_format = ieee_big_endian_format;
1899 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1900 detected_double_format = ieee_little_endian_format;
1901 else
1902 detected_double_format = unknown_format;
1903 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001904#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906#endif
1907
1908#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 {
1910 float y = 16711938.0;
1911 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1912 detected_float_format = ieee_big_endian_format;
1913 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1914 detected_float_format = ieee_little_endian_format;
1915 else
1916 detected_float_format = unknown_format;
1917 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001918#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001920#endif
1921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 double_format = detected_double_format;
1923 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001926 if (FloatInfoType.tp_name == NULL) {
1927 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1928 return 0;
1929 }
1930 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931}
1932
Georg Brandl2ee470f2008-07-16 12:55:28 +00001933int
1934PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001935{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001936 PyFloatObject *f = free_list, *next;
1937 int i = numfree;
1938 while (f) {
1939 next = (PyFloatObject*) Py_TYPE(f);
1940 PyObject_FREE(f);
1941 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001943 free_list = NULL;
1944 numfree = 0;
1945 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001946}
1947
1948void
1949PyFloat_Fini(void)
1950{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001951 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001952}
Tim Peters9905b942003-03-20 20:53:32 +00001953
David Malcolm49526f42012-06-22 14:55:41 -04001954/* Print summary info about the state of the optimized allocator */
1955void
1956_PyFloat_DebugMallocStats(FILE *out)
1957{
1958 _PyDebugAllocatorStats(out,
1959 "free PyFloatObject",
1960 numfree, sizeof(PyFloatObject));
1961}
1962
1963
Tim Peters9905b942003-03-20 20:53:32 +00001964/*----------------------------------------------------------------------------
1965 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001966 */
1967int
1968_PyFloat_Pack4(double x, unsigned char *p, int le)
1969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (float_format == unknown_format) {
1971 unsigned char sign;
1972 int e;
1973 double f;
1974 unsigned int fbits;
1975 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (le) {
1978 p += 3;
1979 incr = -1;
1980 }
Tim Peters9905b942003-03-20 20:53:32 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (x < 0) {
1983 sign = 1;
1984 x = -x;
1985 }
1986 else
1987 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 /* Normalize f to be in the range [1.0, 2.0) */
1992 if (0.5 <= f && f < 1.0) {
1993 f *= 2.0;
1994 e--;
1995 }
1996 else if (f == 0.0)
1997 e = 0;
1998 else {
1999 PyErr_SetString(PyExc_SystemError,
2000 "frexp() result out of range");
2001 return -1;
2002 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (e >= 128)
2005 goto Overflow;
2006 else if (e < -126) {
2007 /* Gradual underflow */
2008 f = ldexp(f, 126 + e);
2009 e = 0;
2010 }
2011 else if (!(e == 0 && f == 0.0)) {
2012 e += 127;
2013 f -= 1.0; /* Get rid of leading 1 */
2014 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 f *= 8388608.0; /* 2**23 */
2017 fbits = (unsigned int)(f + 0.5); /* Round */
2018 assert(fbits <= 8388608);
2019 if (fbits >> 23) {
2020 /* The carry propagated out of a string of 23 1 bits. */
2021 fbits = 0;
2022 ++e;
2023 if (e >= 255)
2024 goto Overflow;
2025 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* First byte */
2028 *p = (sign << 7) | (e >> 1);
2029 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* Second byte */
2032 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2033 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* Third byte */
2036 *p = (fbits >> 8) & 0xFF;
2037 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* Fourth byte */
2040 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 /* Done */
2043 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 }
2046 else {
2047 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002048 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2052 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if ((float_format == ieee_little_endian_format && !le)
2055 || (float_format == ieee_big_endian_format && le)) {
2056 p += 3;
2057 incr = -1;
2058 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 for (i = 0; i < 4; i++) {
2061 *p = *s++;
2062 p += incr;
2063 }
2064 return 0;
2065 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002066 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyErr_SetString(PyExc_OverflowError,
2068 "float too large to pack with f format");
2069 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002070}
2071
2072int
2073_PyFloat_Pack8(double x, unsigned char *p, int le)
2074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (double_format == unknown_format) {
2076 unsigned char sign;
2077 int e;
2078 double f;
2079 unsigned int fhi, flo;
2080 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 if (le) {
2083 p += 7;
2084 incr = -1;
2085 }
Tim Peters9905b942003-03-20 20:53:32 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 if (x < 0) {
2088 sign = 1;
2089 x = -x;
2090 }
2091 else
2092 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 /* Normalize f to be in the range [1.0, 2.0) */
2097 if (0.5 <= f && f < 1.0) {
2098 f *= 2.0;
2099 e--;
2100 }
2101 else if (f == 0.0)
2102 e = 0;
2103 else {
2104 PyErr_SetString(PyExc_SystemError,
2105 "frexp() result out of range");
2106 return -1;
2107 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (e >= 1024)
2110 goto Overflow;
2111 else if (e < -1022) {
2112 /* Gradual underflow */
2113 f = ldexp(f, 1022 + e);
2114 e = 0;
2115 }
2116 else if (!(e == 0 && f == 0.0)) {
2117 e += 1023;
2118 f -= 1.0; /* Get rid of leading 1 */
2119 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2122 f *= 268435456.0; /* 2**28 */
2123 fhi = (unsigned int)f; /* Truncate */
2124 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 f -= (double)fhi;
2127 f *= 16777216.0; /* 2**24 */
2128 flo = (unsigned int)(f + 0.5); /* Round */
2129 assert(flo <= 16777216);
2130 if (flo >> 24) {
2131 /* The carry propagated out of a string of 24 1 bits. */
2132 flo = 0;
2133 ++fhi;
2134 if (fhi >> 28) {
2135 /* And it also progagated out of the next 28 bits. */
2136 fhi = 0;
2137 ++e;
2138 if (e >= 2047)
2139 goto Overflow;
2140 }
2141 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* First byte */
2144 *p = (sign << 7) | (e >> 4);
2145 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 /* Second byte */
2148 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2149 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Third byte */
2152 *p = (fhi >> 16) & 0xFF;
2153 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* Fourth byte */
2156 *p = (fhi >> 8) & 0xFF;
2157 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 /* Fifth byte */
2160 *p = fhi & 0xFF;
2161 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Sixth byte */
2164 *p = (flo >> 16) & 0xFF;
2165 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Seventh byte */
2168 *p = (flo >> 8) & 0xFF;
2169 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Eighth byte */
2172 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002173 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* Done */
2176 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 Overflow:
2179 PyErr_SetString(PyExc_OverflowError,
2180 "float too large to pack with d format");
2181 return -1;
2182 }
2183 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002184 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if ((double_format == ieee_little_endian_format && !le)
2188 || (double_format == ieee_big_endian_format && le)) {
2189 p += 7;
2190 incr = -1;
2191 }
2192
2193 for (i = 0; i < 8; i++) {
2194 *p = *s++;
2195 p += incr;
2196 }
2197 return 0;
2198 }
Tim Peters9905b942003-03-20 20:53:32 +00002199}
2200
2201double
2202_PyFloat_Unpack4(const unsigned char *p, int le)
2203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (float_format == unknown_format) {
2205 unsigned char sign;
2206 int e;
2207 unsigned int f;
2208 double x;
2209 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (le) {
2212 p += 3;
2213 incr = -1;
2214 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* First byte */
2217 sign = (*p >> 7) & 1;
2218 e = (*p & 0x7F) << 1;
2219 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* Second byte */
2222 e |= (*p >> 7) & 1;
2223 f = (*p & 0x7F) << 16;
2224 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 if (e == 255) {
2227 PyErr_SetString(
2228 PyExc_ValueError,
2229 "can't unpack IEEE 754 special value "
2230 "on non-IEEE platform");
2231 return -1;
2232 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Third byte */
2235 f |= *p << 8;
2236 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Fourth byte */
2239 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* XXX This sadly ignores Inf/NaN issues */
2244 if (e == 0)
2245 e = -126;
2246 else {
2247 x += 1.0;
2248 e -= 127;
2249 }
2250 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (sign)
2253 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 return x;
2256 }
2257 else {
2258 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if ((float_format == ieee_little_endian_format && !le)
2261 || (float_format == ieee_big_endian_format && le)) {
2262 char buf[4];
2263 char *d = &buf[3];
2264 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 for (i = 0; i < 4; i++) {
2267 *d-- = *p++;
2268 }
2269 memcpy(&x, buf, 4);
2270 }
2271 else {
2272 memcpy(&x, p, 4);
2273 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 return x;
2276 }
Tim Peters9905b942003-03-20 20:53:32 +00002277}
2278
2279double
2280_PyFloat_Unpack8(const unsigned char *p, int le)
2281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (double_format == unknown_format) {
2283 unsigned char sign;
2284 int e;
2285 unsigned int fhi, flo;
2286 double x;
2287 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 if (le) {
2290 p += 7;
2291 incr = -1;
2292 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* First byte */
2295 sign = (*p >> 7) & 1;
2296 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Second byte */
2301 e |= (*p >> 4) & 0xF;
2302 fhi = (*p & 0xF) << 24;
2303 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 if (e == 2047) {
2306 PyErr_SetString(
2307 PyExc_ValueError,
2308 "can't unpack IEEE 754 special value "
2309 "on non-IEEE platform");
2310 return -1.0;
2311 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Third byte */
2314 fhi |= *p << 16;
2315 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Fourth byte */
2318 fhi |= *p << 8;
2319 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Fifth byte */
2322 fhi |= *p;
2323 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Sixth byte */
2326 flo = *p << 16;
2327 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Seventh byte */
2330 flo |= *p << 8;
2331 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* Eighth byte */
2334 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2337 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 if (e == 0)
2340 e = -1022;
2341 else {
2342 x += 1.0;
2343 e -= 1023;
2344 }
2345 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (sign)
2348 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 return x;
2351 }
2352 else {
2353 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 if ((double_format == ieee_little_endian_format && !le)
2356 || (double_format == ieee_big_endian_format && le)) {
2357 char buf[8];
2358 char *d = &buf[7];
2359 int i;
2360
2361 for (i = 0; i < 8; i++) {
2362 *d-- = *p++;
2363 }
2364 memcpy(&x, buf, 8);
2365 }
2366 else {
2367 memcpy(&x, p, 8);
2368 }
2369
2370 return x;
2371 }
Tim Peters9905b942003-03-20 20:53:32 +00002372}