blob: 80bf71efd21a4e424d8da48a54f969f777f6f99d [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;
1228 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1229 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 */
1291 x = _Py_parse_inf_or_nan(s, &coeff_end);
1292 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) {
Serhiy Storchaka5787ef62016-05-12 10:32:30 +03001442 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;
1572 /* If it's a string, but not a string subclass, use
1573 PyFloat_FromString. */
1574 if (PyUnicode_CheckExact(x))
1575 return PyFloat_FromString(x);
1576 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577}
1578
Guido van Rossumbef14172001-08-29 15:47:46 +00001579/* Wimpy, slow approach to tp_new calls for subtypes of float:
1580 first create a regular float from whatever arguments we got,
1581 then allocate a subtype instance and initialize its ob_fval
1582 from the regular float. The regular float is then thrown away.
1583*/
1584static PyObject *
1585float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 assert(PyType_IsSubtype(type, &PyFloat_Type));
1590 tmp = float_new(&PyFloat_Type, args, kwds);
1591 if (tmp == NULL)
1592 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001593 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 newobj = type->tp_alloc(type, 0);
1595 if (newobj == NULL) {
1596 Py_DECREF(tmp);
1597 return NULL;
1598 }
1599 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1600 Py_DECREF(tmp);
1601 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001602}
1603
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001604static PyObject *
1605float_getnewargs(PyFloatObject *v)
1606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001608}
1609
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001610/* this is for the benefit of the pack/unpack routines below */
1611
1612typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614} float_format_type;
1615
1616static float_format_type double_format, float_format;
1617static float_format_type detected_double_format, detected_float_format;
1618
1619static PyObject *
1620float_getformat(PyTypeObject *v, PyObject* arg)
1621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 char* s;
1623 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (!PyUnicode_Check(arg)) {
1626 PyErr_Format(PyExc_TypeError,
1627 "__getformat__() argument must be string, not %.500s",
1628 Py_TYPE(arg)->tp_name);
1629 return NULL;
1630 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001631 s = PyUnicode_AsUTF8(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 if (s == NULL)
1633 return NULL;
1634 if (strcmp(s, "double") == 0) {
1635 r = double_format;
1636 }
1637 else if (strcmp(s, "float") == 0) {
1638 r = float_format;
1639 }
1640 else {
1641 PyErr_SetString(PyExc_ValueError,
1642 "__getformat__() argument 1 must be "
1643 "'double' or 'float'");
1644 return NULL;
1645 }
1646
1647 switch (r) {
1648 case unknown_format:
1649 return PyUnicode_FromString("unknown");
1650 case ieee_little_endian_format:
1651 return PyUnicode_FromString("IEEE, little-endian");
1652 case ieee_big_endian_format:
1653 return PyUnicode_FromString("IEEE, big-endian");
1654 default:
1655 Py_FatalError("insane float_format or double_format");
1656 return NULL;
1657 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001658}
1659
1660PyDoc_STRVAR(float_getformat_doc,
1661"float.__getformat__(typestr) -> string\n"
1662"\n"
1663"You probably don't want to use this function. It exists mainly to be\n"
1664"used in Python's test suite.\n"
1665"\n"
1666"typestr must be 'double' or 'float'. This function returns whichever of\n"
1667"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1668"format of floating point numbers used by the C type named by typestr.");
1669
1670static PyObject *
1671float_setformat(PyTypeObject *v, PyObject* args)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 char* typestr;
1674 char* format;
1675 float_format_type f;
1676 float_format_type detected;
1677 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1680 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 if (strcmp(typestr, "double") == 0) {
1683 p = &double_format;
1684 detected = detected_double_format;
1685 }
1686 else if (strcmp(typestr, "float") == 0) {
1687 p = &float_format;
1688 detected = detected_float_format;
1689 }
1690 else {
1691 PyErr_SetString(PyExc_ValueError,
1692 "__setformat__() argument 1 must "
1693 "be 'double' or 'float'");
1694 return NULL;
1695 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 if (strcmp(format, "unknown") == 0) {
1698 f = unknown_format;
1699 }
1700 else if (strcmp(format, "IEEE, little-endian") == 0) {
1701 f = ieee_little_endian_format;
1702 }
1703 else if (strcmp(format, "IEEE, big-endian") == 0) {
1704 f = ieee_big_endian_format;
1705 }
1706 else {
1707 PyErr_SetString(PyExc_ValueError,
1708 "__setformat__() argument 2 must be "
1709 "'unknown', 'IEEE, little-endian' or "
1710 "'IEEE, big-endian'");
1711 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 if (f != unknown_format && f != detected) {
1716 PyErr_Format(PyExc_ValueError,
1717 "can only set %s format to 'unknown' or the "
1718 "detected platform value", typestr);
1719 return NULL;
1720 }
1721
1722 *p = f;
1723 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724}
1725
1726PyDoc_STRVAR(float_setformat_doc,
1727"float.__setformat__(typestr, fmt) -> None\n"
1728"\n"
1729"You probably don't want to use this function. It exists mainly to be\n"
1730"used in Python's test suite.\n"
1731"\n"
1732"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1733"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1734"one of the latter two if it appears to match the underlying C reality.\n"
1735"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001736"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001737"This affects how floats are converted to and from binary strings.");
1738
Guido van Rossumb43daf72007-08-01 18:08:08 +00001739static PyObject *
1740float_getzero(PyObject *v, void *closure)
1741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001743}
1744
Eric Smith8c663262007-08-25 02:26:07 +00001745static PyObject *
1746float__format__(PyObject *self, PyObject *args)
1747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001749 _PyUnicodeWriter writer;
1750 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1753 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001754
Victor Stinner8f674cc2013-04-17 23:02:17 +02001755 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001756 ret = _PyFloat_FormatAdvancedWriter(
1757 &writer,
1758 self,
1759 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1760 if (ret == -1) {
1761 _PyUnicodeWriter_Dealloc(&writer);
1762 return NULL;
1763 }
1764 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001765}
1766
1767PyDoc_STRVAR(float__format__doc,
1768"float.__format__(format_spec) -> string\n"
1769"\n"
1770"Formats the float according to format_spec.");
1771
1772
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001773static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001775 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001777 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001779 "Return the Integral closest to x, rounding half toward even.\n"
1780 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1782 float_as_integer_ratio_doc},
1783 {"fromhex", (PyCFunction)float_fromhex,
1784 METH_O|METH_CLASS, float_fromhex_doc},
1785 {"hex", (PyCFunction)float_hex,
1786 METH_NOARGS, float_hex_doc},
1787 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001788 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001789#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001791 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001793 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001795 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001796#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1798 {"__getformat__", (PyCFunction)float_getformat,
1799 METH_O|METH_CLASS, float_getformat_doc},
1800 {"__setformat__", (PyCFunction)float_setformat,
1801 METH_VARARGS|METH_CLASS, float_setformat_doc},
1802 {"__format__", (PyCFunction)float__format__,
1803 METH_VARARGS, float__format__doc},
1804 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001805};
1806
Guido van Rossumb43daf72007-08-01 18:08:08 +00001807static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001809 (getter)float_float, (setter)NULL,
1810 "the real part of a complex number",
1811 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001813 (getter)float_getzero, (setter)NULL,
1814 "the imaginary part of a complex number",
1815 NULL},
1816 {NULL} /* Sentinel */
1817};
1818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001819PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820"float(x) -> floating point number\n\
1821\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001822Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823
1824
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001825static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 float_add, /*nb_add*/
1827 float_sub, /*nb_subtract*/
1828 float_mul, /*nb_multiply*/
1829 float_rem, /*nb_remainder*/
1830 float_divmod, /*nb_divmod*/
1831 float_pow, /*nb_power*/
1832 (unaryfunc)float_neg, /*nb_negative*/
1833 (unaryfunc)float_float, /*nb_positive*/
1834 (unaryfunc)float_abs, /*nb_absolute*/
1835 (inquiry)float_bool, /*nb_bool*/
1836 0, /*nb_invert*/
1837 0, /*nb_lshift*/
1838 0, /*nb_rshift*/
1839 0, /*nb_and*/
1840 0, /*nb_xor*/
1841 0, /*nb_or*/
1842 float_trunc, /*nb_int*/
1843 0, /*nb_reserved*/
1844 float_float, /*nb_float*/
1845 0, /* nb_inplace_add */
1846 0, /* nb_inplace_subtract */
1847 0, /* nb_inplace_multiply */
1848 0, /* nb_inplace_remainder */
1849 0, /* nb_inplace_power */
1850 0, /* nb_inplace_lshift */
1851 0, /* nb_inplace_rshift */
1852 0, /* nb_inplace_and */
1853 0, /* nb_inplace_xor */
1854 0, /* nb_inplace_or */
1855 float_floor_div, /* nb_floor_divide */
1856 float_div, /* nb_true_divide */
1857 0, /* nb_inplace_floor_divide */
1858 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001859};
1860
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001861PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1863 "float",
1864 sizeof(PyFloatObject),
1865 0,
1866 (destructor)float_dealloc, /* tp_dealloc */
1867 0, /* tp_print */
1868 0, /* tp_getattr */
1869 0, /* tp_setattr */
1870 0, /* tp_reserved */
1871 (reprfunc)float_repr, /* tp_repr */
1872 &float_as_number, /* tp_as_number */
1873 0, /* tp_as_sequence */
1874 0, /* tp_as_mapping */
1875 (hashfunc)float_hash, /* tp_hash */
1876 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001877 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyObject_GenericGetAttr, /* tp_getattro */
1879 0, /* tp_setattro */
1880 0, /* tp_as_buffer */
1881 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1882 float_doc, /* tp_doc */
1883 0, /* tp_traverse */
1884 0, /* tp_clear */
1885 float_richcompare, /* tp_richcompare */
1886 0, /* tp_weaklistoffset */
1887 0, /* tp_iter */
1888 0, /* tp_iternext */
1889 float_methods, /* tp_methods */
1890 0, /* tp_members */
1891 float_getset, /* tp_getset */
1892 0, /* tp_base */
1893 0, /* tp_dict */
1894 0, /* tp_descr_get */
1895 0, /* tp_descr_set */
1896 0, /* tp_dictoffset */
1897 0, /* tp_init */
1898 0, /* tp_alloc */
1899 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001900};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001901
Victor Stinner1c8f0592013-07-22 22:24:54 +02001902int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001903_PyFloat_Init(void)
1904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* We attempt to determine if this machine is using IEEE
1906 floating point formats by peering at the bits of some
1907 carefully chosen values. If it looks like we are on an
1908 IEEE platform, the float packing/unpacking routines can
1909 just copy bits, if not they resort to arithmetic & shifts
1910 and masks. The shifts & masks approach works on all finite
1911 values, but what happens to infinities, NaNs and signed
1912 zeroes on packing is an accident, and attempting to unpack
1913 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Note that if we're on some whacked-out platform which uses
1916 IEEE formats but isn't strictly little-endian or big-
1917 endian, we will fall back to the portable shifts & masks
1918 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919
1920#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 {
1922 double x = 9006104071832581.0;
1923 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1924 detected_double_format = ieee_big_endian_format;
1925 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1926 detected_double_format = ieee_little_endian_format;
1927 else
1928 detected_double_format = unknown_format;
1929 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001932#endif
1933
1934#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 {
1936 float y = 16711938.0;
1937 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1938 detected_float_format = ieee_big_endian_format;
1939 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1940 detected_float_format = ieee_little_endian_format;
1941 else
1942 detected_float_format = unknown_format;
1943 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001944#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001946#endif
1947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 double_format = detected_double_format;
1949 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001952 if (FloatInfoType.tp_name == NULL) {
1953 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1954 return 0;
1955 }
1956 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001957}
1958
Georg Brandl2ee470f2008-07-16 12:55:28 +00001959int
1960PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001961{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001962 PyFloatObject *f = free_list, *next;
1963 int i = numfree;
1964 while (f) {
1965 next = (PyFloatObject*) Py_TYPE(f);
1966 PyObject_FREE(f);
1967 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001969 free_list = NULL;
1970 numfree = 0;
1971 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001972}
1973
1974void
1975PyFloat_Fini(void)
1976{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001977 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001978}
Tim Peters9905b942003-03-20 20:53:32 +00001979
David Malcolm49526f42012-06-22 14:55:41 -04001980/* Print summary info about the state of the optimized allocator */
1981void
1982_PyFloat_DebugMallocStats(FILE *out)
1983{
1984 _PyDebugAllocatorStats(out,
1985 "free PyFloatObject",
1986 numfree, sizeof(PyFloatObject));
1987}
1988
1989
Tim Peters9905b942003-03-20 20:53:32 +00001990/*----------------------------------------------------------------------------
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001991 * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h.
1992 * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in:
1993 * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c
1994 * We use:
1995 * bits = (unsigned short)f; Note the truncation
1996 * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) {
1997 * bits++;
1998 * }
Tim Peters9905b942003-03-20 20:53:32 +00001999 */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002000
2001int
2002_PyFloat_Pack2(double x, unsigned char *p, int le)
2003{
2004 unsigned char sign;
2005 int e;
2006 double f;
2007 unsigned short bits;
2008 int incr = 1;
2009
2010 if (x == 0.0) {
2011 sign = (copysign(1.0, x) == -1.0);
2012 e = 0;
2013 bits = 0;
2014 }
2015 else if (Py_IS_INFINITY(x)) {
2016 sign = (x < 0.0);
2017 e = 0x1f;
2018 bits = 0;
2019 }
2020 else if (Py_IS_NAN(x)) {
2021 /* There are 2046 distinct half-precision NaNs (1022 signaling and
2022 1024 quiet), but there are only two quiet NaNs that don't arise by
2023 quieting a signaling NaN; we get those by setting the topmost bit
2024 of the fraction field and clearing all other fraction bits. We
2025 choose the one with the appropriate sign. */
2026 sign = (copysign(1.0, x) == -1.0);
2027 e = 0x1f;
2028 bits = 512;
2029 }
2030 else {
2031 sign = (x < 0.0);
2032 if (sign) {
2033 x = -x;
2034 }
2035
2036 f = frexp(x, &e);
2037 if (f < 0.5 || f >= 1.0) {
2038 PyErr_SetString(PyExc_SystemError,
2039 "frexp() result out of range");
2040 return -1;
2041 }
2042
2043 /* Normalize f to be in the range [1.0, 2.0) */
2044 f *= 2.0;
2045 e--;
2046
2047 if (e >= 16) {
2048 goto Overflow;
2049 }
2050 else if (e < -25) {
2051 /* |x| < 2**-25. Underflow to zero. */
2052 f = 0.0;
2053 e = 0;
2054 }
2055 else if (e < -14) {
2056 /* |x| < 2**-14. Gradual underflow */
2057 f = ldexp(f, 14 + e);
2058 e = 0;
2059 }
2060 else /* if (!(e == 0 && f == 0.0)) */ {
2061 e += 15;
2062 f -= 1.0; /* Get rid of leading 1 */
2063 }
2064
2065 f *= 1024.0; /* 2**10 */
2066 /* Round to even */
2067 bits = (unsigned short)f; /* Note the truncation */
2068 assert(bits < 1024);
2069 assert(e < 31);
2070 if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) {
2071 ++bits;
2072 if (bits == 1024) {
2073 /* The carry propagated out of a string of 10 1 bits. */
2074 bits = 0;
2075 ++e;
2076 if (e == 31)
2077 goto Overflow;
2078 }
2079 }
2080 }
2081
2082 bits |= (e << 10) | (sign << 15);
2083
2084 /* Write out result. */
2085 if (le) {
2086 p += 1;
2087 incr = -1;
2088 }
2089
2090 /* First byte */
2091 *p = (unsigned char)((bits >> 8) & 0xFF);
2092 p += incr;
2093
2094 /* Second byte */
2095 *p = (unsigned char)(bits & 0xFF);
2096
2097 return 0;
2098
2099 Overflow:
2100 PyErr_SetString(PyExc_OverflowError,
2101 "float too large to pack with e format");
2102 return -1;
2103}
2104
Tim Peters9905b942003-03-20 20:53:32 +00002105int
2106_PyFloat_Pack4(double x, unsigned char *p, int le)
2107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (float_format == unknown_format) {
2109 unsigned char sign;
2110 int e;
2111 double f;
2112 unsigned int fbits;
2113 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (le) {
2116 p += 3;
2117 incr = -1;
2118 }
Tim Peters9905b942003-03-20 20:53:32 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 if (x < 0) {
2121 sign = 1;
2122 x = -x;
2123 }
2124 else
2125 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* Normalize f to be in the range [1.0, 2.0) */
2130 if (0.5 <= f && f < 1.0) {
2131 f *= 2.0;
2132 e--;
2133 }
2134 else if (f == 0.0)
2135 e = 0;
2136 else {
2137 PyErr_SetString(PyExc_SystemError,
2138 "frexp() result out of range");
2139 return -1;
2140 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (e >= 128)
2143 goto Overflow;
2144 else if (e < -126) {
2145 /* Gradual underflow */
2146 f = ldexp(f, 126 + e);
2147 e = 0;
2148 }
2149 else if (!(e == 0 && f == 0.0)) {
2150 e += 127;
2151 f -= 1.0; /* Get rid of leading 1 */
2152 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 f *= 8388608.0; /* 2**23 */
2155 fbits = (unsigned int)(f + 0.5); /* Round */
2156 assert(fbits <= 8388608);
2157 if (fbits >> 23) {
2158 /* The carry propagated out of a string of 23 1 bits. */
2159 fbits = 0;
2160 ++e;
2161 if (e >= 255)
2162 goto Overflow;
2163 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* First byte */
2166 *p = (sign << 7) | (e >> 1);
2167 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* Second byte */
2170 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2171 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 /* Third byte */
2174 *p = (fbits >> 8) & 0xFF;
2175 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* Fourth byte */
2178 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* Done */
2181 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
2184 else {
2185 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002186 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2190 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if ((float_format == ieee_little_endian_format && !le)
2193 || (float_format == ieee_big_endian_format && le)) {
2194 p += 3;
2195 incr = -1;
2196 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 for (i = 0; i < 4; i++) {
2199 *p = *s++;
2200 p += incr;
2201 }
2202 return 0;
2203 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002204 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 PyErr_SetString(PyExc_OverflowError,
2206 "float too large to pack with f format");
2207 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002208}
2209
2210int
2211_PyFloat_Pack8(double x, unsigned char *p, int le)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (double_format == unknown_format) {
2214 unsigned char sign;
2215 int e;
2216 double f;
2217 unsigned int fhi, flo;
2218 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (le) {
2221 p += 7;
2222 incr = -1;
2223 }
Tim Peters9905b942003-03-20 20:53:32 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (x < 0) {
2226 sign = 1;
2227 x = -x;
2228 }
2229 else
2230 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Normalize f to be in the range [1.0, 2.0) */
2235 if (0.5 <= f && f < 1.0) {
2236 f *= 2.0;
2237 e--;
2238 }
2239 else if (f == 0.0)
2240 e = 0;
2241 else {
2242 PyErr_SetString(PyExc_SystemError,
2243 "frexp() result out of range");
2244 return -1;
2245 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (e >= 1024)
2248 goto Overflow;
2249 else if (e < -1022) {
2250 /* Gradual underflow */
2251 f = ldexp(f, 1022 + e);
2252 e = 0;
2253 }
2254 else if (!(e == 0 && f == 0.0)) {
2255 e += 1023;
2256 f -= 1.0; /* Get rid of leading 1 */
2257 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2260 f *= 268435456.0; /* 2**28 */
2261 fhi = (unsigned int)f; /* Truncate */
2262 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 f -= (double)fhi;
2265 f *= 16777216.0; /* 2**24 */
2266 flo = (unsigned int)(f + 0.5); /* Round */
2267 assert(flo <= 16777216);
2268 if (flo >> 24) {
2269 /* The carry propagated out of a string of 24 1 bits. */
2270 flo = 0;
2271 ++fhi;
2272 if (fhi >> 28) {
2273 /* And it also progagated out of the next 28 bits. */
2274 fhi = 0;
2275 ++e;
2276 if (e >= 2047)
2277 goto Overflow;
2278 }
2279 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 /* First byte */
2282 *p = (sign << 7) | (e >> 4);
2283 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* Second byte */
2286 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2287 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* Third byte */
2290 *p = (fhi >> 16) & 0xFF;
2291 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 /* Fourth byte */
2294 *p = (fhi >> 8) & 0xFF;
2295 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Fifth byte */
2298 *p = fhi & 0xFF;
2299 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Sixth byte */
2302 *p = (flo >> 16) & 0xFF;
2303 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Seventh byte */
2306 *p = (flo >> 8) & 0xFF;
2307 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Eighth byte */
2310 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002311 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Done */
2314 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 Overflow:
2317 PyErr_SetString(PyExc_OverflowError,
2318 "float too large to pack with d format");
2319 return -1;
2320 }
2321 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002322 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 if ((double_format == ieee_little_endian_format && !le)
2326 || (double_format == ieee_big_endian_format && le)) {
2327 p += 7;
2328 incr = -1;
2329 }
2330
2331 for (i = 0; i < 8; i++) {
2332 *p = *s++;
2333 p += incr;
2334 }
2335 return 0;
2336 }
Tim Peters9905b942003-03-20 20:53:32 +00002337}
2338
2339double
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002340_PyFloat_Unpack2(const unsigned char *p, int le)
2341{
2342 unsigned char sign;
2343 int e;
2344 unsigned int f;
2345 double x;
2346 int incr = 1;
2347
2348 if (le) {
2349 p += 1;
2350 incr = -1;
2351 }
2352
2353 /* First byte */
2354 sign = (*p >> 7) & 1;
2355 e = (*p & 0x7C) >> 2;
2356 f = (*p & 0x03) << 8;
2357 p += incr;
2358
2359 /* Second byte */
2360 f |= *p;
2361
2362 if (e == 0x1f) {
2363#ifdef PY_NO_SHORT_FLOAT_REPR
2364 if (f == 0) {
2365 /* Infinity */
2366 return sign ? -Py_HUGE_VAL : Py_HUGE_VAL;
2367 }
2368 else {
2369 /* NaN */
2370#ifdef Py_NAN
2371 return sign ? -Py_NAN : Py_NAN;
2372#else
2373 PyErr_SetString(
2374 PyExc_ValueError,
2375 "can't unpack IEEE 754 NaN "
2376 "on platform that does not support NaNs");
2377 return -1;
2378#endif /* #ifdef Py_NAN */
2379 }
2380#else
2381 if (f == 0) {
2382 /* Infinity */
2383 return _Py_dg_infinity(sign);
2384 }
2385 else {
2386 /* NaN */
2387 return _Py_dg_stdnan(sign);
2388 }
2389#endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */
2390 }
2391
2392 x = (double)f / 1024.0;
2393
2394 if (e == 0) {
2395 e = -14;
2396 }
2397 else {
2398 x += 1.0;
2399 e -= 15;
2400 }
2401 x = ldexp(x, e);
2402
2403 if (sign)
2404 x = -x;
2405
2406 return x;
2407}
2408
2409double
Tim Peters9905b942003-03-20 20:53:32 +00002410_PyFloat_Unpack4(const unsigned char *p, int le)
2411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 if (float_format == unknown_format) {
2413 unsigned char sign;
2414 int e;
2415 unsigned int f;
2416 double x;
2417 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (le) {
2420 p += 3;
2421 incr = -1;
2422 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 /* First byte */
2425 sign = (*p >> 7) & 1;
2426 e = (*p & 0x7F) << 1;
2427 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* Second byte */
2430 e |= (*p >> 7) & 1;
2431 f = (*p & 0x7F) << 16;
2432 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (e == 255) {
2435 PyErr_SetString(
2436 PyExc_ValueError,
2437 "can't unpack IEEE 754 special value "
2438 "on non-IEEE platform");
2439 return -1;
2440 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* Third byte */
2443 f |= *p << 8;
2444 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* Fourth byte */
2447 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* XXX This sadly ignores Inf/NaN issues */
2452 if (e == 0)
2453 e = -126;
2454 else {
2455 x += 1.0;
2456 e -= 127;
2457 }
2458 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (sign)
2461 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return x;
2464 }
2465 else {
2466 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if ((float_format == ieee_little_endian_format && !le)
2469 || (float_format == ieee_big_endian_format && le)) {
2470 char buf[4];
2471 char *d = &buf[3];
2472 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 for (i = 0; i < 4; i++) {
2475 *d-- = *p++;
2476 }
2477 memcpy(&x, buf, 4);
2478 }
2479 else {
2480 memcpy(&x, p, 4);
2481 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 return x;
2484 }
Tim Peters9905b942003-03-20 20:53:32 +00002485}
2486
2487double
2488_PyFloat_Unpack8(const unsigned char *p, int le)
2489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 if (double_format == unknown_format) {
2491 unsigned char sign;
2492 int e;
2493 unsigned int fhi, flo;
2494 double x;
2495 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 if (le) {
2498 p += 7;
2499 incr = -1;
2500 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* First byte */
2503 sign = (*p >> 7) & 1;
2504 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* Second byte */
2509 e |= (*p >> 4) & 0xF;
2510 fhi = (*p & 0xF) << 24;
2511 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (e == 2047) {
2514 PyErr_SetString(
2515 PyExc_ValueError,
2516 "can't unpack IEEE 754 special value "
2517 "on non-IEEE platform");
2518 return -1.0;
2519 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* Third byte */
2522 fhi |= *p << 16;
2523 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* Fourth byte */
2526 fhi |= *p << 8;
2527 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 /* Fifth byte */
2530 fhi |= *p;
2531 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* Sixth byte */
2534 flo = *p << 16;
2535 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 /* Seventh byte */
2538 flo |= *p << 8;
2539 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* Eighth byte */
2542 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2545 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (e == 0)
2548 e = -1022;
2549 else {
2550 x += 1.0;
2551 e -= 1023;
2552 }
2553 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (sign)
2556 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return x;
2559 }
2560 else {
2561 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 if ((double_format == ieee_little_endian_format && !le)
2564 || (double_format == ieee_big_endian_format && le)) {
2565 char buf[8];
2566 char *d = &buf[7];
2567 int i;
2568
2569 for (i = 0; i < 8; i++) {
2570 *d-- = *p++;
2571 }
2572 memcpy(&x, buf, 8);
2573 }
2574 else {
2575 memcpy(&x, p, 8);
2576 }
2577
2578 return x;
2579 }
Tim Peters9905b942003-03-20 20:53:32 +00002580}