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