blob: da600f4aa829d2059cf8b2b84380612c01613108 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Guido van Rossum6923e131990-11-02 17:50:43 +000012
Mark Dickinsond19052c2010-06-27 18:19:09 +000013/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000014 free_list is a singly-linked list of available PyFloatObjects, linked
15 via abuse of their ob_type members.
16*/
17
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000018#ifndef PyFloat_MAXFREELIST
19#define PyFloat_MAXFREELIST 100
20#endif
21static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000022static PyFloatObject *free_list = NULL;
23
Christian Heimes93852662007-12-01 12:22:32 +000024double
25PyFloat_GetMax(void)
26{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000028}
29
30double
31PyFloat_GetMin(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
Christian Heimesd32ed6f2008-01-14 18:49:24 +000036static PyTypeObject FloatInfoType;
37
38PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000039"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000040\n\
41A structseq holding information about the float type. It contains low level\n\
42information about the precision and internal representation. Please study\n\
43your system's :file:`float.h` for more information.");
44
45static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 {"max", "DBL_MAX -- maximum representable finite float"},
47 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
48 "is representable"},
49 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
50 "is representable"},
51 {"min", "DBL_MIN -- Minimum positive normalizer float"},
52 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
53 "is a normalized float"},
54 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
55 "a normalized"},
56 {"dig", "DBL_DIG -- digits"},
57 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
58 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
59 "representable float"},
60 {"radix", "FLT_RADIX -- radix of exponent"},
61 {"rounds", "FLT_ROUNDS -- addition rounds"},
62 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000063};
64
65static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 "sys.float_info", /* name */
67 floatinfo__doc__, /* doc */
68 floatinfo_fields, /* fields */
69 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000070};
71
Christian Heimes93852662007-12-01 12:22:32 +000072PyObject *
73PyFloat_GetInfo(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject* floatinfo;
76 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 floatinfo = PyStructSequence_New(&FloatInfoType);
79 if (floatinfo == NULL) {
80 return NULL;
81 }
Christian Heimes93852662007-12-01 12:22:32 +000082
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000085#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 SetDblFlag(DBL_MAX);
89 SetIntFlag(DBL_MAX_EXP);
90 SetIntFlag(DBL_MAX_10_EXP);
91 SetDblFlag(DBL_MIN);
92 SetIntFlag(DBL_MIN_EXP);
93 SetIntFlag(DBL_MIN_10_EXP);
94 SetIntFlag(DBL_DIG);
95 SetIntFlag(DBL_MANT_DIG);
96 SetDblFlag(DBL_EPSILON);
97 SetIntFlag(FLT_RADIX);
98 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +000099#undef SetIntFlag
100#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101
102 if (PyErr_Occurred()) {
103 Py_CLEAR(floatinfo);
104 return NULL;
105 }
106 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000107}
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200112 PyFloatObject *op = free_list;
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000113 if (op != NULL) {
114 free_list = (PyFloatObject *) Py_TYPE(op);
115 numfree--;
116 } else {
117 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
118 if (!op)
119 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
121 /* Inline PyObject_New */
Christian Heimesd3afe782013-12-04 09:27:47 +0100122 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 op->ob_fval = fval;
124 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125}
126
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000127PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000128PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 const char *s, *last, *end;
131 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000132 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_ssize_t len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200134 Py_buffer view = {NULL, NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200138 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000140 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200141 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000142 if (s == NULL) {
143 Py_DECREF(s_buffer);
144 return NULL;
145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000147 else if (PyBytes_Check(v)) {
148 s = PyBytes_AS_STRING(v);
149 len = PyBytes_GET_SIZE(v);
150 }
151 else if (PyByteArray_Check(v)) {
152 s = PyByteArray_AS_STRING(v);
153 len = PyByteArray_GET_SIZE(v);
154 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200155 else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
156 s = (const char *)view.buf;
157 len = view.len;
Martin Pantereeb896c2015-11-07 02:32:21 +0000158 /* Copy to NUL-terminated buffer. */
159 s_buffer = PyBytes_FromStringAndSize(s, len);
160 if (s_buffer == NULL) {
161 PyBuffer_Release(&view);
162 return NULL;
163 }
164 s = PyBytes_AS_STRING(s_buffer);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200165 }
166 else {
Ezio Melottia5b95992013-11-07 19:18:34 +0200167 PyErr_Format(PyExc_TypeError,
168 "float() argument must be a string or a number, not '%.200s'",
169 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return NULL;
171 }
172 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000173 /* strip space */
174 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000176 while (s < last - 1 && Py_ISSPACE(last[-1]))
177 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* We don't care about overflow or underflow. If the platform
179 * supports them, infinities and signed zeroes (on underflow) are
180 * fine. */
181 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000182 if (end != last) {
183 PyErr_Format(PyExc_ValueError,
184 "could not convert string to float: "
185 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 result = NULL;
187 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000188 else if (x == -1.0 && PyErr_Occurred())
189 result = NULL;
190 else
191 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000192
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200193 PyBuffer_Release(&view);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000194 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196}
197
Guido van Rossum234f9421993-06-17 12:35:49 +0000198static void
Fred Drakefd99de62000-07-09 05:02:18 +0000199float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000202 if (numfree >= PyFloat_MAXFREELIST) {
203 PyObject_FREE(op);
204 return;
205 }
206 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_TYPE(op) = (struct _typeobject *)free_list;
208 free_list = op;
209 }
210 else
211 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000212}
213
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214double
Fred Drakefd99de62000-07-09 05:02:18 +0000215PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyNumberMethods *nb;
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300218 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (op == NULL) {
222 PyErr_BadArgument();
223 return -1;
224 }
Tim Petersd2364e82001-11-01 20:09:42 +0000225
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300226 if (PyFloat_Check(op)) {
227 return PyFloat_AS_DOUBLE(op);
228 }
229
230 nb = Py_TYPE(op)->tp_as_number;
231 if (nb == NULL || nb->nb_float == NULL) {
232 PyErr_Format(PyExc_TypeError, "must be real number, not %.50s",
233 op->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 return -1;
235 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000236
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300237 res = (*nb->nb_float) (op);
238 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 return -1;
240 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300241 if (!PyFloat_CheckExact(res)) {
242 if (!PyFloat_Check(res)) {
243 PyErr_Format(PyExc_TypeError,
244 "%.50s.__float__ returned non-float (type %.50s)",
245 op->ob_type->tp_name, res->ob_type->tp_name);
246 Py_DECREF(res);
247 return -1;
248 }
249 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
250 "%.50s.__float__ returned non-float (type %.50s). "
251 "The ability to return an instance of a strict subclass of float "
252 "is deprecated, and may be removed in a future version of Python.",
253 op->ob_type->tp_name, res->ob_type->tp_name)) {
254 Py_DECREF(res);
255 return -1;
256 }
257 }
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Serhiy Storchaka16931c32016-06-03 21:42:55 +0300259 val = PyFloat_AS_DOUBLE(res);
260 Py_DECREF(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262}
263
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000265 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000266 set to NULL, and the function invoking this macro returns NULL. If
Serhiy Storchaka95949422013-08-27 19:40:23 +0300267 obj is not of float or int type, Py_NotImplemented is incref'ed,
Tim Peters77d8a4f2001-12-11 20:31:34 +0000268 stored in obj, and returned from the function invoking this macro.
269*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270#define CONVERT_TO_DOUBLE(obj, dbl) \
271 if (PyFloat_Check(obj)) \
272 dbl = PyFloat_AS_DOUBLE(obj); \
273 else if (convert_to_double(&(obj), &(dbl)) < 0) \
274 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000275
Eric Smith0923d1d2009-04-16 20:16:10 +0000276/* Methods */
277
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000279convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000280{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200281 PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (PyLong_Check(obj)) {
284 *dbl = PyLong_AsDouble(obj);
285 if (*dbl == -1.0 && PyErr_Occurred()) {
286 *v = NULL;
287 return -1;
288 }
289 }
290 else {
291 Py_INCREF(Py_NotImplemented);
292 *v = Py_NotImplemented;
293 return -1;
294 }
295 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000296}
297
Eric Smith0923d1d2009-04-16 20:16:10 +0000298static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000299float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000300{
301 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200302 char *buf;
303
304 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
305 'r', 0,
306 Py_DTSF_ADD_DOT_0,
307 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000308 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000309 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200310 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000311 PyMem_Free(buf);
312 return result;
313}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000314
Tim Peters307fa782004-09-23 08:06:40 +0000315/* Comparison is pretty much a nightmare. When comparing float to float,
316 * we do it as straightforwardly (and long-windedly) as conceivable, so
317 * that, e.g., Python x == y delivers the same result as the platform
318 * C x == y when x and/or y is a NaN.
319 * When mixing float with an integer type, there's no good *uniform* approach.
320 * Converting the double to an integer obviously doesn't work, since we
321 * may lose info from fractional bits. Converting the integer to a double
Serhiy Storchaka95949422013-08-27 19:40:23 +0300322 * also has two failure modes: (1) an int may trigger overflow (too
Tim Peters307fa782004-09-23 08:06:40 +0000323 * 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 +0200324 * 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 +0000325 * 63 bits of precision, but a C double probably has only 53), and then
326 * we can falsely claim equality when low-order integer bits are lost by
327 * coercion to double. So this part is painful too.
328 */
329
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000330static PyObject*
331float_richcompare(PyObject *v, PyObject *w, int op)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 double i, j;
334 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 assert(PyFloat_Check(v));
337 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* Switch on the type of w. Set i and j to doubles to be compared,
340 * and op to the richcomp to use.
341 */
342 if (PyFloat_Check(w))
343 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 else if (!Py_IS_FINITE(i)) {
346 if (PyLong_Check(w))
347 /* If i is an infinity, its magnitude exceeds any
348 * finite integer, so it doesn't matter which int we
349 * compare i with. If i is a NaN, similarly.
350 */
351 j = 0.0;
352 else
353 goto Unimplemented;
354 }
Tim Peters307fa782004-09-23 08:06:40 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 else if (PyLong_Check(w)) {
357 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
358 int wsign = _PyLong_Sign(w);
359 size_t nbits;
360 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (vsign != wsign) {
363 /* Magnitudes are irrelevant -- the signs alone
364 * determine the outcome.
365 */
366 i = (double)vsign;
367 j = (double)wsign;
368 goto Compare;
369 }
370 /* The signs are the same. */
371 /* Convert w to a double if it fits. In particular, 0 fits. */
372 nbits = _PyLong_NumBits(w);
373 if (nbits == (size_t)-1 && PyErr_Occurred()) {
374 /* This long is so large that size_t isn't big enough
375 * to hold the # of bits. Replace with little doubles
376 * that give the same outcome -- w is so large that
377 * its magnitude must exceed the magnitude of any
378 * finite float.
379 */
380 PyErr_Clear();
381 i = (double)vsign;
382 assert(wsign != 0);
383 j = wsign * 2.0;
384 goto Compare;
385 }
386 if (nbits <= 48) {
387 j = PyLong_AsDouble(w);
388 /* It's impossible that <= 48 bits overflowed. */
389 assert(j != -1.0 || ! PyErr_Occurred());
390 goto Compare;
391 }
392 assert(wsign != 0); /* else nbits was 0 */
393 assert(vsign != 0); /* if vsign were 0, then since wsign is
394 * not 0, we would have taken the
395 * vsign != wsign branch at the start */
396 /* We want to work with non-negative numbers. */
397 if (vsign < 0) {
398 /* "Multiply both sides" by -1; this also swaps the
399 * comparator.
400 */
401 i = -i;
402 op = _Py_SwappedOp[op];
403 }
404 assert(i > 0.0);
405 (void) frexp(i, &exponent);
406 /* exponent is the # of bits in v before the radix point;
407 * we know that nbits (the # of bits in w) > 48 at this point
408 */
409 if (exponent < 0 || (size_t)exponent < nbits) {
410 i = 1.0;
411 j = 2.0;
412 goto Compare;
413 }
414 if ((size_t)exponent > nbits) {
415 i = 2.0;
416 j = 1.0;
417 goto Compare;
418 }
419 /* v and w have the same number of bits before the radix
Serhiy Storchaka95949422013-08-27 19:40:23 +0300420 * point. Construct two ints that have the same comparison
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 * outcome.
422 */
423 {
424 double fracpart;
425 double intpart;
426 PyObject *result = NULL;
427 PyObject *one = NULL;
428 PyObject *vv = NULL;
429 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (wsign < 0) {
432 ww = PyNumber_Negative(w);
433 if (ww == NULL)
434 goto Error;
435 }
436 else
437 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 fracpart = modf(i, &intpart);
440 vv = PyLong_FromDouble(intpart);
441 if (vv == NULL)
442 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (fracpart != 0.0) {
445 /* Shift left, and or a 1 bit into vv
446 * to represent the lost fraction.
447 */
448 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 one = PyLong_FromLong(1);
451 if (one == NULL)
452 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 temp = PyNumber_Lshift(ww, one);
455 if (temp == NULL)
456 goto Error;
457 Py_DECREF(ww);
458 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 temp = PyNumber_Lshift(vv, one);
461 if (temp == NULL)
462 goto Error;
463 Py_DECREF(vv);
464 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 temp = PyNumber_Or(vv, one);
467 if (temp == NULL)
468 goto Error;
469 Py_DECREF(vv);
470 vv = temp;
471 }
Tim Peters307fa782004-09-23 08:06:40 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 r = PyObject_RichCompareBool(vv, ww, op);
474 if (r < 0)
475 goto Error;
476 result = PyBool_FromLong(r);
477 Error:
478 Py_XDECREF(vv);
479 Py_XDECREF(ww);
480 Py_XDECREF(one);
481 return result;
482 }
483 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000484
Serhiy Storchaka95949422013-08-27 19:40:23 +0300485 else /* w isn't float or int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000487
488 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyFPE_START_PROTECT("richcompare", return NULL)
490 switch (op) {
491 case Py_EQ:
492 r = i == j;
493 break;
494 case Py_NE:
495 r = i != j;
496 break;
497 case Py_LE:
498 r = i <= j;
499 break;
500 case Py_GE:
501 r = i >= j;
502 break;
503 case Py_LT:
504 r = i < j;
505 break;
506 case Py_GT:
507 r = i > j;
508 break;
509 }
510 PyFPE_END_PROTECT(r)
511 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000512
513 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500514 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000515}
516
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000517static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000518float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000521}
522
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000524float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 double a,b;
527 CONVERT_TO_DOUBLE(v, a);
528 CONVERT_TO_DOUBLE(w, b);
529 PyFPE_START_PROTECT("add", return 0)
530 a = a + b;
531 PyFPE_END_PROTECT(a)
532 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533}
534
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000536float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 double a,b;
539 CONVERT_TO_DOUBLE(v, a);
540 CONVERT_TO_DOUBLE(w, b);
541 PyFPE_START_PROTECT("subtract", return 0)
542 a = a - b;
543 PyFPE_END_PROTECT(a)
544 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545}
546
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000548float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 double a,b;
551 CONVERT_TO_DOUBLE(v, a);
552 CONVERT_TO_DOUBLE(w, b);
553 PyFPE_START_PROTECT("multiply", return 0)
554 a = a * b;
555 PyFPE_END_PROTECT(a)
556 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557}
558
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000560float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 double a,b;
563 CONVERT_TO_DOUBLE(v, a);
564 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (b == 0.0) {
566 PyErr_SetString(PyExc_ZeroDivisionError,
567 "float division by zero");
568 return NULL;
569 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 PyFPE_START_PROTECT("divide", return 0)
571 a = a / b;
572 PyFPE_END_PROTECT(a)
573 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574}
575
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000576static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000577float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 double vx, wx;
580 double mod;
581 CONVERT_TO_DOUBLE(v, vx);
582 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (wx == 0.0) {
584 PyErr_SetString(PyExc_ZeroDivisionError,
585 "float modulo");
586 return NULL;
587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 PyFPE_START_PROTECT("modulo", return 0)
589 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000590 if (mod) {
591 /* ensure the remainder has the same sign as the denominator */
592 if ((wx < 0) != (mod < 0)) {
593 mod += wx;
594 }
595 }
596 else {
597 /* the remainder is zero, and in the presence of signed zeroes
598 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000599 it has the same sign as the denominator. */
600 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 }
602 PyFPE_END_PROTECT(mod)
603 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604}
605
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000607float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 double vx, wx;
610 double div, mod, floordiv;
611 CONVERT_TO_DOUBLE(v, vx);
612 CONVERT_TO_DOUBLE(w, wx);
613 if (wx == 0.0) {
614 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
615 return NULL;
616 }
617 PyFPE_START_PROTECT("divmod", return 0)
618 mod = fmod(vx, wx);
619 /* fmod is typically exact, so vx-mod is *mathematically* an
620 exact multiple of wx. But this is fp arithmetic, and fp
621 vx - mod is an approximation; the result is that div may
622 not be an exact integral value after the division, although
623 it will always be very close to one.
624 */
625 div = (vx - mod) / wx;
626 if (mod) {
627 /* ensure the remainder has the same sign as the denominator */
628 if ((wx < 0) != (mod < 0)) {
629 mod += wx;
630 div -= 1.0;
631 }
632 }
633 else {
634 /* the remainder is zero, and in the presence of signed zeroes
635 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000636 it has the same sign as the denominator. */
637 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 /* snap quotient to nearest integral value */
640 if (div) {
641 floordiv = floor(div);
642 if (div - floordiv > 0.5)
643 floordiv += 1.0;
644 }
645 else {
646 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000647 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
649 PyFPE_END_PROTECT(floordiv)
650 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000651}
652
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000654float_floor_div(PyObject *v, PyObject *w)
655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 t = float_divmod(v, w);
659 if (t == NULL || t == Py_NotImplemented)
660 return t;
661 assert(PyTuple_CheckExact(t));
662 r = PyTuple_GET_ITEM(t, 0);
663 Py_INCREF(r);
664 Py_DECREF(t);
665 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000666}
667
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000668/* determine whether x is an odd integer or not; assumes that
669 x is not an infinity or nan. */
670#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
671
Tim Peters63a35712001-12-11 19:57:24 +0000672static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000673float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 double iv, iw, ix;
676 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if ((PyObject *)z != Py_None) {
679 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
680 "allowed unless all arguments are integers");
681 return NULL;
682 }
Tim Peters32f453e2001-09-03 08:35:41 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 CONVERT_TO_DOUBLE(v, iv);
685 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 /* Sort out special cases here instead of relying on pow() */
688 if (iw == 0) { /* v**0 is 1, even 0**0 */
689 return PyFloat_FromDouble(1.0);
690 }
691 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
692 return PyFloat_FromDouble(iv);
693 }
694 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
695 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
696 }
697 if (Py_IS_INFINITY(iw)) {
698 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
699 * abs(v) > 1 (including case where v infinite)
700 *
701 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
702 * abs(v) > 1 (including case where v infinite)
703 */
704 iv = fabs(iv);
705 if (iv == 1.0)
706 return PyFloat_FromDouble(1.0);
707 else if ((iw > 0.0) == (iv > 1.0))
708 return PyFloat_FromDouble(fabs(iw)); /* return inf */
709 else
710 return PyFloat_FromDouble(0.0);
711 }
712 if (Py_IS_INFINITY(iv)) {
713 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
714 * both cases, we need to add the appropriate sign if w is
715 * an odd integer.
716 */
717 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
718 if (iw > 0.0)
719 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
720 else
721 return PyFloat_FromDouble(iw_is_odd ?
722 copysign(0.0, iv) : 0.0);
723 }
724 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
725 (already dealt with above), and an error
726 if w is negative. */
727 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
728 if (iw < 0.0) {
729 PyErr_SetString(PyExc_ZeroDivisionError,
730 "0.0 cannot be raised to a "
731 "negative power");
732 return NULL;
733 }
734 /* use correct sign if iw is odd */
735 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
736 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (iv < 0.0) {
739 /* Whether this is an error is a mess, and bumps into libm
740 * bugs so we have to figure it out ourselves.
741 */
742 if (iw != floor(iw)) {
743 /* Negative numbers raised to fractional powers
744 * become complex.
745 */
746 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
747 }
748 /* iw is an exact integer, albeit perhaps a very large
749 * one. Replace iv by its absolute value and remember
750 * to negate the pow result if iw is odd.
751 */
752 iv = -iv;
753 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
754 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
757 /* (-1) ** large_integer also ends up here. Here's an
758 * extract from the comments for the previous
759 * implementation explaining why this special case is
760 * necessary:
761 *
762 * -1 raised to an exact integer should never be exceptional.
763 * Alas, some libms (chiefly glibc as of early 2003) return
764 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
765 * happen to be representable in a *C* integer. That's a
766 * bug.
767 */
768 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
769 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 /* Now iv and iw are finite, iw is nonzero, and iv is
772 * positive and not equal to 1.0. We finally allow
773 * the platform pow to step in and do the rest.
774 */
775 errno = 0;
776 PyFPE_START_PROTECT("pow", return NULL)
777 ix = pow(iv, iw);
778 PyFPE_END_PROTECT(ix)
779 Py_ADJUST_ERANGE1(ix);
780 if (negate_result)
781 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (errno != 0) {
784 /* We don't expect any errno value other than ERANGE, but
785 * the range of libm bugs appears unbounded.
786 */
787 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
788 PyExc_ValueError);
789 return NULL;
790 }
791 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792}
793
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000794#undef DOUBLE_IS_ODD_INTEGER
795
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000797float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800}
801
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000802static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000803float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806}
807
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000808static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000809float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000812}
813
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000815float_is_integer(PyObject *v)
816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 double x = PyFloat_AsDouble(v);
818 PyObject *o;
819
820 if (x == -1.0 && PyErr_Occurred())
821 return NULL;
822 if (!Py_IS_FINITE(x))
823 Py_RETURN_FALSE;
824 errno = 0;
825 PyFPE_START_PROTECT("is_integer", return NULL)
826 o = (floor(x) == x) ? Py_True : Py_False;
827 PyFPE_END_PROTECT(x)
828 if (errno != 0) {
829 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
830 PyExc_ValueError);
831 return NULL;
832 }
833 Py_INCREF(o);
834 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000835}
836
837#if 0
838static PyObject *
839float_is_inf(PyObject *v)
840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 double x = PyFloat_AsDouble(v);
842 if (x == -1.0 && PyErr_Occurred())
843 return NULL;
844 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000845}
846
847static PyObject *
848float_is_nan(PyObject *v)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 double x = PyFloat_AsDouble(v);
851 if (x == -1.0 && PyErr_Occurred())
852 return NULL;
853 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000854}
855
856static PyObject *
857float_is_finite(PyObject *v)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 double x = PyFloat_AsDouble(v);
860 if (x == -1.0 && PyErr_Occurred())
861 return NULL;
862 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000863}
864#endif
865
866static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000867float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 double x = PyFloat_AsDouble(v);
870 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 (void)modf(x, &wholepart);
873 /* Try to get out cheap if this fits in a Python int. The attempt
874 * to cast to long must be protected, as C doesn't define what
875 * happens if the double is too big to fit in a long. Some rare
876 * systems raise an exception then (RISCOS was mentioned as one,
877 * and someone using a non-default option on Sun also bumped into
878 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
879 * still be vulnerable: if a long has more bits of precision than
880 * a double, casting MIN/MAX to double may yield an approximation,
881 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
882 * yield true from the C expression wholepart<=LONG_MAX, despite
883 * that wholepart is actually greater than LONG_MAX.
884 */
885 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
886 const long aslong = (long)wholepart;
887 return PyLong_FromLong(aslong);
888 }
889 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000890}
891
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000892/* double_round: rounds a finite double to the closest multiple of
893 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
894 ndigits <= 323). Returns a Python float, or sets a Python error and
895 returns NULL on failure (OverflowError and memory errors are possible). */
896
897#ifndef PY_NO_SHORT_FLOAT_REPR
898/* version of double_round that uses the correctly-rounded string<->double
899 conversions from Python/dtoa.c */
900
901static PyObject *
902double_round(double x, int ndigits) {
903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 double rounded;
905 Py_ssize_t buflen, mybuflen=100;
906 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
907 int decpt, sign;
908 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000909 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000912 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000914 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (buf == NULL) {
916 PyErr_NoMemory();
917 return NULL;
918 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
921 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
922 buflen = buf_end - buf;
923 if (buflen + 8 > mybuflen) {
924 mybuflen = buflen+8;
925 mybuf = (char *)PyMem_Malloc(mybuflen);
926 if (mybuf == NULL) {
927 PyErr_NoMemory();
928 goto exit;
929 }
930 }
931 /* copy buf to mybuf, adding exponent, sign and leading 0 */
932 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
933 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* and convert the resulting string back to a double */
936 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000937 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000939 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (errno == ERANGE && fabs(rounded) >= 1.)
941 PyErr_SetString(PyExc_OverflowError,
942 "rounded value too large to represent");
943 else
944 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* done computing value; now clean up */
947 if (mybuf != shortbuf)
948 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000949 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 _Py_dg_freedtoa(buf);
951 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000952}
953
954#else /* PY_NO_SHORT_FLOAT_REPR */
955
956/* fallback version, to be used when correctly rounded binary<->decimal
957 conversions aren't available */
958
959static PyObject *
960double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 double pow1, pow2, y, z;
962 if (ndigits >= 0) {
963 if (ndigits > 22) {
964 /* pow1 and pow2 are each safe from overflow, but
965 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
966 pow1 = pow(10.0, (double)(ndigits-22));
967 pow2 = 1e22;
968 }
969 else {
970 pow1 = pow(10.0, (double)ndigits);
971 pow2 = 1.0;
972 }
973 y = (x*pow1)*pow2;
974 /* if y overflows, then rounded value is exactly x */
975 if (!Py_IS_FINITE(y))
976 return PyFloat_FromDouble(x);
977 }
978 else {
979 pow1 = pow(10.0, (double)-ndigits);
980 pow2 = 1.0; /* unused; silences a gcc compiler warning */
981 y = x / pow1;
982 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 z = round(y);
985 if (fabs(y-z) == 0.5)
986 /* halfway between two integers; use round-half-even */
987 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (ndigits >= 0)
990 z = (z / pow2) / pow1;
991 else
992 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* if computation resulted in overflow, raise OverflowError */
995 if (!Py_IS_FINITE(z)) {
996 PyErr_SetString(PyExc_OverflowError,
997 "overflow occurred during round");
998 return NULL;
999 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001002}
1003
1004#endif /* PY_NO_SHORT_FLOAT_REPR */
1005
1006/* round a Python float v to the closest multiple of 10**-ndigits */
1007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001008static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001009float_round(PyObject *v, PyObject *args)
1010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 double x, rounded;
1012 PyObject *o_ndigits = NULL;
1013 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 x = PyFloat_AsDouble(v);
1016 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1017 return NULL;
Steve Dowercb39d1f2015-04-15 16:10:59 -04001018 if (o_ndigits == NULL || o_ndigits == Py_None) {
1019 /* single-argument round or with None ndigits:
1020 * round to nearest integer */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 rounded = round(x);
1022 if (fabs(x-rounded) == 0.5)
1023 /* halfway case: round to even */
1024 rounded = 2.0*round(x/2.0);
1025 return PyLong_FromDouble(rounded);
1026 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* interpret second argument as a Py_ssize_t; clips on overflow */
1029 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1030 if (ndigits == -1 && PyErr_Occurred())
1031 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 /* nans and infinities round to themselves */
1034 if (!Py_IS_FINITE(x))
1035 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1038 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1039 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001040#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1041#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (ndigits > NDIGITS_MAX)
1043 /* return x */
1044 return PyFloat_FromDouble(x);
1045 else if (ndigits < NDIGITS_MIN)
1046 /* return 0.0, but with sign of x */
1047 return PyFloat_FromDouble(0.0*x);
1048 else
1049 /* finite x, and ndigits is not unreasonably large */
1050 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001051#undef NDIGITS_MAX
1052#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001053}
1054
1055static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001056float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 if (PyFloat_CheckExact(v))
1059 Py_INCREF(v);
1060 else
1061 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1062 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063}
1064
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001065/* turn ASCII hex characters into integer values and vice versa */
1066
1067static char
1068char_from_hex(int x)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001071 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001072}
1073
1074static int
1075hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 int x;
1077 switch(c) {
1078 case '0':
1079 x = 0;
1080 break;
1081 case '1':
1082 x = 1;
1083 break;
1084 case '2':
1085 x = 2;
1086 break;
1087 case '3':
1088 x = 3;
1089 break;
1090 case '4':
1091 x = 4;
1092 break;
1093 case '5':
1094 x = 5;
1095 break;
1096 case '6':
1097 x = 6;
1098 break;
1099 case '7':
1100 x = 7;
1101 break;
1102 case '8':
1103 x = 8;
1104 break;
1105 case '9':
1106 x = 9;
1107 break;
1108 case 'a':
1109 case 'A':
1110 x = 10;
1111 break;
1112 case 'b':
1113 case 'B':
1114 x = 11;
1115 break;
1116 case 'c':
1117 case 'C':
1118 x = 12;
1119 break;
1120 case 'd':
1121 case 'D':
1122 x = 13;
1123 break;
1124 case 'e':
1125 case 'E':
1126 x = 14;
1127 break;
1128 case 'f':
1129 case 'F':
1130 x = 15;
1131 break;
1132 default:
1133 x = -1;
1134 break;
1135 }
1136 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001137}
1138
1139/* convert a float to a hexadecimal string */
1140
1141/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1142 of the form 4k+1. */
1143#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1144
1145static PyObject *
1146float_hex(PyObject *v)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 double x, m;
1149 int e, shift, i, si, esign;
1150 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1151 trailing NUL byte. */
1152 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001157 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001160 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return PyUnicode_FromString("-0x0.0p+0");
1162 else
1163 return PyUnicode_FromString("0x0.0p+0");
1164 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001167 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 m = ldexp(m, shift);
1169 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 si = 0;
1172 s[si] = char_from_hex((int)m);
1173 si++;
1174 m -= (int)m;
1175 s[si] = '.';
1176 si++;
1177 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1178 m *= 16.0;
1179 s[si] = char_from_hex((int)m);
1180 si++;
1181 m -= (int)m;
1182 }
1183 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (e < 0) {
1186 esign = (int)'-';
1187 e = -e;
1188 }
1189 else
1190 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (x < 0.0)
1193 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1194 else
1195 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001196}
1197
1198PyDoc_STRVAR(float_hex_doc,
1199"float.hex() -> string\n\
1200\n\
1201Return a hexadecimal representation of a floating-point number.\n\
1202>>> (-0.1).hex()\n\
1203'-0x1.999999999999ap-4'\n\
1204>>> 3.14159.hex()\n\
1205'0x1.921f9f01b866ep+1'");
1206
1207/* Convert a hexadecimal string to a float. */
1208
1209static PyObject *
1210float_fromhex(PyObject *cls, PyObject *arg)
1211{
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001212 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 double x;
1214 long exp, top_exp, lsb, key_digit;
1215 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1216 int half_eps, digit, round_up, negate=0;
1217 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /*
1220 * For the sake of simplicity and correctness, we impose an artificial
1221 * limit on ndigits, the total number of hex digits in the coefficient
1222 * The limit is chosen to ensure that, writing exp for the exponent,
1223 *
1224 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1225 * guaranteed to overflow (provided it's nonzero)
1226 *
1227 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1228 * guaranteed to underflow to 0.
1229 *
1230 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1231 * overflow in the calculation of exp and top_exp below.
1232 *
1233 * More specifically, ndigits is assumed to satisfy the following
1234 * inequalities:
1235 *
1236 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1237 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1238 *
1239 * If either of these inequalities is not satisfied, a ValueError is
1240 * raised. Otherwise, write x for the value of the hex string, and
1241 * assume x is nonzero. Then
1242 *
1243 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1244 *
1245 * Now if exp > LONG_MAX/2 then:
1246 *
1247 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1248 * = DBL_MAX_EXP
1249 *
1250 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1251 * double, so overflows. If exp < LONG_MIN/2, then
1252 *
1253 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1254 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1255 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1256 *
1257 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1258 * when converted to a C double.
1259 *
1260 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1261 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1262 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 s = _PyUnicode_AsStringAndSize(arg, &length);
1265 if (s == NULL)
1266 return NULL;
1267 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /********************
1270 * Parse the string *
1271 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* leading whitespace */
1274 while (Py_ISSPACE(*s))
1275 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 /* infinities and nans */
1278 x = _Py_parse_inf_or_nan(s, &coeff_end);
1279 if (coeff_end != s) {
1280 s = coeff_end;
1281 goto finished;
1282 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* optional sign */
1285 if (*s == '-') {
1286 s++;
1287 negate = 1;
1288 }
1289 else if (*s == '+')
1290 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* [0x] */
1293 s_store = s;
1294 if (*s == '0') {
1295 s++;
1296 if (*s == 'x' || *s == 'X')
1297 s++;
1298 else
1299 s = s_store;
1300 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* coefficient: <integer> [. <fraction>] */
1303 coeff_start = s;
1304 while (hex_from_char(*s) >= 0)
1305 s++;
1306 s_store = s;
1307 if (*s == '.') {
1308 s++;
1309 while (hex_from_char(*s) >= 0)
1310 s++;
1311 coeff_end = s-1;
1312 }
1313 else
1314 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /* ndigits = total # of hex digits; fdigits = # after point */
1317 ndigits = coeff_end - coeff_start;
1318 fdigits = coeff_end - s_store;
1319 if (ndigits == 0)
1320 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001321 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1322 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* [p <exponent>] */
1326 if (*s == 'p' || *s == 'P') {
1327 s++;
1328 exp_start = s;
1329 if (*s == '-' || *s == '+')
1330 s++;
1331 if (!('0' <= *s && *s <= '9'))
1332 goto parse_error;
1333 s++;
1334 while ('0' <= *s && *s <= '9')
1335 s++;
1336 exp = strtol(exp_start, NULL, 10);
1337 }
1338 else
1339 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1343 coeff_end-(j) : \
1344 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /*******************************************
1347 * Compute rounded value of the hex string *
1348 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* Discard leading zeros, and catch extreme overflow and underflow */
1351 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1352 ndigits--;
1353 if (ndigits == 0 || exp < LONG_MIN/2) {
1354 x = 0.0;
1355 goto finished;
1356 }
1357 if (exp > LONG_MAX/2)
1358 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* Adjust exponent for fractional part. */
1361 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1364 top_exp = exp + 4*((long)ndigits - 1);
1365 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1366 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* catch almost all nonextreme cases of overflow and underflow here */
1369 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1370 x = 0.0;
1371 goto finished;
1372 }
1373 if (top_exp > DBL_MAX_EXP)
1374 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* lsb = exponent of least significant bit of the *rounded* value.
1377 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001378 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 x = 0.0;
1381 if (exp >= lsb) {
1382 /* no rounding required */
1383 for (i = ndigits-1; i >= 0; i--)
1384 x = 16.0*x + HEX_DIGIT(i);
1385 x = ldexp(x, (int)(exp));
1386 goto finished;
1387 }
1388 /* rounding required. key_digit is the index of the hex digit
1389 containing the first bit to be rounded away. */
1390 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1391 key_digit = (lsb - exp - 1) / 4;
1392 for (i = ndigits-1; i > key_digit; i--)
1393 x = 16.0*x + HEX_DIGIT(i);
1394 digit = HEX_DIGIT(key_digit);
1395 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1398 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1399 if ((digit & half_eps) != 0) {
1400 round_up = 0;
1401 if ((digit & (3*half_eps-1)) != 0 ||
1402 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1403 round_up = 1;
1404 else
1405 for (i = key_digit-1; i >= 0; i--)
1406 if (HEX_DIGIT(i) != 0) {
1407 round_up = 1;
1408 break;
1409 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001410 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 x += 2*half_eps;
1412 if (top_exp == DBL_MAX_EXP &&
1413 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1414 /* overflow corner case: pre-rounded value <
1415 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1416 goto overflow_error;
1417 }
1418 }
1419 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001420
1421 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* optional trailing whitespace leading to the end of the string */
1423 while (Py_ISSPACE(*s))
1424 s++;
1425 if (s != s_end)
1426 goto parse_error;
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001427 result = PyFloat_FromDouble(negate ? -x : x);
1428 if (cls != (PyObject *)&PyFloat_Type && result != NULL) {
Serhiy Storchaka5787ef62016-05-12 10:32:30 +03001429 Py_SETREF(result, PyObject_CallFunctionObjArgs(cls, result, NULL));
Serhiy Storchaka25885d12016-05-12 10:21:14 +03001430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001432
1433 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 PyErr_SetString(PyExc_OverflowError,
1435 "hexadecimal value too large to represent as a float");
1436 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001437
1438 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyErr_SetString(PyExc_ValueError,
1440 "invalid hexadecimal floating-point string");
1441 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001442
1443 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 PyErr_SetString(PyExc_ValueError,
1445 "hexadecimal string too long to convert");
1446 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001447}
1448
1449PyDoc_STRVAR(float_fromhex_doc,
1450"float.fromhex(string) -> float\n\
1451\n\
1452Create a floating-point number from a hexadecimal string.\n\
1453>>> float.fromhex('0x1.ffffp10')\n\
14542047.984375\n\
1455>>> float.fromhex('-0x1p-1074')\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001456-5e-324");
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001457
1458
Christian Heimes26855632008-01-27 23:50:43 +00001459static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001460float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 double self;
1463 double float_part;
1464 int exponent;
1465 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 PyObject *py_exponent = NULL;
1468 PyObject *numerator = NULL;
1469 PyObject *denominator = NULL;
1470 PyObject *result_pair = NULL;
1471 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (Py_IS_INFINITY(self)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001476 PyErr_SetString(PyExc_OverflowError,
1477 "cannot convert Infinity to integer ratio");
1478 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (Py_IS_NAN(self)) {
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +02001481 PyErr_SetString(PyExc_ValueError,
1482 "cannot convert NaN to integer ratio");
1483 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 }
Christian Heimes26855632008-01-27 23:50:43 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1487 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1488 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1491 float_part *= 2.0;
1492 exponent--;
1493 }
1494 /* self == float_part * 2**exponent exactly and float_part is integral.
1495 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1496 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 numerator = PyLong_FromDouble(float_part);
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001499 if (numerator == NULL)
1500 goto error;
1501 denominator = PyLong_FromLong(1);
1502 if (denominator == NULL)
1503 goto error;
1504 py_exponent = PyLong_FromLong(Py_ABS(exponent));
1505 if (py_exponent == NULL)
1506 goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /* fold in 2**exponent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (exponent > 0) {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001510 Py_SETREF(numerator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001511 long_methods->nb_lshift(numerator, py_exponent));
1512 if (numerator == NULL)
1513 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 }
1515 else {
Serhiy Storchaka59865e72016-04-11 09:57:37 +03001516 Py_SETREF(denominator,
Serhiy Storchaka4e6aad12015-12-29 22:55:48 +02001517 long_methods->nb_lshift(denominator, py_exponent));
1518 if (denominator == NULL)
1519 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 }
1521
1522 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001523
Christian Heimes26855632008-01-27 23:50:43 +00001524error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 Py_XDECREF(py_exponent);
1526 Py_XDECREF(denominator);
1527 Py_XDECREF(numerator);
1528 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001529}
1530
1531PyDoc_STRVAR(float_as_integer_ratio_doc,
1532"float.as_integer_ratio() -> (int, int)\n"
1533"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001534"Return a pair of integers, whose ratio is exactly equal to the original\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001535"float and with a positive denominator.\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001536"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001537"\n"
1538">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001539"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001540">>> (0.0).as_integer_ratio()\n"
1541"(0, 1)\n"
1542">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001543"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001544
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001545
Jeremy Hylton938ace62002-07-17 16:30:39 +00001546static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001547float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1548
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549static PyObject *
1550float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyObject *x = Py_False; /* Integer zero */
1553 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (type != &PyFloat_Type)
1556 return float_subtype_new(type, args, kwds); /* Wimp out */
1557 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1558 return NULL;
1559 /* If it's a string, but not a string subclass, use
1560 PyFloat_FromString. */
1561 if (PyUnicode_CheckExact(x))
1562 return PyFloat_FromString(x);
1563 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564}
1565
Guido van Rossumbef14172001-08-29 15:47:46 +00001566/* Wimpy, slow approach to tp_new calls for subtypes of float:
1567 first create a regular float from whatever arguments we got,
1568 then allocate a subtype instance and initialize its ob_fval
1569 from the regular float. The regular float is then thrown away.
1570*/
1571static PyObject *
1572float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 assert(PyType_IsSubtype(type, &PyFloat_Type));
1577 tmp = float_new(&PyFloat_Type, args, kwds);
1578 if (tmp == NULL)
1579 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02001580 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 newobj = type->tp_alloc(type, 0);
1582 if (newobj == NULL) {
1583 Py_DECREF(tmp);
1584 return NULL;
1585 }
1586 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1587 Py_DECREF(tmp);
1588 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001589}
1590
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001591static PyObject *
1592float_getnewargs(PyFloatObject *v)
1593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001595}
1596
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597/* this is for the benefit of the pack/unpack routines below */
1598
1599typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001601} float_format_type;
1602
1603static float_format_type double_format, float_format;
1604static float_format_type detected_double_format, detected_float_format;
1605
1606static PyObject *
1607float_getformat(PyTypeObject *v, PyObject* arg)
1608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 char* s;
1610 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (!PyUnicode_Check(arg)) {
1613 PyErr_Format(PyExc_TypeError,
1614 "__getformat__() argument must be string, not %.500s",
1615 Py_TYPE(arg)->tp_name);
1616 return NULL;
1617 }
1618 s = _PyUnicode_AsString(arg);
1619 if (s == NULL)
1620 return NULL;
1621 if (strcmp(s, "double") == 0) {
1622 r = double_format;
1623 }
1624 else if (strcmp(s, "float") == 0) {
1625 r = float_format;
1626 }
1627 else {
1628 PyErr_SetString(PyExc_ValueError,
1629 "__getformat__() argument 1 must be "
1630 "'double' or 'float'");
1631 return NULL;
1632 }
1633
1634 switch (r) {
1635 case unknown_format:
1636 return PyUnicode_FromString("unknown");
1637 case ieee_little_endian_format:
1638 return PyUnicode_FromString("IEEE, little-endian");
1639 case ieee_big_endian_format:
1640 return PyUnicode_FromString("IEEE, big-endian");
1641 default:
1642 Py_FatalError("insane float_format or double_format");
1643 return NULL;
1644 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001645}
1646
1647PyDoc_STRVAR(float_getformat_doc,
1648"float.__getformat__(typestr) -> string\n"
1649"\n"
1650"You probably don't want to use this function. It exists mainly to be\n"
1651"used in Python's test suite.\n"
1652"\n"
1653"typestr must be 'double' or 'float'. This function returns whichever of\n"
1654"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1655"format of floating point numbers used by the C type named by typestr.");
1656
1657static PyObject *
1658float_setformat(PyTypeObject *v, PyObject* args)
1659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 char* typestr;
1661 char* format;
1662 float_format_type f;
1663 float_format_type detected;
1664 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1667 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (strcmp(typestr, "double") == 0) {
1670 p = &double_format;
1671 detected = detected_double_format;
1672 }
1673 else if (strcmp(typestr, "float") == 0) {
1674 p = &float_format;
1675 detected = detected_float_format;
1676 }
1677 else {
1678 PyErr_SetString(PyExc_ValueError,
1679 "__setformat__() argument 1 must "
1680 "be 'double' or 'float'");
1681 return NULL;
1682 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (strcmp(format, "unknown") == 0) {
1685 f = unknown_format;
1686 }
1687 else if (strcmp(format, "IEEE, little-endian") == 0) {
1688 f = ieee_little_endian_format;
1689 }
1690 else if (strcmp(format, "IEEE, big-endian") == 0) {
1691 f = ieee_big_endian_format;
1692 }
1693 else {
1694 PyErr_SetString(PyExc_ValueError,
1695 "__setformat__() argument 2 must be "
1696 "'unknown', 'IEEE, little-endian' or "
1697 "'IEEE, big-endian'");
1698 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (f != unknown_format && f != detected) {
1703 PyErr_Format(PyExc_ValueError,
1704 "can only set %s format to 'unknown' or the "
1705 "detected platform value", typestr);
1706 return NULL;
1707 }
1708
1709 *p = f;
1710 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711}
1712
1713PyDoc_STRVAR(float_setformat_doc,
1714"float.__setformat__(typestr, fmt) -> None\n"
1715"\n"
1716"You probably don't want to use this function. It exists mainly to be\n"
1717"used in Python's test suite.\n"
1718"\n"
1719"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1720"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1721"one of the latter two if it appears to match the underlying C reality.\n"
1722"\n"
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001723"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724"This affects how floats are converted to and from binary strings.");
1725
Guido van Rossumb43daf72007-08-01 18:08:08 +00001726static PyObject *
1727float_getzero(PyObject *v, void *closure)
1728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001730}
1731
Eric Smith8c663262007-08-25 02:26:07 +00001732static PyObject *
1733float__format__(PyObject *self, PyObject *args)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001736 _PyUnicodeWriter writer;
1737 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1740 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001741
Victor Stinner8f674cc2013-04-17 23:02:17 +02001742 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743 ret = _PyFloat_FormatAdvancedWriter(
1744 &writer,
1745 self,
1746 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1747 if (ret == -1) {
1748 _PyUnicodeWriter_Dealloc(&writer);
1749 return NULL;
1750 }
1751 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001752}
1753
1754PyDoc_STRVAR(float__format__doc,
1755"float.__format__(format_spec) -> string\n"
1756"\n"
1757"Formats the float according to format_spec.");
1758
1759
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001760static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001762 "Return self, the complex conjugate of any float."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001764 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 {"__round__", (PyCFunction)float_round, METH_VARARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001766 "Return the Integral closest to x, rounding half toward even.\n"
1767 "When an argument is passed, work like built-in round(x, ndigits)."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1769 float_as_integer_ratio_doc},
1770 {"fromhex", (PyCFunction)float_fromhex,
1771 METH_O|METH_CLASS, float_fromhex_doc},
1772 {"hex", (PyCFunction)float_hex,
1773 METH_NOARGS, float_hex_doc},
1774 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001775 "Return True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001776#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001778 "Return True if the float is positive or negative infinite."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001780 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti7760b4e2013-10-06 00:45:11 +03001782 "Return True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001783#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1785 {"__getformat__", (PyCFunction)float_getformat,
1786 METH_O|METH_CLASS, float_getformat_doc},
1787 {"__setformat__", (PyCFunction)float_setformat,
1788 METH_VARARGS|METH_CLASS, float_setformat_doc},
1789 {"__format__", (PyCFunction)float__format__,
1790 METH_VARARGS, float__format__doc},
1791 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001792};
1793
Guido van Rossumb43daf72007-08-01 18:08:08 +00001794static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001796 (getter)float_float, (setter)NULL,
1797 "the real part of a complex number",
1798 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001800 (getter)float_getzero, (setter)NULL,
1801 "the imaginary part of a complex number",
1802 NULL},
1803 {NULL} /* Sentinel */
1804};
1805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807"float(x) -> floating point number\n\
1808\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001809Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810
1811
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001812static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 float_add, /*nb_add*/
1814 float_sub, /*nb_subtract*/
1815 float_mul, /*nb_multiply*/
1816 float_rem, /*nb_remainder*/
1817 float_divmod, /*nb_divmod*/
1818 float_pow, /*nb_power*/
1819 (unaryfunc)float_neg, /*nb_negative*/
1820 (unaryfunc)float_float, /*nb_positive*/
1821 (unaryfunc)float_abs, /*nb_absolute*/
1822 (inquiry)float_bool, /*nb_bool*/
1823 0, /*nb_invert*/
1824 0, /*nb_lshift*/
1825 0, /*nb_rshift*/
1826 0, /*nb_and*/
1827 0, /*nb_xor*/
1828 0, /*nb_or*/
1829 float_trunc, /*nb_int*/
1830 0, /*nb_reserved*/
1831 float_float, /*nb_float*/
1832 0, /* nb_inplace_add */
1833 0, /* nb_inplace_subtract */
1834 0, /* nb_inplace_multiply */
1835 0, /* nb_inplace_remainder */
1836 0, /* nb_inplace_power */
1837 0, /* nb_inplace_lshift */
1838 0, /* nb_inplace_rshift */
1839 0, /* nb_inplace_and */
1840 0, /* nb_inplace_xor */
1841 0, /* nb_inplace_or */
1842 float_floor_div, /* nb_floor_divide */
1843 float_div, /* nb_true_divide */
1844 0, /* nb_inplace_floor_divide */
1845 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846};
1847
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1850 "float",
1851 sizeof(PyFloatObject),
1852 0,
1853 (destructor)float_dealloc, /* tp_dealloc */
1854 0, /* tp_print */
1855 0, /* tp_getattr */
1856 0, /* tp_setattr */
1857 0, /* tp_reserved */
1858 (reprfunc)float_repr, /* tp_repr */
1859 &float_as_number, /* tp_as_number */
1860 0, /* tp_as_sequence */
1861 0, /* tp_as_mapping */
1862 (hashfunc)float_hash, /* tp_hash */
1863 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001864 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyObject_GenericGetAttr, /* tp_getattro */
1866 0, /* tp_setattro */
1867 0, /* tp_as_buffer */
1868 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1869 float_doc, /* tp_doc */
1870 0, /* tp_traverse */
1871 0, /* tp_clear */
1872 float_richcompare, /* tp_richcompare */
1873 0, /* tp_weaklistoffset */
1874 0, /* tp_iter */
1875 0, /* tp_iternext */
1876 float_methods, /* tp_methods */
1877 0, /* tp_members */
1878 float_getset, /* tp_getset */
1879 0, /* tp_base */
1880 0, /* tp_dict */
1881 0, /* tp_descr_get */
1882 0, /* tp_descr_set */
1883 0, /* tp_dictoffset */
1884 0, /* tp_init */
1885 0, /* tp_alloc */
1886 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001887};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001888
Victor Stinner1c8f0592013-07-22 22:24:54 +02001889int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001890_PyFloat_Init(void)
1891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* We attempt to determine if this machine is using IEEE
1893 floating point formats by peering at the bits of some
1894 carefully chosen values. If it looks like we are on an
1895 IEEE platform, the float packing/unpacking routines can
1896 just copy bits, if not they resort to arithmetic & shifts
1897 and masks. The shifts & masks approach works on all finite
1898 values, but what happens to infinities, NaNs and signed
1899 zeroes on packing is an accident, and attempting to unpack
1900 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 Note that if we're on some whacked-out platform which uses
1903 IEEE formats but isn't strictly little-endian or big-
1904 endian, we will fall back to the portable shifts & masks
1905 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906
1907#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 {
1909 double x = 9006104071832581.0;
1910 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1911 detected_double_format = ieee_big_endian_format;
1912 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1913 detected_double_format = ieee_little_endian_format;
1914 else
1915 detected_double_format = unknown_format;
1916 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001917#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919#endif
1920
1921#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 {
1923 float y = 16711938.0;
1924 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1925 detected_float_format = ieee_big_endian_format;
1926 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1927 detected_float_format = ieee_little_endian_format;
1928 else
1929 detected_float_format = unknown_format;
1930 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001933#endif
1934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 double_format = detected_double_format;
1936 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001939 if (FloatInfoType.tp_name == NULL) {
1940 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1941 return 0;
1942 }
1943 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001944}
1945
Georg Brandl2ee470f2008-07-16 12:55:28 +00001946int
1947PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001948{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001949 PyFloatObject *f = free_list, *next;
1950 int i = numfree;
1951 while (f) {
1952 next = (PyFloatObject*) Py_TYPE(f);
1953 PyObject_FREE(f);
1954 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001956 free_list = NULL;
1957 numfree = 0;
1958 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001959}
1960
1961void
1962PyFloat_Fini(void)
1963{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001964 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001965}
Tim Peters9905b942003-03-20 20:53:32 +00001966
David Malcolm49526f42012-06-22 14:55:41 -04001967/* Print summary info about the state of the optimized allocator */
1968void
1969_PyFloat_DebugMallocStats(FILE *out)
1970{
1971 _PyDebugAllocatorStats(out,
1972 "free PyFloatObject",
1973 numfree, sizeof(PyFloatObject));
1974}
1975
1976
Tim Peters9905b942003-03-20 20:53:32 +00001977/*----------------------------------------------------------------------------
1978 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001979 */
1980int
1981_PyFloat_Pack4(double x, unsigned char *p, int le)
1982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (float_format == unknown_format) {
1984 unsigned char sign;
1985 int e;
1986 double f;
1987 unsigned int fbits;
1988 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (le) {
1991 p += 3;
1992 incr = -1;
1993 }
Tim Peters9905b942003-03-20 20:53:32 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (x < 0) {
1996 sign = 1;
1997 x = -x;
1998 }
1999 else
2000 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* Normalize f to be in the range [1.0, 2.0) */
2005 if (0.5 <= f && f < 1.0) {
2006 f *= 2.0;
2007 e--;
2008 }
2009 else if (f == 0.0)
2010 e = 0;
2011 else {
2012 PyErr_SetString(PyExc_SystemError,
2013 "frexp() result out of range");
2014 return -1;
2015 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (e >= 128)
2018 goto Overflow;
2019 else if (e < -126) {
2020 /* Gradual underflow */
2021 f = ldexp(f, 126 + e);
2022 e = 0;
2023 }
2024 else if (!(e == 0 && f == 0.0)) {
2025 e += 127;
2026 f -= 1.0; /* Get rid of leading 1 */
2027 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 f *= 8388608.0; /* 2**23 */
2030 fbits = (unsigned int)(f + 0.5); /* Round */
2031 assert(fbits <= 8388608);
2032 if (fbits >> 23) {
2033 /* The carry propagated out of a string of 23 1 bits. */
2034 fbits = 0;
2035 ++e;
2036 if (e >= 255)
2037 goto Overflow;
2038 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* First byte */
2041 *p = (sign << 7) | (e >> 1);
2042 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* Second byte */
2045 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2046 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 /* Third byte */
2049 *p = (fbits >> 8) & 0xFF;
2050 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Fourth byte */
2053 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 /* Done */
2056 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
2059 else {
2060 float y = (float)x;
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002061 const unsigned char *s = (unsigned char*)&y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2065 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if ((float_format == ieee_little_endian_format && !le)
2068 || (float_format == ieee_big_endian_format && le)) {
2069 p += 3;
2070 incr = -1;
2071 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 for (i = 0; i < 4; i++) {
2074 *p = *s++;
2075 p += incr;
2076 }
2077 return 0;
2078 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002079 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 PyErr_SetString(PyExc_OverflowError,
2081 "float too large to pack with f format");
2082 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002083}
2084
2085int
2086_PyFloat_Pack8(double x, unsigned char *p, int le)
2087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (double_format == unknown_format) {
2089 unsigned char sign;
2090 int e;
2091 double f;
2092 unsigned int fhi, flo;
2093 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (le) {
2096 p += 7;
2097 incr = -1;
2098 }
Tim Peters9905b942003-03-20 20:53:32 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (x < 0) {
2101 sign = 1;
2102 x = -x;
2103 }
2104 else
2105 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Normalize f to be in the range [1.0, 2.0) */
2110 if (0.5 <= f && f < 1.0) {
2111 f *= 2.0;
2112 e--;
2113 }
2114 else if (f == 0.0)
2115 e = 0;
2116 else {
2117 PyErr_SetString(PyExc_SystemError,
2118 "frexp() result out of range");
2119 return -1;
2120 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (e >= 1024)
2123 goto Overflow;
2124 else if (e < -1022) {
2125 /* Gradual underflow */
2126 f = ldexp(f, 1022 + e);
2127 e = 0;
2128 }
2129 else if (!(e == 0 && f == 0.0)) {
2130 e += 1023;
2131 f -= 1.0; /* Get rid of leading 1 */
2132 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2135 f *= 268435456.0; /* 2**28 */
2136 fhi = (unsigned int)f; /* Truncate */
2137 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 f -= (double)fhi;
2140 f *= 16777216.0; /* 2**24 */
2141 flo = (unsigned int)(f + 0.5); /* Round */
2142 assert(flo <= 16777216);
2143 if (flo >> 24) {
2144 /* The carry propagated out of a string of 24 1 bits. */
2145 flo = 0;
2146 ++fhi;
2147 if (fhi >> 28) {
2148 /* And it also progagated out of the next 28 bits. */
2149 fhi = 0;
2150 ++e;
2151 if (e >= 2047)
2152 goto Overflow;
2153 }
2154 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 /* First byte */
2157 *p = (sign << 7) | (e >> 4);
2158 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* Second byte */
2161 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2162 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* Third byte */
2165 *p = (fhi >> 16) & 0xFF;
2166 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* Fourth byte */
2169 *p = (fhi >> 8) & 0xFF;
2170 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 /* Fifth byte */
2173 *p = fhi & 0xFF;
2174 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 /* Sixth byte */
2177 *p = (flo >> 16) & 0xFF;
2178 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* Seventh byte */
2181 *p = (flo >> 8) & 0xFF;
2182 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* Eighth byte */
2185 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002186 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 /* Done */
2189 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Overflow:
2192 PyErr_SetString(PyExc_OverflowError,
2193 "float too large to pack with d format");
2194 return -1;
2195 }
2196 else {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002197 const unsigned char *s = (unsigned char*)&x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if ((double_format == ieee_little_endian_format && !le)
2201 || (double_format == ieee_big_endian_format && le)) {
2202 p += 7;
2203 incr = -1;
2204 }
2205
2206 for (i = 0; i < 8; i++) {
2207 *p = *s++;
2208 p += incr;
2209 }
2210 return 0;
2211 }
Tim Peters9905b942003-03-20 20:53:32 +00002212}
2213
2214double
2215_PyFloat_Unpack4(const unsigned char *p, int le)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (float_format == unknown_format) {
2218 unsigned char sign;
2219 int e;
2220 unsigned int f;
2221 double x;
2222 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (le) {
2225 p += 3;
2226 incr = -1;
2227 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* First byte */
2230 sign = (*p >> 7) & 1;
2231 e = (*p & 0x7F) << 1;
2232 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Second byte */
2235 e |= (*p >> 7) & 1;
2236 f = (*p & 0x7F) << 16;
2237 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (e == 255) {
2240 PyErr_SetString(
2241 PyExc_ValueError,
2242 "can't unpack IEEE 754 special value "
2243 "on non-IEEE platform");
2244 return -1;
2245 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* Third byte */
2248 f |= *p << 8;
2249 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* Fourth byte */
2252 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* XXX This sadly ignores Inf/NaN issues */
2257 if (e == 0)
2258 e = -126;
2259 else {
2260 x += 1.0;
2261 e -= 127;
2262 }
2263 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (sign)
2266 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 return x;
2269 }
2270 else {
2271 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if ((float_format == ieee_little_endian_format && !le)
2274 || (float_format == ieee_big_endian_format && le)) {
2275 char buf[4];
2276 char *d = &buf[3];
2277 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 for (i = 0; i < 4; i++) {
2280 *d-- = *p++;
2281 }
2282 memcpy(&x, buf, 4);
2283 }
2284 else {
2285 memcpy(&x, p, 4);
2286 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return x;
2289 }
Tim Peters9905b942003-03-20 20:53:32 +00002290}
2291
2292double
2293_PyFloat_Unpack8(const unsigned char *p, int le)
2294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (double_format == unknown_format) {
2296 unsigned char sign;
2297 int e;
2298 unsigned int fhi, flo;
2299 double x;
2300 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (le) {
2303 p += 7;
2304 incr = -1;
2305 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* First byte */
2308 sign = (*p >> 7) & 1;
2309 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Second byte */
2314 e |= (*p >> 4) & 0xF;
2315 fhi = (*p & 0xF) << 24;
2316 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if (e == 2047) {
2319 PyErr_SetString(
2320 PyExc_ValueError,
2321 "can't unpack IEEE 754 special value "
2322 "on non-IEEE platform");
2323 return -1.0;
2324 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* Third byte */
2327 fhi |= *p << 16;
2328 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 /* Fourth byte */
2331 fhi |= *p << 8;
2332 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Fifth byte */
2335 fhi |= *p;
2336 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* Sixth byte */
2339 flo = *p << 16;
2340 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Seventh byte */
2343 flo |= *p << 8;
2344 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* Eighth byte */
2347 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2350 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (e == 0)
2353 e = -1022;
2354 else {
2355 x += 1.0;
2356 e -= 1023;
2357 }
2358 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 if (sign)
2361 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return x;
2364 }
2365 else {
2366 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if ((double_format == ieee_little_endian_format && !le)
2369 || (double_format == ieee_big_endian_format && le)) {
2370 char buf[8];
2371 char *d = &buf[7];
2372 int i;
2373
2374 for (i = 0; i < 8; i++) {
2375 *d-- = *p++;
2376 }
2377 memcpy(&x, buf, 8);
2378 }
2379 else {
2380 memcpy(&x, p, 8);
2381 }
2382
2383 return x;
2384 }
Tim Peters9905b942003-03-20 20:53:32 +00002385}