blob: 3a881c3358b47feabd222a5f55d95bce44f9bbd4 [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
Brett Cannona721aba2016-09-09 14:57:09 -0700127static PyObject *
128float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
129{
130 double x;
131 const char *end;
132 const char *last = s + len;
133 /* strip space */
134 while (s < last && Py_ISSPACE(*s)) {
135 s++;
136 }
137
138 while (s < last - 1 && Py_ISSPACE(last[-1])) {
139 last--;
140 }
141
142 /* We don't care about overflow or underflow. If the platform
143 * supports them, infinities and signed zeroes (on underflow) are
144 * fine. */
145 x = PyOS_string_to_double(s, (char **)&end, NULL);
146 if (end != last) {
147 PyErr_Format(PyExc_ValueError,
148 "could not convert string to float: "
149 "%R", obj);
150 return NULL;
151 }
152 else if (x == -1.0 && PyErr_Occurred()) {
153 return NULL;
154 }
155 else {
156 return PyFloat_FromDouble(x);
157 }
158}
159
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000161PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162{
Brett Cannona721aba2016-09-09 14:57:09 -0700163 const char *s;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000164 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200166 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200170 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000172 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200173 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000174 if (s == NULL) {
175 Py_DECREF(s_buffer);
176 return NULL;
177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000179 else if (PyBytes_Check(v)) {
180 s = PyBytes_AS_STRING(v);
181 len = PyBytes_GET_SIZE(v);
182 }
183 else if (PyByteArray_Check(v)) {
184 s = PyByteArray_AS_STRING(v);
185 len = PyByteArray_GET_SIZE(v);
186 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200187 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
188 s = (const char *)view.buf;
189 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000190 /* Copy to NUL-terminated buffer. */
191 s_buffer = PyBytes_FromStringAndSize(s, len);
192 if (s_buffer == NULL) {
193 PyBuffer_Release(&view);
194 return NULL;
195 }
196 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200197 }
198 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200199 PyErr_Format(PyExc_TypeError,
200 "float() argument must be a string or a number, not '%.200s'",
201 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 return NULL;
203 }
Brett Cannona721aba2016-09-09 14:57:09 -0700204 result = _Py_string_to_number_with_underscores(s, len, "float", v, v,
205 float_from_string_inner);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200206 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000207 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000209}
210
Guido van Rossum234f9421993-06-17 12:35:49 +0000211static void
Fred Drakefd99de62000-07-09 05:02:18 +0000212float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000215 if (numfree >= PyFloat_MAXFREELIST) {
216 PyObject_FREE(op);
217 return;
218 }
219 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_TYPE(op) = (struct _typeobject *)free_list;
221 free_list = op;
222 }
223 else
224 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000225}
226
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227double
Fred Drakefd99de62000-07-09 05:02:18 +0000228PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300231 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (op == NULL) {
235 PyErr_BadArgument();
236 return -1;
237 }
Tim Petersd2364e82001-11-01 20:09:42 +0000238
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300239 if (PyFloat_Check(op)) {
240 return PyFloat_AS_DOUBLE(op);
241 }
242
243 nb = Py_TYPE(op)->tp_as_number;
244 if (nb == NULL || nb->nb_float == NULL) {
245 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
246 op->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return -1;
248 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000249
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300250 res = (*nb->nb_float) (op);
251 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 return -1;
253 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300254 if (!PyFloat_CheckExact(res)) {
255 if (!PyFloat_Check(res)) {
256 PyErr_Format(PyExc_TypeError,
257 "%.50s.__float__ returned non-float (type %.50s)",
258 op->ob_type->tp_name, res->ob_type->tp_name);
259 Py_DECREF(res);
260 return -1;
261 }
262 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
263 "%.50s.__float__ returned non-float (type %.50s). "
264 "The ability to return an instance of a strict subclass of float "
265 "is deprecated, and may be removed in a future version of Python.",
266 op->ob_type->tp_name, res->ob_type->tp_name)) {
267 Py_DECREF(res);
268 return -1;
269 }
270 }
Tim Petersd2364e82001-11-01 20:09:42 +0000271
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300272 val = PyFloat_AS_DOUBLE(res);
273 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275}
276
Neil Schemenauer32117e52001-01-04 01:44:34 +0000277/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000278 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000279 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300280 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000281 stored in obj, and returned from the function invoking this macro.
282*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283#define CONVERT_TO_DOUBLE(obj, dbl) \
284 if (PyFloat_Check(obj)) \
285 dbl = PyFloat_AS_DOUBLE(obj); \
286 else if (convert_to_double(&(obj), &(dbl)) < 0) \
287 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000288
Eric Smith0923d1d2009-04-16 20:16:10 +0000289/* Methods */
290
Neil Schemenauer32117e52001-01-04 01:44:34 +0000291static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000292convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000293{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200294 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (PyLong_Check(obj)) {
297 *dbl = PyLong_AsDouble(obj);
298 if (*dbl == -1.0 && PyErr_Occurred()) {
299 *v = NULL;
300 return -1;
301 }
302 }
303 else {
304 Py_INCREF(Py_NotImplemented);
305 *v = Py_NotImplemented;
306 return -1;
307 }
308 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000309}
310
Eric Smith0923d1d2009-04-16 20:16:10 +0000311static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000312float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000313{
314 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200315 char *buf;
316
317 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
318 'r', 0,
319 Py_DTSF_ADD_DOT_0,
320 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000321 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000322 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200323 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000324 PyMem_Free(buf);
325 return result;
326}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000327
Tim Peters307fa782004-09-23 08:06:40 +0000328/* Comparison is pretty much a nightmare. When comparing float to float,
329 * we do it as straightforwardly (and long-windedly) as conceivable, so
330 * that, e.g., Python x == y delivers the same result as the platform
331 * C x == y when x and/or y is a NaN.
332 * When mixing float with an integer type, there's no good *uniform* approach.
333 * Converting the double to an integer obviously doesn't work, since we
334 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300335 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000336 * 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 +0200337 * 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 +0000338 * 63 bits of precision, but a C double probably has only 53), and then
339 * we can falsely claim equality when low-order integer bits are lost by
340 * coercion to double. So this part is painful too.
341 */
342
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000343static PyObject*
344float_richcompare(PyObject *v, PyObject *w, int op)
345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 double i, j;
347 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 assert(PyFloat_Check(v));
350 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* Switch on the type of w. Set i and j to doubles to be compared,
353 * and op to the richcomp to use.
354 */
355 if (PyFloat_Check(w))
356 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 else if (!Py_IS_FINITE(i)) {
359 if (PyLong_Check(w))
360 /* If i is an infinity, its magnitude exceeds any
361 * finite integer, so it doesn't matter which int we
362 * compare i with. If i is a NaN, similarly.
363 */
364 j = 0.0;
365 else
366 goto Unimplemented;
367 }
Tim Peters307fa782004-09-23 08:06:40 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 else if (PyLong_Check(w)) {
370 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
371 int wsign = _PyLong_Sign(w);
372 size_t nbits;
373 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (vsign != wsign) {
376 /* Magnitudes are irrelevant -- the signs alone
377 * determine the outcome.
378 */
379 i = (double)vsign;
380 j = (double)wsign;
381 goto Compare;
382 }
383 /* The signs are the same. */
384 /* Convert w to a double if it fits. In particular, 0 fits. */
385 nbits = _PyLong_NumBits(w);
386 if (nbits == (size_t)-1 && PyErr_Occurred()) {
387 /* This long is so large that size_t isn't big enough
388 * to hold the # of bits. Replace with little doubles
389 * that give the same outcome -- w is so large that
390 * its magnitude must exceed the magnitude of any
391 * finite float.
392 */
393 PyErr_Clear();
394 i = (double)vsign;
395 assert(wsign != 0);
396 j = wsign * 2.0;
397 goto Compare;
398 }
399 if (nbits <= 48) {
400 j = PyLong_AsDouble(w);
401 /* It's impossible that <= 48 bits overflowed. */
402 assert(j != -1.0 || ! PyErr_Occurred());
403 goto Compare;
404 }
405 assert(wsign != 0); /* else nbits was 0 */
406 assert(vsign != 0); /* if vsign were 0, then since wsign is
407 * not 0, we would have taken the
408 * vsign != wsign branch at the start */
409 /* We want to work with non-negative numbers. */
410 if (vsign < 0) {
411 /* "Multiply both sides" by -1; this also swaps the
412 * comparator.
413 */
414 i = -i;
415 op = _Py_SwappedOp[op];
416 }
417 assert(i > 0.0);
418 (void) frexp(i, &exponent);
419 /* exponent is the # of bits in v before the radix point;
420 * we know that nbits (the # of bits in w) > 48 at this point
421 */
422 if (exponent < 0 || (size_t)exponent < nbits) {
423 i = 1.0;
424 j = 2.0;
425 goto Compare;
426 }
427 if ((size_t)exponent > nbits) {
428 i = 2.0;
429 j = 1.0;
430 goto Compare;
431 }
432 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300433 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 * outcome.
435 */
436 {
437 double fracpart;
438 double intpart;
439 PyObject *result = NULL;
440 PyObject *one = NULL;
441 PyObject *vv = NULL;
442 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (wsign < 0) {
445 ww = PyNumber_Negative(w);
446 if (ww == NULL)
447 goto Error;
448 }
449 else
450 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 fracpart = modf(i, &intpart);
453 vv = PyLong_FromDouble(intpart);
454 if (vv == NULL)
455 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (fracpart != 0.0) {
458 /* Shift left, and or a 1 bit into vv
459 * to represent the lost fraction.
460 */
461 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 one = PyLong_FromLong(1);
464 if (one == NULL)
465 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 temp = PyNumber_Lshift(ww, one);
468 if (temp == NULL)
469 goto Error;
470 Py_DECREF(ww);
471 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 temp = PyNumber_Lshift(vv, one);
474 if (temp == NULL)
475 goto Error;
476 Py_DECREF(vv);
477 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 temp = PyNumber_Or(vv, one);
480 if (temp == NULL)
481 goto Error;
482 Py_DECREF(vv);
483 vv = temp;
484 }
Tim Peters307fa782004-09-23 08:06:40 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 r = PyObject_RichCompareBool(vv, ww, op);
487 if (r < 0)
488 goto Error;
489 result = PyBool_FromLong(r);
490 Error:
491 Py_XDECREF(vv);
492 Py_XDECREF(ww);
493 Py_XDECREF(one);
494 return result;
495 }
496 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000497
Serhiy Storchaka95949422013-08-27 19:40:23 +0300498 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000500
501 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyFPE_START_PROTECT("richcompare", return NULL)
503 switch (op) {
504 case Py_EQ:
505 r = i == j;
506 break;
507 case Py_NE:
508 r = i != j;
509 break;
510 case Py_LE:
511 r = i <= j;
512 break;
513 case Py_GE:
514 r = i >= j;
515 break;
516 case Py_LT:
517 r = i < j;
518 break;
519 case Py_GT:
520 r = i > j;
521 break;
522 }
523 PyFPE_END_PROTECT(r)
524 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000525
526 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500527 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000528}
529
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000530static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000534}
535
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 double a,b;
540 CONVERT_TO_DOUBLE(v, a);
541 CONVERT_TO_DOUBLE(w, b);
542 PyFPE_START_PROTECT("add", return 0)
543 a = a + b;
544 PyFPE_END_PROTECT(a)
545 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000549float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 double a,b;
552 CONVERT_TO_DOUBLE(v, a);
553 CONVERT_TO_DOUBLE(w, b);
554 PyFPE_START_PROTECT("subtract", return 0)
555 a = a - b;
556 PyFPE_END_PROTECT(a)
557 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 double a,b;
564 CONVERT_TO_DOUBLE(v, a);
565 CONVERT_TO_DOUBLE(w, b);
566 PyFPE_START_PROTECT("multiply", return 0)
567 a = a * b;
568 PyFPE_END_PROTECT(a)
569 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double a,b;
576 CONVERT_TO_DOUBLE(v, a);
577 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (b == 0.0) {
579 PyErr_SetString(PyExc_ZeroDivisionError,
580 "float division by zero");
581 return NULL;
582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyFPE_START_PROTECT("divide", return 0)
584 a = a / b;
585 PyFPE_END_PROTECT(a)
586 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 double vx, wx;
593 double mod;
594 CONVERT_TO_DOUBLE(v, vx);
595 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (wx == 0.0) {
597 PyErr_SetString(PyExc_ZeroDivisionError,
598 "float modulo");
599 return NULL;
600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyFPE_START_PROTECT("modulo", return 0)
602 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000603 if (mod) {
604 /* ensure the remainder has the same sign as the denominator */
605 if ((wx < 0) != (mod < 0)) {
606 mod += wx;
607 }
608 }
609 else {
610 /* the remainder is zero, and in the presence of signed zeroes
611 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000612 it has the same sign as the denominator. */
613 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 }
615 PyFPE_END_PROTECT(mod)
616 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 double vx, wx;
623 double div, mod, floordiv;
624 CONVERT_TO_DOUBLE(v, vx);
625 CONVERT_TO_DOUBLE(w, wx);
626 if (wx == 0.0) {
627 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
628 return NULL;
629 }
630 PyFPE_START_PROTECT("divmod", return 0)
631 mod = fmod(vx, wx);
632 /* fmod is typically exact, so vx-mod is *mathematically* an
633 exact multiple of wx. But this is fp arithmetic, and fp
634 vx - mod is an approximation; the result is that div may
635 not be an exact integral value after the division, although
636 it will always be very close to one.
637 */
638 div = (vx - mod) / wx;
639 if (mod) {
640 /* ensure the remainder has the same sign as the denominator */
641 if ((wx < 0) != (mod < 0)) {
642 mod += wx;
643 div -= 1.0;
644 }
645 }
646 else {
647 /* the remainder is zero, and in the presence of signed zeroes
648 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000649 it has the same sign as the denominator. */
650 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 /* snap quotient to nearest integral value */
653 if (div) {
654 floordiv = floor(div);
655 if (div - floordiv > 0.5)
656 floordiv += 1.0;
657 }
658 else {
659 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000660 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 PyFPE_END_PROTECT(floordiv)
663 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000667float_floor_div(PyObject *v, PyObject *w)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 t = float_divmod(v, w);
672 if (t == NULL || t == Py_NotImplemented)
673 return t;
674 assert(PyTuple_CheckExact(t));
675 r = PyTuple_GET_ITEM(t, 0);
676 Py_INCREF(r);
677 Py_DECREF(t);
678 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000679}
680
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000681/* determine whether x is an odd integer or not; assumes that
682 x is not an infinity or nan. */
683#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
684
Tim Peters63a35712001-12-11 19:57:24 +0000685static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000686float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 double iv, iw, ix;
689 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if ((PyObject *)z != Py_None) {
692 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
693 "allowed unless all arguments are integers");
694 return NULL;
695 }
Tim Peters32f453e2001-09-03 08:35:41 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 CONVERT_TO_DOUBLE(v, iv);
698 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Sort out special cases here instead of relying on pow() */
701 if (iw == 0) { /* v**0 is 1, even 0**0 */
702 return PyFloat_FromDouble(1.0);
703 }
704 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
705 return PyFloat_FromDouble(iv);
706 }
707 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
708 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
709 }
710 if (Py_IS_INFINITY(iw)) {
711 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
712 * abs(v) > 1 (including case where v infinite)
713 *
714 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
715 * abs(v) > 1 (including case where v infinite)
716 */
717 iv = fabs(iv);
718 if (iv == 1.0)
719 return PyFloat_FromDouble(1.0);
720 else if ((iw > 0.0) == (iv > 1.0))
721 return PyFloat_FromDouble(fabs(iw)); /* return inf */
722 else
723 return PyFloat_FromDouble(0.0);
724 }
725 if (Py_IS_INFINITY(iv)) {
726 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
727 * both cases, we need to add the appropriate sign if w is
728 * an odd integer.
729 */
730 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
731 if (iw > 0.0)
732 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
733 else
734 return PyFloat_FromDouble(iw_is_odd ?
735 copysign(0.0, iv) : 0.0);
736 }
737 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
738 (already dealt with above), and an error
739 if w is negative. */
740 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
741 if (iw < 0.0) {
742 PyErr_SetString(PyExc_ZeroDivisionError,
743 "0.0 cannot be raised to a "
744 "negative power");
745 return NULL;
746 }
747 /* use correct sign if iw is odd */
748 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
749 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (iv < 0.0) {
752 /* Whether this is an error is a mess, and bumps into libm
753 * bugs so we have to figure it out ourselves.
754 */
755 if (iw != floor(iw)) {
756 /* Negative numbers raised to fractional powers
757 * become complex.
758 */
759 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
760 }
761 /* iw is an exact integer, albeit perhaps a very large
762 * one. Replace iv by its absolute value and remember
763 * to negate the pow result if iw is odd.
764 */
765 iv = -iv;
766 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
767 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
770 /* (-1) ** large_integer also ends up here. Here's an
771 * extract from the comments for the previous
772 * implementation explaining why this special case is
773 * necessary:
774 *
775 * -1 raised to an exact integer should never be exceptional.
776 * Alas, some libms (chiefly glibc as of early 2003) return
777 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
778 * happen to be representable in a *C* integer. That's a
779 * bug.
780 */
781 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
782 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Now iv and iw are finite, iw is nonzero, and iv is
785 * positive and not equal to 1.0. We finally allow
786 * the platform pow to step in and do the rest.
787 */
788 errno = 0;
789 PyFPE_START_PROTECT("pow", return NULL)
790 ix = pow(iv, iw);
791 PyFPE_END_PROTECT(ix)
792 Py_ADJUST_ERANGE1(ix);
793 if (negate_result)
794 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (errno != 0) {
797 /* We don't expect any errno value other than ERANGE, but
798 * the range of libm bugs appears unbounded.
799 */
800 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
801 PyExc_ValueError);
802 return NULL;
803 }
804 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805}
806
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000807#undef DOUBLE_IS_ODD_INTEGER
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000816float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819}
820
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000821static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000822float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000825}
826
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000827static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000828float_is_integer(PyObject *v)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 double x = PyFloat_AsDouble(v);
831 PyObject *o;
832
833 if (x == -1.0 && PyErr_Occurred())
834 return NULL;
835 if (!Py_IS_FINITE(x))
836 Py_RETURN_FALSE;
837 errno = 0;
838 PyFPE_START_PROTECT("is_integer", return NULL)
839 o = (floor(x) == x) ? Py_True : Py_False;
840 PyFPE_END_PROTECT(x)
841 if (errno != 0) {
842 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
843 PyExc_ValueError);
844 return NULL;
845 }
846 Py_INCREF(o);
847 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000848}
849
850#if 0
851static PyObject *
852float_is_inf(PyObject *v)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 double x = PyFloat_AsDouble(v);
855 if (x == -1.0 && PyErr_Occurred())
856 return NULL;
857 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000858}
859
860static PyObject *
861float_is_nan(PyObject *v)
862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 double x = PyFloat_AsDouble(v);
864 if (x == -1.0 && PyErr_Occurred())
865 return NULL;
866 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000867}
868
869static PyObject *
870float_is_finite(PyObject *v)
871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 double x = PyFloat_AsDouble(v);
873 if (x == -1.0 && PyErr_Occurred())
874 return NULL;
875 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000876}
877#endif
878
879static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000880float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 double x = PyFloat_AsDouble(v);
883 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 (void)modf(x, &wholepart);
886 /* Try to get out cheap if this fits in a Python int. The attempt
887 * to cast to long must be protected, as C doesn't define what
888 * happens if the double is too big to fit in a long. Some rare
889 * systems raise an exception then (RISCOS was mentioned as one,
890 * and someone using a non-default option on Sun also bumped into
891 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
892 * still be vulnerable: if a long has more bits of precision than
893 * a double, casting MIN/MAX to double may yield an approximation,
894 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
895 * yield true from the C expression wholepart<=LONG_MAX, despite
896 * that wholepart is actually greater than LONG_MAX.
897 */
898 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
899 const long aslong = (long)wholepart;
900 return PyLong_FromLong(aslong);
901 }
902 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000903}
904
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905/* double_round: rounds a finite double to the closest multiple of
906 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
907 ndigits <= 323). Returns a Python float, or sets a Python error and
908 returns NULL on failure (OverflowError and memory errors are possible). */
909
910#ifndef PY_NO_SHORT_FLOAT_REPR
911/* version of double_round that uses the correctly-rounded string<->double
912 conversions from Python/dtoa.c */
913
914static PyObject *
915double_round(double x, int ndigits) {
916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 double rounded;
918 Py_ssize_t buflen, mybuflen=100;
919 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
920 int decpt, sign;
921 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000922 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000925 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000927 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (buf == NULL) {
929 PyErr_NoMemory();
930 return NULL;
931 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
934 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
935 buflen = buf_end - buf;
936 if (buflen + 8 > mybuflen) {
937 mybuflen = buflen+8;
938 mybuf = (char *)PyMem_Malloc(mybuflen);
939 if (mybuf == NULL) {
940 PyErr_NoMemory();
941 goto exit;
942 }
943 }
944 /* copy buf to mybuf, adding exponent, sign and leading 0 */
945 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
946 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* and convert the resulting string back to a double */
949 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000950 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000952 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (errno == ERANGE && fabs(rounded) >= 1.)
954 PyErr_SetString(PyExc_OverflowError,
955 "rounded value too large to represent");
956 else
957 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* done computing value; now clean up */
960 if (mybuf != shortbuf)
961 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000962 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 _Py_dg_freedtoa(buf);
964 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000965}
966
967#else /* PY_NO_SHORT_FLOAT_REPR */
968
969/* fallback version, to be used when correctly rounded binary<->decimal
970 conversions aren't available */
971
972static PyObject *
973double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 double pow1, pow2, y, z;
975 if (ndigits >= 0) {
976 if (ndigits > 22) {
977 /* pow1 and pow2 are each safe from overflow, but
978 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
979 pow1 = pow(10.0, (double)(ndigits-22));
980 pow2 = 1e22;
981 }
982 else {
983 pow1 = pow(10.0, (double)ndigits);
984 pow2 = 1.0;
985 }
986 y = (x*pow1)*pow2;
987 /* if y overflows, then rounded value is exactly x */
988 if (!Py_IS_FINITE(y))
989 return PyFloat_FromDouble(x);
990 }
991 else {
992 pow1 = pow(10.0, (double)-ndigits);
993 pow2 = 1.0; /* unused; silences a gcc compiler warning */
994 y = x / pow1;
995 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 z = round(y);
998 if (fabs(y-z) == 0.5)
999 /* halfway between two integers; use round-half-even */
1000 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (ndigits >= 0)
1003 z = (z / pow2) / pow1;
1004 else
1005 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* if computation resulted in overflow, raise OverflowError */
1008 if (!Py_IS_FINITE(z)) {
1009 PyErr_SetString(PyExc_OverflowError,
1010 "overflow occurred during round");
1011 return NULL;
1012 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001015}
1016
1017#endif /* PY_NO_SHORT_FLOAT_REPR */
1018
1019/* round a Python float v to the closest multiple of 10**-ndigits */
1020
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001021static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001022float_round(PyObject *v, PyObject *args)
1023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 double x, rounded;
1025 PyObject *o_ndigits = NULL;
1026 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 x = PyFloat_AsDouble(v);
1029 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1030 return NULL;
Steve Dowercb39d1f2015-04-15 16:10:59 -04001031 if (o_ndigits == NULL || o_ndigits == Py_None) {
1032 /* single-argument round or with None ndigits:
1033 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 rounded = round(x);
1035 if (fabs(x-rounded) == 0.5)
1036 /* halfway case: round to even */
1037 rounded = 2.0*round(x/2.0);
1038 return PyLong_FromDouble(rounded);
1039 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* interpret second argument as a Py_ssize_t; clips on overflow */
1042 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1043 if (ndigits == -1 && PyErr_Occurred())
1044 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 /* nans and infinities round to themselves */
1047 if (!Py_IS_FINITE(x))
1048 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1051 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1052 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001053#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1054#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (ndigits > NDIGITS_MAX)
1056 /* return x */
1057 return PyFloat_FromDouble(x);
1058 else if (ndigits < NDIGITS_MIN)
1059 /* return 0.0, but with sign of x */
1060 return PyFloat_FromDouble(0.0*x);
1061 else
1062 /* finite x, and ndigits is not unreasonably large */
1063 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001064#undef NDIGITS_MAX
1065#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001066}
1067
1068static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001069float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (PyFloat_CheckExact(v))
1072 Py_INCREF(v);
1073 else
1074 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1075 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001076}
1077
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001078/* turn ASCII hex characters into integer values and vice versa */
1079
1080static char
1081char_from_hex(int x)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001084 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001085}
1086
1087static int
1088hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 int x;
1090 switch(c) {
1091 case '0':
1092 x = 0;
1093 break;
1094 case '1':
1095 x = 1;
1096 break;
1097 case '2':
1098 x = 2;
1099 break;
1100 case '3':
1101 x = 3;
1102 break;
1103 case '4':
1104 x = 4;
1105 break;
1106 case '5':
1107 x = 5;
1108 break;
1109 case '6':
1110 x = 6;
1111 break;
1112 case '7':
1113 x = 7;
1114 break;
1115 case '8':
1116 x = 8;
1117 break;
1118 case '9':
1119 x = 9;
1120 break;
1121 case 'a':
1122 case 'A':
1123 x = 10;
1124 break;
1125 case 'b':
1126 case 'B':
1127 x = 11;
1128 break;
1129 case 'c':
1130 case 'C':
1131 x = 12;
1132 break;
1133 case 'd':
1134 case 'D':
1135 x = 13;
1136 break;
1137 case 'e':
1138 case 'E':
1139 x = 14;
1140 break;
1141 case 'f':
1142 case 'F':
1143 x = 15;
1144 break;
1145 default:
1146 x = -1;
1147 break;
1148 }
1149 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001150}
1151
1152/* convert a float to a hexadecimal string */
1153
1154/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1155 of the form 4k+1. */
1156#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1157
1158static PyObject *
1159float_hex(PyObject *v)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 double x, m;
1162 int e, shift, i, si, esign;
1163 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1164 trailing NUL byte. */
1165 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001170 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001173 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return PyUnicode_FromString("-0x0.0p+0");
1175 else
1176 return PyUnicode_FromString("0x0.0p+0");
1177 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001180 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 m = ldexp(m, shift);
1182 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 si = 0;
1185 s[si] = char_from_hex((int)m);
1186 si++;
1187 m -= (int)m;
1188 s[si] = '.';
1189 si++;
1190 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1191 m *= 16.0;
1192 s[si] = char_from_hex((int)m);
1193 si++;
1194 m -= (int)m;
1195 }
1196 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (e < 0) {
1199 esign = (int)'-';
1200 e = -e;
1201 }
1202 else
1203 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (x < 0.0)
1206 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1207 else
1208 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001209}
1210
1211PyDoc_STRVAR(float_hex_doc,
1212"float.hex() -> string\n\
1213\n\
1214Return a hexadecimal representation of a floating-point number.\n\
1215>>> (-0.1).hex()\n\
1216'-0x1.999999999999ap-4'\n\
1217>>> 3.14159.hex()\n\
1218'0x1.921f9f01b866ep+1'");
1219
1220/* Convert a hexadecimal string to a float. */
1221
1222static PyObject *
1223float_fromhex(PyObject *cls, PyObject *arg)
1224{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001225 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 double x;
1227 long exp, top_exp, lsb, key_digit;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001228 const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 int half_eps, digit, round_up, negate=0;
1230 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /*
1233 * For the sake of simplicity and correctness, we impose an artificial
1234 * limit on ndigits, the total number of hex digits in the coefficient
1235 * The limit is chosen to ensure that, writing exp for the exponent,
1236 *
1237 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1238 * guaranteed to overflow (provided it's nonzero)
1239 *
1240 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1241 * guaranteed to underflow to 0.
1242 *
1243 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1244 * overflow in the calculation of exp and top_exp below.
1245 *
1246 * More specifically, ndigits is assumed to satisfy the following
1247 * inequalities:
1248 *
1249 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1250 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1251 *
1252 * If either of these inequalities is not satisfied, a ValueError is
1253 * raised. Otherwise, write x for the value of the hex string, and
1254 * assume x is nonzero. Then
1255 *
1256 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1257 *
1258 * Now if exp > LONG_MAX/2 then:
1259 *
1260 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1261 * = DBL_MAX_EXP
1262 *
1263 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1264 * double, so overflows. If exp < LONG_MIN/2, then
1265 *
1266 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1267 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1268 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1269 *
1270 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1271 * when converted to a C double.
1272 *
1273 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1274 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1275 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
Serhiy Storchaka06515832016-11-20 09:13:07 +02001277 s = PyUnicode_AsUTF8AndSize(arg, &length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (s == NULL)
1279 return NULL;
1280 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 /********************
1283 * Parse the string *
1284 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /* leading whitespace */
1287 while (Py_ISSPACE(*s))
1288 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 /* infinities and nans */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001291 x = _Py_parse_inf_or_nan(s, (char **)&coeff_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (coeff_end != s) {
1293 s = coeff_end;
1294 goto finished;
1295 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* optional sign */
1298 if (*s == '-') {
1299 s++;
1300 negate = 1;
1301 }
1302 else if (*s == '+')
1303 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 /* [0x] */
1306 s_store = s;
1307 if (*s == '0') {
1308 s++;
1309 if (*s == 'x' || *s == 'X')
1310 s++;
1311 else
1312 s = s_store;
1313 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /* coefficient: <integer> [. <fraction>] */
1316 coeff_start = s;
1317 while (hex_from_char(*s) >= 0)
1318 s++;
1319 s_store = s;
1320 if (*s == '.') {
1321 s++;
1322 while (hex_from_char(*s) >= 0)
1323 s++;
1324 coeff_end = s-1;
1325 }
1326 else
1327 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* ndigits = total # of hex digits; fdigits = # after point */
1330 ndigits = coeff_end - coeff_start;
1331 fdigits = coeff_end - s_store;
1332 if (ndigits == 0)
1333 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001334 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1335 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* [p <exponent>] */
1339 if (*s == 'p' || *s == 'P') {
1340 s++;
1341 exp_start = s;
1342 if (*s == '-' || *s == '+')
1343 s++;
1344 if (!('0' <= *s && *s <= '9'))
1345 goto parse_error;
1346 s++;
1347 while ('0' <= *s && *s <= '9')
1348 s++;
1349 exp = strtol(exp_start, NULL, 10);
1350 }
1351 else
1352 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001353
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001354/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1356 coeff_end-(j) : \
1357 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /*******************************************
1360 * Compute rounded value of the hex string *
1361 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* Discard leading zeros, and catch extreme overflow and underflow */
1364 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1365 ndigits--;
1366 if (ndigits == 0 || exp < LONG_MIN/2) {
1367 x = 0.0;
1368 goto finished;
1369 }
1370 if (exp > LONG_MAX/2)
1371 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* Adjust exponent for fractional part. */
1374 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1377 top_exp = exp + 4*((long)ndigits - 1);
1378 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1379 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 /* catch almost all nonextreme cases of overflow and underflow here */
1382 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1383 x = 0.0;
1384 goto finished;
1385 }
1386 if (top_exp > DBL_MAX_EXP)
1387 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* lsb = exponent of least significant bit of the *rounded* value.
1390 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001391 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 x = 0.0;
1394 if (exp >= lsb) {
1395 /* no rounding required */
1396 for (i = ndigits-1; i >= 0; i--)
1397 x = 16.0*x + HEX_DIGIT(i);
1398 x = ldexp(x, (int)(exp));
1399 goto finished;
1400 }
1401 /* rounding required. key_digit is the index of the hex digit
1402 containing the first bit to be rounded away. */
1403 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1404 key_digit = (lsb - exp - 1) / 4;
1405 for (i = ndigits-1; i > key_digit; i--)
1406 x = 16.0*x + HEX_DIGIT(i);
1407 digit = HEX_DIGIT(key_digit);
1408 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1411 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1412 if ((digit & half_eps) != 0) {
1413 round_up = 0;
1414 if ((digit & (3*half_eps-1)) != 0 ||
1415 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1416 round_up = 1;
1417 else
1418 for (i = key_digit-1; i >= 0; i--)
1419 if (HEX_DIGIT(i) != 0) {
1420 round_up = 1;
1421 break;
1422 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001423 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 x += 2*half_eps;
1425 if (top_exp == DBL_MAX_EXP &&
1426 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1427 /* overflow corner case: pre-rounded value <
1428 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1429 goto overflow_error;
1430 }
1431 }
1432 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001433
1434 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 /* optional trailing whitespace leading to the end of the string */
1436 while (Py_ISSPACE(*s))
1437 s++;
1438 if (s != s_end)
1439 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001440 result = PyFloat_FromDouble(negate ? -x : x);
1441 if (cls != (PyObject *)&PyFloat_Type && result != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001442 Py_SETREF(result, PyObject_CallFunctionObjArgs(cls, result, NULL));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001445
1446 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyErr_SetString(PyExc_OverflowError,
1448 "hexadecimal value too large to represent as a float");
1449 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001450
1451 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyErr_SetString(PyExc_ValueError,
1453 "invalid hexadecimal floating-point string");
1454 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001455
1456 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyErr_SetString(PyExc_ValueError,
1458 "hexadecimal string too long to convert");
1459 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001460}
1461
1462PyDoc_STRVAR(float_fromhex_doc,
1463"float.fromhex(string) -> float\n\
1464\n\
1465Create a floating-point number from a hexadecimal string.\n\
1466>>> float.fromhex('0x1.ffffp10')\n\
14672047.984375\n\
1468>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001469-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001470
1471
Christian Heimes26855632008-01-27 23:50:43 +00001472static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001473float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 double self;
1476 double float_part;
1477 int exponent;
1478 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *py_exponent = NULL;
1481 PyObject *numerator = NULL;
1482 PyObject *denominator = NULL;
1483 PyObject *result_pair = NULL;
1484 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (Py_IS_INFINITY(self)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001489 PyErr_SetString(PyExc_OverflowError,
1490 "cannot convert Infinity to integer ratio");
1491 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (Py_IS_NAN(self)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001494 PyErr_SetString(PyExc_ValueError,
1495 "cannot convert NaN to integer ratio");
1496 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 }
Christian Heimes26855632008-01-27 23:50:43 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1500 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1501 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1504 float_part *= 2.0;
1505 exponent--;
1506 }
1507 /* self == float_part * 2**exponent exactly and float_part is integral.
1508 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1509 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001512 if (numerator == NULL)
1513 goto error;
1514 denominator = PyLong_FromLong(1);
1515 if (denominator == NULL)
1516 goto error;
1517 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1518 if (py_exponent == NULL)
1519 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001523 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001524 long_methods->nb_lshift(numerator, py_exponent));
1525 if (numerator == NULL)
1526 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 }
1528 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001529 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001530 long_methods->nb_lshift(denominator, py_exponent));
1531 if (denominator == NULL)
1532 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 }
1534
1535 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001536
Christian Heimes26855632008-01-27 23:50:43 +00001537error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 Py_XDECREF(py_exponent);
1539 Py_XDECREF(denominator);
1540 Py_XDECREF(numerator);
1541 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001542}
1543
1544PyDoc_STRVAR(float_as_integer_ratio_doc,
1545"float.as_integer_ratio() -> (int, int)\n"
1546"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001547"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001548"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001549"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001550"\n"
1551">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001552"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001553">>> (0.0).as_integer_ratio()\n"
1554"(0, 1)\n"
1555">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001556"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001557
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001558
Jeremy Hylton938ace62002-07-17 16:30:39 +00001559static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001560float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1561
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562static PyObject *
1563float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyObject *x = Py_False; /* Integer zero */
1566 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 if (type != &PyFloat_Type)
1569 return float_subtype_new(type, args, kwds); /* Wimp out */
1570 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1571 return NULL;
Serhiy Storchaka58d23e62017-03-06 00:53:39 +02001572 if (kwds != NULL && PyDict_GET_SIZE(kwds) != 0) {
1573 if (PyErr_Warn(PyExc_DeprecationWarning,
1574 "Using 'x' as a keyword argument is deprecated; "
1575 "specify the value as a positional argument instead") < 0)
1576 return NULL;
1577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 /* If it's a string, but not a string subclass, use
1579 PyFloat_FromString. */
1580 if (PyUnicode_CheckExact(x))
1581 return PyFloat_FromString(x);
1582 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583}
1584
Guido van Rossumbef14172001-08-29 15:47:46 +00001585/* Wimpy, slow approach to tp_new calls for subtypes of float:
1586 first create a regular float from whatever arguments we got,
1587 then allocate a subtype instance and initialize its ob_fval
1588 from the regular float. The regular float is then thrown away.
1589*/
1590static PyObject *
1591float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 assert(PyType_IsSubtype(type, &PyFloat_Type));
1596 tmp = float_new(&PyFloat_Type, args, kwds);
1597 if (tmp == NULL)
1598 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001599 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 newobj = type->tp_alloc(type, 0);
1601 if (newobj == NULL) {
1602 Py_DECREF(tmp);
1603 return NULL;
1604 }
1605 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1606 Py_DECREF(tmp);
1607 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001608}
1609
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001610static PyObject *
1611float_getnewargs(PyFloatObject *v)
1612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001614}
1615
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001616/* this is for the benefit of the pack/unpack routines below */
1617
1618typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620} float_format_type;
1621
1622static float_format_type double_format, float_format;
1623static float_format_type detected_double_format, detected_float_format;
1624
1625static PyObject *
1626float_getformat(PyTypeObject *v, PyObject* arg)
1627{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001628 const char *s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (!PyUnicode_Check(arg)) {
1632 PyErr_Format(PyExc_TypeError,
1633 "__getformat__() argument must be string, not %.500s",
1634 Py_TYPE(arg)->tp_name);
1635 return NULL;
1636 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001637 s = PyUnicode_AsUTF8(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (s == NULL)
1639 return NULL;
1640 if (strcmp(s, "double") == 0) {
1641 r = double_format;
1642 }
1643 else if (strcmp(s, "float") == 0) {
1644 r = float_format;
1645 }
1646 else {
1647 PyErr_SetString(PyExc_ValueError,
1648 "__getformat__() argument 1 must be "
1649 "'double' or 'float'");
1650 return NULL;
1651 }
1652
1653 switch (r) {
1654 case unknown_format:
1655 return PyUnicode_FromString("unknown");
1656 case ieee_little_endian_format:
1657 return PyUnicode_FromString("IEEE, little-endian");
1658 case ieee_big_endian_format:
1659 return PyUnicode_FromString("IEEE, big-endian");
1660 default:
1661 Py_FatalError("insane float_format or double_format");
1662 return NULL;
1663 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001664}
1665
1666PyDoc_STRVAR(float_getformat_doc,
1667"float.__getformat__(typestr) -> string\n"
1668"\n"
1669"You probably don't want to use this function. It exists mainly to be\n"
1670"used in Python's test suite.\n"
1671"\n"
1672"typestr must be 'double' or 'float'. This function returns whichever of\n"
1673"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1674"format of floating point numbers used by the C type named by typestr.");
1675
1676static PyObject *
1677float_setformat(PyTypeObject *v, PyObject* args)
1678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 char* typestr;
1680 char* format;
1681 float_format_type f;
1682 float_format_type detected;
1683 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1686 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (strcmp(typestr, "double") == 0) {
1689 p = &double_format;
1690 detected = detected_double_format;
1691 }
1692 else if (strcmp(typestr, "float") == 0) {
1693 p = &float_format;
1694 detected = detected_float_format;
1695 }
1696 else {
1697 PyErr_SetString(PyExc_ValueError,
1698 "__setformat__() argument 1 must "
1699 "be 'double' or 'float'");
1700 return NULL;
1701 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (strcmp(format, "unknown") == 0) {
1704 f = unknown_format;
1705 }
1706 else if (strcmp(format, "IEEE, little-endian") == 0) {
1707 f = ieee_little_endian_format;
1708 }
1709 else if (strcmp(format, "IEEE, big-endian") == 0) {
1710 f = ieee_big_endian_format;
1711 }
1712 else {
1713 PyErr_SetString(PyExc_ValueError,
1714 "__setformat__() argument 2 must be "
1715 "'unknown', 'IEEE, little-endian' or "
1716 "'IEEE, big-endian'");
1717 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (f != unknown_format && f != detected) {
1722 PyErr_Format(PyExc_ValueError,
1723 "can only set %s format to 'unknown' or the "
1724 "detected platform value", typestr);
1725 return NULL;
1726 }
1727
1728 *p = f;
1729 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001730}
1731
1732PyDoc_STRVAR(float_setformat_doc,
1733"float.__setformat__(typestr, fmt) -> None\n"
1734"\n"
1735"You probably don't want to use this function. It exists mainly to be\n"
1736"used in Python's test suite.\n"
1737"\n"
1738"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1739"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1740"one of the latter two if it appears to match the underlying C reality.\n"
1741"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001742"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001743"This affects how floats are converted to and from binary strings.");
1744
Guido van Rossumb43daf72007-08-01 18:08:08 +00001745static PyObject *
1746float_getzero(PyObject *v, void *closure)
1747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001749}
1750
Eric Smith8c663262007-08-25 02:26:07 +00001751static PyObject *
1752float__format__(PyObject *self, PyObject *args)
1753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755 _PyUnicodeWriter writer;
1756 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1759 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760
Victor Stinner8f674cc2013-04-17 23:02:17 +02001761 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 ret = _PyFloat_FormatAdvancedWriter(
1763 &writer,
1764 self,
1765 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1766 if (ret == -1) {
1767 _PyUnicodeWriter_Dealloc(&writer);
1768 return NULL;
1769 }
1770 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001771}
1772
1773PyDoc_STRVAR(float__format__doc,
1774"float.__format__(format_spec) -> string\n"
1775"\n"
1776"Formats the float according to format_spec.");
1777
1778
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001779static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001781 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001783 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001785 "Return the Integral closest to x, rounding half toward even.\n"
1786 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1788 float_as_integer_ratio_doc},
1789 {"fromhex", (PyCFunction)float_fromhex,
1790 METH_O|METH_CLASS, float_fromhex_doc},
1791 {"hex", (PyCFunction)float_hex,
1792 METH_NOARGS, float_hex_doc},
1793 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001794 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001795#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001797 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001799 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001801 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001802#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1804 {"__getformat__", (PyCFunction)float_getformat,
1805 METH_O|METH_CLASS, float_getformat_doc},
1806 {"__setformat__", (PyCFunction)float_setformat,
1807 METH_VARARGS|METH_CLASS, float_setformat_doc},
1808 {"__format__", (PyCFunction)float__format__,
1809 METH_VARARGS, float__format__doc},
1810 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001811};
1812
Guido van Rossumb43daf72007-08-01 18:08:08 +00001813static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001815 (getter)float_float, (setter)NULL,
1816 "the real part of a complex number",
1817 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001819 (getter)float_getzero, (setter)NULL,
1820 "the imaginary part of a complex number",
1821 NULL},
1822 {NULL} /* Sentinel */
1823};
1824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001825PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826"float(x) -> floating point number\n\
1827\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001828Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829
1830
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001831static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 float_add, /*nb_add*/
1833 float_sub, /*nb_subtract*/
1834 float_mul, /*nb_multiply*/
1835 float_rem, /*nb_remainder*/
1836 float_divmod, /*nb_divmod*/
1837 float_pow, /*nb_power*/
1838 (unaryfunc)float_neg, /*nb_negative*/
1839 (unaryfunc)float_float, /*nb_positive*/
1840 (unaryfunc)float_abs, /*nb_absolute*/
1841 (inquiry)float_bool, /*nb_bool*/
1842 0, /*nb_invert*/
1843 0, /*nb_lshift*/
1844 0, /*nb_rshift*/
1845 0, /*nb_and*/
1846 0, /*nb_xor*/
1847 0, /*nb_or*/
1848 float_trunc, /*nb_int*/
1849 0, /*nb_reserved*/
1850 float_float, /*nb_float*/
1851 0, /* nb_inplace_add */
1852 0, /* nb_inplace_subtract */
1853 0, /* nb_inplace_multiply */
1854 0, /* nb_inplace_remainder */
1855 0, /* nb_inplace_power */
1856 0, /* nb_inplace_lshift */
1857 0, /* nb_inplace_rshift */
1858 0, /* nb_inplace_and */
1859 0, /* nb_inplace_xor */
1860 0, /* nb_inplace_or */
1861 float_floor_div, /* nb_floor_divide */
1862 float_div, /* nb_true_divide */
1863 0, /* nb_inplace_floor_divide */
1864 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001865};
1866
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001867PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1869 "float",
1870 sizeof(PyFloatObject),
1871 0,
1872 (destructor)float_dealloc, /* tp_dealloc */
1873 0, /* tp_print */
1874 0, /* tp_getattr */
1875 0, /* tp_setattr */
1876 0, /* tp_reserved */
1877 (reprfunc)float_repr, /* tp_repr */
1878 &float_as_number, /* tp_as_number */
1879 0, /* tp_as_sequence */
1880 0, /* tp_as_mapping */
1881 (hashfunc)float_hash, /* tp_hash */
1882 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001883 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 PyObject_GenericGetAttr, /* tp_getattro */
1885 0, /* tp_setattro */
1886 0, /* tp_as_buffer */
1887 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1888 float_doc, /* tp_doc */
1889 0, /* tp_traverse */
1890 0, /* tp_clear */
1891 float_richcompare, /* tp_richcompare */
1892 0, /* tp_weaklistoffset */
1893 0, /* tp_iter */
1894 0, /* tp_iternext */
1895 float_methods, /* tp_methods */
1896 0, /* tp_members */
1897 float_getset, /* tp_getset */
1898 0, /* tp_base */
1899 0, /* tp_dict */
1900 0, /* tp_descr_get */
1901 0, /* tp_descr_set */
1902 0, /* tp_dictoffset */
1903 0, /* tp_init */
1904 0, /* tp_alloc */
1905 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001906};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001907
Victor Stinner1c8f0592013-07-22 22:24:54 +02001908int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001909_PyFloat_Init(void)
1910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 /* We attempt to determine if this machine is using IEEE
1912 floating point formats by peering at the bits of some
1913 carefully chosen values. If it looks like we are on an
1914 IEEE platform, the float packing/unpacking routines can
1915 just copy bits, if not they resort to arithmetic & shifts
1916 and masks. The shifts & masks approach works on all finite
1917 values, but what happens to infinities, NaNs and signed
1918 zeroes on packing is an accident, and attempting to unpack
1919 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Note that if we're on some whacked-out platform which uses
1922 IEEE formats but isn't strictly little-endian or big-
1923 endian, we will fall back to the portable shifts & masks
1924 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001925
1926#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 {
1928 double x = 9006104071832581.0;
1929 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1930 detected_double_format = ieee_big_endian_format;
1931 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1932 detected_double_format = ieee_little_endian_format;
1933 else
1934 detected_double_format = unknown_format;
1935 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001938#endif
1939
1940#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 {
1942 float y = 16711938.0;
1943 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1944 detected_float_format = ieee_big_endian_format;
1945 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1946 detected_float_format = ieee_little_endian_format;
1947 else
1948 detected_float_format = unknown_format;
1949 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001950#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001952#endif
1953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 double_format = detected_double_format;
1955 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001958 if (FloatInfoType.tp_name == NULL) {
1959 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1960 return 0;
1961 }
1962 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001963}
1964
Georg Brandl2ee470f2008-07-16 12:55:28 +00001965int
1966PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001967{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001968 PyFloatObject *f = free_list, *next;
1969 int i = numfree;
1970 while (f) {
1971 next = (PyFloatObject*) Py_TYPE(f);
1972 PyObject_FREE(f);
1973 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001975 free_list = NULL;
1976 numfree = 0;
1977 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001978}
1979
1980void
1981PyFloat_Fini(void)
1982{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001983 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001984}
Tim Peters9905b942003-03-20 20:53:32 +00001985
David Malcolm49526f42012-06-22 14:55:41 -04001986/* Print summary info about the state of the optimized allocator */
1987void
1988_PyFloat_DebugMallocStats(FILE *out)
1989{
1990 _PyDebugAllocatorStats(out,
1991 "free PyFloatObject",
1992 numfree, sizeof(PyFloatObject));
1993}
1994
1995
Tim Peters9905b942003-03-20 20:53:32 +00001996/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001997 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
1998 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
1999 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
2000 * We use:
2001 * bits = (unsigned short)f; Note the truncation
2002 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
2003 * bits++;
2004 * }
Tim Peters9905b942003-03-20 20:53:32 +00002005 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002006
2007int
2008_PyFloat_Pack2(double x, unsigned char *p, int le)
2009{
2010 unsigned char sign;
2011 int e;
2012 double f;
2013 unsigned short bits;
2014 int incr = 1;
2015
2016 if (x == 0.0) {
2017 sign = (copysign(1.0, x) == -1.0);
2018 e = 0;
2019 bits = 0;
2020 }
2021 else if (Py_IS_INFINITY(x)) {
2022 sign = (x < 0.0);
2023 e = 0x1f;
2024 bits = 0;
2025 }
2026 else if (Py_IS_NAN(x)) {
2027 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2028 1024 quiet), but there are only two quiet NaNs that don't arise by
2029 quieting a signaling NaN; we get those by setting the topmost bit
2030 of the fraction field and clearing all other fraction bits. We
2031 choose the one with the appropriate sign. */
2032 sign = (copysign(1.0, x) == -1.0);
2033 e = 0x1f;
2034 bits = 512;
2035 }
2036 else {
2037 sign = (x < 0.0);
2038 if (sign) {
2039 x = -x;
2040 }
2041
2042 f = frexp(x, &e);
2043 if (f < 0.5 || f >= 1.0) {
2044 PyErr_SetString(PyExc_SystemError,
2045 "frexp() result out of range");
2046 return -1;
2047 }
2048
2049 /* Normalize f to be in the range [1.0, 2.0) */
2050 f *= 2.0;
2051 e--;
2052
2053 if (e >= 16) {
2054 goto Overflow;
2055 }
2056 else if (e < -25) {
2057 /* |x| < 2**-25. Underflow to zero. */
2058 f = 0.0;
2059 e = 0;
2060 }
2061 else if (e < -14) {
2062 /* |x| < 2**-14. Gradual underflow */
2063 f = ldexp(f, 14 + e);
2064 e = 0;
2065 }
2066 else /* if (!(e == 0 && f == 0.0)) */ {
2067 e += 15;
2068 f -= 1.0; /* Get rid of leading 1 */
2069 }
2070
2071 f *= 1024.0; /* 2**10 */
2072 /* Round to even */
2073 bits = (unsigned short)f; /* Note the truncation */
2074 assert(bits < 1024);
2075 assert(e < 31);
2076 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2077 ++bits;
2078 if (bits == 1024) {
2079 /* The carry propagated out of a string of 10 1 bits. */
2080 bits = 0;
2081 ++e;
2082 if (e == 31)
2083 goto Overflow;
2084 }
2085 }
2086 }
2087
2088 bits |= (e << 10) | (sign << 15);
2089
2090 /* Write out result. */
2091 if (le) {
2092 p += 1;
2093 incr = -1;
2094 }
2095
2096 /* First byte */
2097 *p = (unsigned char)((bits >> 8) & 0xFF);
2098 p += incr;
2099
2100 /* Second byte */
2101 *p = (unsigned char)(bits & 0xFF);
2102
2103 return 0;
2104
2105 Overflow:
2106 PyErr_SetString(PyExc_OverflowError,
2107 "float too large to pack with e format");
2108 return -1;
2109}
2110
Tim Peters9905b942003-03-20 20:53:32 +00002111int
2112_PyFloat_Pack4(double x, unsigned char *p, int le)
2113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (float_format == unknown_format) {
2115 unsigned char sign;
2116 int e;
2117 double f;
2118 unsigned int fbits;
2119 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (le) {
2122 p += 3;
2123 incr = -1;
2124 }
Tim Peters9905b942003-03-20 20:53:32 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (x < 0) {
2127 sign = 1;
2128 x = -x;
2129 }
2130 else
2131 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* Normalize f to be in the range [1.0, 2.0) */
2136 if (0.5 <= f && f < 1.0) {
2137 f *= 2.0;
2138 e--;
2139 }
2140 else if (f == 0.0)
2141 e = 0;
2142 else {
2143 PyErr_SetString(PyExc_SystemError,
2144 "frexp() result out of range");
2145 return -1;
2146 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (e >= 128)
2149 goto Overflow;
2150 else if (e < -126) {
2151 /* Gradual underflow */
2152 f = ldexp(f, 126 + e);
2153 e = 0;
2154 }
2155 else if (!(e == 0 && f == 0.0)) {
2156 e += 127;
2157 f -= 1.0; /* Get rid of leading 1 */
2158 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 f *= 8388608.0; /* 2**23 */
2161 fbits = (unsigned int)(f + 0.5); /* Round */
2162 assert(fbits <= 8388608);
2163 if (fbits >> 23) {
2164 /* The carry propagated out of a string of 23 1 bits. */
2165 fbits = 0;
2166 ++e;
2167 if (e >= 255)
2168 goto Overflow;
2169 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* First byte */
2172 *p = (sign << 7) | (e >> 1);
2173 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* Second byte */
2176 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2177 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Third byte */
2180 *p = (fbits >> 8) & 0xFF;
2181 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 /* Fourth byte */
2184 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Done */
2187 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 }
2190 else {
2191 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002192 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2196 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if ((float_format == ieee_little_endian_format && !le)
2199 || (float_format == ieee_big_endian_format && le)) {
2200 p += 3;
2201 incr = -1;
2202 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 for (i = 0; i < 4; i++) {
2205 *p = *s++;
2206 p += incr;
2207 }
2208 return 0;
2209 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002210 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyErr_SetString(PyExc_OverflowError,
2212 "float too large to pack with f format");
2213 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002214}
2215
2216int
2217_PyFloat_Pack8(double x, unsigned char *p, int le)
2218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if (double_format == unknown_format) {
2220 unsigned char sign;
2221 int e;
2222 double f;
2223 unsigned int fhi, flo;
2224 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 if (le) {
2227 p += 7;
2228 incr = -1;
2229 }
Tim Peters9905b942003-03-20 20:53:32 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 if (x < 0) {
2232 sign = 1;
2233 x = -x;
2234 }
2235 else
2236 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Normalize f to be in the range [1.0, 2.0) */
2241 if (0.5 <= f && f < 1.0) {
2242 f *= 2.0;
2243 e--;
2244 }
2245 else if (f == 0.0)
2246 e = 0;
2247 else {
2248 PyErr_SetString(PyExc_SystemError,
2249 "frexp() result out of range");
2250 return -1;
2251 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (e >= 1024)
2254 goto Overflow;
2255 else if (e < -1022) {
2256 /* Gradual underflow */
2257 f = ldexp(f, 1022 + e);
2258 e = 0;
2259 }
2260 else if (!(e == 0 && f == 0.0)) {
2261 e += 1023;
2262 f -= 1.0; /* Get rid of leading 1 */
2263 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2266 f *= 268435456.0; /* 2**28 */
2267 fhi = (unsigned int)f; /* Truncate */
2268 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 f -= (double)fhi;
2271 f *= 16777216.0; /* 2**24 */
2272 flo = (unsigned int)(f + 0.5); /* Round */
2273 assert(flo <= 16777216);
2274 if (flo >> 24) {
2275 /* The carry propagated out of a string of 24 1 bits. */
2276 flo = 0;
2277 ++fhi;
2278 if (fhi >> 28) {
2279 /* And it also progagated out of the next 28 bits. */
2280 fhi = 0;
2281 ++e;
2282 if (e >= 2047)
2283 goto Overflow;
2284 }
2285 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* First byte */
2288 *p = (sign << 7) | (e >> 4);
2289 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 /* Second byte */
2292 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2293 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Third byte */
2296 *p = (fhi >> 16) & 0xFF;
2297 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* Fourth byte */
2300 *p = (fhi >> 8) & 0xFF;
2301 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* Fifth byte */
2304 *p = fhi & 0xFF;
2305 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Sixth byte */
2308 *p = (flo >> 16) & 0xFF;
2309 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Seventh byte */
2312 *p = (flo >> 8) & 0xFF;
2313 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* Eighth byte */
2316 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002317 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* Done */
2320 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 Overflow:
2323 PyErr_SetString(PyExc_OverflowError,
2324 "float too large to pack with d format");
2325 return -1;
2326 }
2327 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002328 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if ((double_format == ieee_little_endian_format && !le)
2332 || (double_format == ieee_big_endian_format && le)) {
2333 p += 7;
2334 incr = -1;
2335 }
2336
2337 for (i = 0; i < 8; i++) {
2338 *p = *s++;
2339 p += incr;
2340 }
2341 return 0;
2342 }
Tim Peters9905b942003-03-20 20:53:32 +00002343}
2344
2345double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002346_PyFloat_Unpack2(const unsigned char *p, int le)
2347{
2348 unsigned char sign;
2349 int e;
2350 unsigned int f;
2351 double x;
2352 int incr = 1;
2353
2354 if (le) {
2355 p += 1;
2356 incr = -1;
2357 }
2358
2359 /* First byte */
2360 sign = (*p >> 7) & 1;
2361 e = (*p & 0x7C) >> 2;
2362 f = (*p & 0x03) << 8;
2363 p += incr;
2364
2365 /* Second byte */
2366 f |= *p;
2367
2368 if (e == 0x1f) {
2369#ifdef PY_NO_SHORT_FLOAT_REPR
2370 if (f == 0) {
2371 /* Infinity */
2372 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2373 }
2374 else {
2375 /* NaN */
2376#ifdef Py_NAN
2377 return sign ? -Py_NAN : Py_NAN;
2378#else
2379 PyErr_SetString(
2380 PyExc_ValueError,
2381 "can't unpack IEEE 754 NaN "
2382 "on platform that does not support NaNs");
2383 return -1;
2384#endif /* #ifdef Py_NAN */
2385 }
2386#else
2387 if (f == 0) {
2388 /* Infinity */
2389 return _Py_dg_infinity(sign);
2390 }
2391 else {
2392 /* NaN */
2393 return _Py_dg_stdnan(sign);
2394 }
2395#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2396 }
2397
2398 x = (double)f / 1024.0;
2399
2400 if (e == 0) {
2401 e = -14;
2402 }
2403 else {
2404 x += 1.0;
2405 e -= 15;
2406 }
2407 x = ldexp(x, e);
2408
2409 if (sign)
2410 x = -x;
2411
2412 return x;
2413}
2414
2415double
Tim Peters9905b942003-03-20 20:53:32 +00002416_PyFloat_Unpack4(const unsigned char *p, int le)
2417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (float_format == unknown_format) {
2419 unsigned char sign;
2420 int e;
2421 unsigned int f;
2422 double x;
2423 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (le) {
2426 p += 3;
2427 incr = -1;
2428 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 /* First byte */
2431 sign = (*p >> 7) & 1;
2432 e = (*p & 0x7F) << 1;
2433 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* Second byte */
2436 e |= (*p >> 7) & 1;
2437 f = (*p & 0x7F) << 16;
2438 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (e == 255) {
2441 PyErr_SetString(
2442 PyExc_ValueError,
2443 "can't unpack IEEE 754 special value "
2444 "on non-IEEE platform");
2445 return -1;
2446 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* Third byte */
2449 f |= *p << 8;
2450 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* Fourth byte */
2453 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* XXX This sadly ignores Inf/NaN issues */
2458 if (e == 0)
2459 e = -126;
2460 else {
2461 x += 1.0;
2462 e -= 127;
2463 }
2464 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 if (sign)
2467 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 return x;
2470 }
2471 else {
2472 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if ((float_format == ieee_little_endian_format && !le)
2475 || (float_format == ieee_big_endian_format && le)) {
2476 char buf[4];
2477 char *d = &buf[3];
2478 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 for (i = 0; i < 4; i++) {
2481 *d-- = *p++;
2482 }
2483 memcpy(&x, buf, 4);
2484 }
2485 else {
2486 memcpy(&x, p, 4);
2487 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 return x;
2490 }
Tim Peters9905b942003-03-20 20:53:32 +00002491}
2492
2493double
2494_PyFloat_Unpack8(const unsigned char *p, int le)
2495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (double_format == unknown_format) {
2497 unsigned char sign;
2498 int e;
2499 unsigned int fhi, flo;
2500 double x;
2501 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 if (le) {
2504 p += 7;
2505 incr = -1;
2506 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* First byte */
2509 sign = (*p >> 7) & 1;
2510 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* Second byte */
2515 e |= (*p >> 4) & 0xF;
2516 fhi = (*p & 0xF) << 24;
2517 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (e == 2047) {
2520 PyErr_SetString(
2521 PyExc_ValueError,
2522 "can't unpack IEEE 754 special value "
2523 "on non-IEEE platform");
2524 return -1.0;
2525 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* Third byte */
2528 fhi |= *p << 16;
2529 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 /* Fourth byte */
2532 fhi |= *p << 8;
2533 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 /* Fifth byte */
2536 fhi |= *p;
2537 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 /* Sixth byte */
2540 flo = *p << 16;
2541 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /* Seventh byte */
2544 flo |= *p << 8;
2545 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 /* Eighth byte */
2548 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2551 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 if (e == 0)
2554 e = -1022;
2555 else {
2556 x += 1.0;
2557 e -= 1023;
2558 }
2559 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 if (sign)
2562 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 return x;
2565 }
2566 else {
2567 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 if ((double_format == ieee_little_endian_format && !le)
2570 || (double_format == ieee_big_endian_format && le)) {
2571 char buf[8];
2572 char *d = &buf[7];
2573 int i;
2574
2575 for (i = 0; i < 8; i++) {
2576 *d-- = *p++;
2577 }
2578 memcpy(&x, buf, 8);
2579 }
2580 else {
2581 memcpy(&x, p, 8);
2582 }
2583
2584 return x;
2585 }
Tim Peters9905b942003-03-20 20:53:32 +00002586}