blob: a433697fa8f622ce32843a55220c1b4fd0656cea [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"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson7103aa42008-07-15 19:08:33 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Neal Norwitz5f95a792008-01-25 08:04:16 +000022#ifdef _OSF_SOURCE
23/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24extern int finite(double);
25#endif
26
Guido van Rossum93ad0df1997-05-13 21:00:42 +000027/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000029#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000030#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000031
Guido van Rossum3fce8831999-03-12 19:43:17 +000032struct _floatblock {
33 struct _floatblock *next;
34 PyFloatObject objects[N_FLOATOBJECTS];
35};
36
37typedef struct _floatblock PyFloatBlock;
38
39static PyFloatBlock *block_list = NULL;
40static PyFloatObject *free_list = NULL;
41
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000043fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044{
45 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000049 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000050 ((PyFloatBlock *)p)->next = block_list;
51 block_list = (PyFloatBlock *)p;
52 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053 q = p + N_FLOATOBJECTS;
54 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000055 Py_TYPE(q) = (struct _typeobject *)(q-1);
56 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000057 return p + N_FLOATOBJECTS - 1;
58}
59
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060double
61PyFloat_GetMax(void)
62{
63 return DBL_MAX;
64}
65
66double
67PyFloat_GetMin(void)
68{
69 return DBL_MIN;
70}
71
Christian Heimes796fc312008-01-30 18:58:29 +000072static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000073
74PyDoc_STRVAR(floatinfo__doc__,
75"sys.floatinfo\n\
76\n\
77A structseq holding information about the float type. It contains low level\n\
78information about the precision and internal representation. Please study\n\
79your system's :file:`float.h` for more information.");
80
81static PyStructSequence_Field floatinfo_fields[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
84 "is representable"},
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
86 "is representable"},
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
91 "a normalized"},
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
98 {0}
99};
100
101static PyStructSequence_Desc floatinfo_desc = {
102 "sys.floatinfo", /* name */
103 floatinfo__doc__, /* doc */
104 floatinfo_fields, /* fields */
105 11
106};
107
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108PyObject *
109PyFloat_GetInfo(void)
110{
Christian Heimes796fc312008-01-30 18:58:29 +0000111 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000112 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114 floatinfo = PyStructSequence_New(&FloatInfoType);
115 if (floatinfo == NULL) {
116 return NULL;
117 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Christian Heimesc94e2b52008-01-14 04:13:37 +0000119#define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121#define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000123
Christian Heimesc94e2b52008-01-14 04:13:37 +0000124 SetDblFlag(DBL_MAX);
125 SetIntFlag(DBL_MAX_EXP);
126 SetIntFlag(DBL_MAX_10_EXP);
127 SetDblFlag(DBL_MIN);
128 SetIntFlag(DBL_MIN_EXP);
129 SetIntFlag(DBL_MIN_10_EXP);
130 SetIntFlag(DBL_DIG);
131 SetIntFlag(DBL_MANT_DIG);
132 SetDblFlag(DBL_EPSILON);
133 SetIntFlag(FLT_RADIX);
134 SetIntFlag(FLT_ROUNDS);
135#undef SetIntFlag
136#undef SetDblFlag
137
138 if (PyErr_Occurred()) {
139 Py_CLEAR(floatinfo);
140 return NULL;
141 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000142 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
152 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000153 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000155 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Tim Petersef14d732000-09-23 03:39:17 +0000161/**************************************************************************
162RED_FLAG 22-Sep-2000 tim
163PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
164
1651. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
168
1692. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
172
173Since we can't change the interface of a public API function, pend is
174still supported but now *officially* useless: if pend is not NULL,
175*pend is set to NULL.
176**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000178PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179{
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000180 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000182 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000184 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000185#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187
Tim Petersef14d732000-09-23 03:39:17 +0000188 if (pend)
189 *pend = NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000190 if (PyString_Check(v)) {
191 s = PyString_AS_STRING(v);
192 len = PyString_GET_SIZE(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000194#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000195 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000196 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000198 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 return NULL;
200 }
Tim Petersef14d732000-09-23 03:39:17 +0000201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000203 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 NULL))
205 return NULL;
206 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000207 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000208 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000210 else if (PyObject_AsCharBuffer(v, &s, &len)) {
211 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000212 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000215 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000216
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 while (*s && isspace(Py_CHARMASK(*s)))
218 s++;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000219 /* We don't care about overflow or underflow. If the platform
220 * supports them, infinities and signed zeroes (on underflow) are
221 * fine. */
222 errno = 0;
Tim Peters858346e2000-09-25 21:01:28 +0000223 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000224 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000225 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000226 if (end == s) {
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000227 if (errno == ENOMEM)
228 PyErr_NoMemory();
229 else {
230 PyOS_snprintf(buffer, sizeof(buffer),
231 "invalid literal for float(): %.200s", s);
232 PyErr_SetString(PyExc_ValueError, buffer);
Christian Heimes0a8143f2007-12-18 23:22:54 +0000233 }
Tim Petersef14d732000-09-23 03:39:17 +0000234 return NULL;
235 }
236 /* Since end != s, the platform made *some* kind of sense out
237 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000238 while (*end && isspace(Py_CHARMASK(*end)))
239 end++;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000240 if (end != last) {
241 if (*end == '\0')
242 PyErr_SetString(PyExc_ValueError,
243 "null byte in argument for float()");
244 else {
245 PyOS_snprintf(buffer, sizeof(buffer),
246 "invalid literal for float(): %.200s", s);
247 PyErr_SetString(PyExc_ValueError, buffer);
248 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 return NULL;
250 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000251 return PyFloat_FromDouble(x);
252}
253
Guido van Rossum234f9421993-06-17 12:35:49 +0000254static void
Fred Drakefd99de62000-07-09 05:02:18 +0000255float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000256{
Guido van Rossum9475a232001-10-05 20:51:39 +0000257 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000258 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000259 free_list = op;
260 }
261 else
Christian Heimese93237d2007-12-19 02:37:44 +0000262 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000263}
264
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000265double
Fred Drakefd99de62000-07-09 05:02:18 +0000266PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268 PyNumberMethods *nb;
269 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000271
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 if (op && PyFloat_Check(op))
273 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000274
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000275 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277 return -1;
278 }
Tim Petersd2364e82001-11-01 20:09:42 +0000279
Christian Heimese93237d2007-12-19 02:37:44 +0000280 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000281 PyErr_SetString(PyExc_TypeError, "a float is required");
282 return -1;
283 }
284
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286 if (fo == NULL)
287 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000288 if (!PyFloat_Check(fo)) {
289 PyErr_SetString(PyExc_TypeError,
290 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000291 return -1;
292 }
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 val = PyFloat_AS_DOUBLE(fo);
295 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000296
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298}
299
300/* Methods */
301
Tim Peters97019e42001-11-28 22:43:45 +0000302static void
303format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304{
305 register char *cp;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000306 int i;
307
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308 /* Subroutine for float_repr and float_print.
309 We want float numbers to be recognizable as such,
310 i.e., they should contain a decimal point or an exponent.
311 However, %g may print the number as an integer;
312 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000313
314 assert(PyFloat_Check(v));
Eric Smith068f0652009-04-25 21:40:15 +0000315 _PyOS_double_to_string(buf, buflen, v->ob_fval, 'g', precision,
316 0, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317 cp = buf;
318 if (*cp == '-')
319 cp++;
320 for (; *cp != '\0'; cp++) {
321 /* Any non-digit means it's not an integer;
322 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000323 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324 break;
325 }
326 if (*cp == '\0') {
327 *cp++ = '.';
328 *cp++ = '0';
329 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000330 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000332 /* Checking the next three chars should be more than enough to
333 * detect inf or nan, even on Windows. We check for inf or nan
334 * at last because they are rare cases.
335 */
336 for (i=0; *cp != '\0' && i<3; cp++, i++) {
337 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
338 continue;
339 /* found something that is neither a digit nor point
340 * it might be a NaN or INF
341 */
342#ifdef Py_NAN
343 if (Py_IS_NAN(v->ob_fval)) {
344 strcpy(buf, "nan");
345 }
346 else
347#endif
348 if (Py_IS_INFINITY(v->ob_fval)) {
349 cp = buf;
350 if (*cp == '-')
351 cp++;
352 strcpy(cp, "inf");
353 }
354 break;
355 }
356
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357}
358
Tim Peters97019e42001-11-28 22:43:45 +0000359/* XXX PyFloat_AsStringEx should not be a public API function (for one
360 XXX thing, its signature passes a buffer without a length; for another,
361 XXX it isn't useful outside this file).
362*/
363void
364PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
365{
366 format_float(buf, 100, v, precision);
367}
368
Neil Schemenauer32117e52001-01-04 01:44:34 +0000369/* Macro and helper that convert PyObject obj to a C double and store
370 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000371 slot function. If conversion to double raises an exception, obj is
372 set to NULL, and the function invoking this macro returns NULL. If
373 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
374 stored in obj, and returned from the function invoking this macro.
375*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000376#define CONVERT_TO_DOUBLE(obj, dbl) \
377 if (PyFloat_Check(obj)) \
378 dbl = PyFloat_AS_DOUBLE(obj); \
379 else if (convert_to_double(&(obj), &(dbl)) < 0) \
380 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000381
382static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000383convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000384{
385 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000386
Neil Schemenauer32117e52001-01-04 01:44:34 +0000387 if (PyInt_Check(obj)) {
388 *dbl = (double)PyInt_AS_LONG(obj);
389 }
390 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000391 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000392 if (*dbl == -1.0 && PyErr_Occurred()) {
393 *v = NULL;
394 return -1;
395 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000396 }
397 else {
398 Py_INCREF(Py_NotImplemented);
399 *v = Py_NotImplemented;
400 return -1;
401 }
402 return 0;
403}
404
Guido van Rossum57072eb1999-12-23 19:00:28 +0000405/* Precisions used by repr() and str(), respectively.
406
407 The repr() precision (17 significant decimal digits) is the minimal number
408 that is guaranteed to have enough precision so that if the number is read
409 back in the exact same binary value is recreated. This is true for IEEE
410 floating point by design, and also happens to work for all other modern
411 hardware.
412
413 The str() precision is chosen so that in most cases, the rounding noise
414 created by various operations is suppressed, while giving plenty of
415 precision for practical use.
416
417*/
418
419#define PREC_REPR 17
420#define PREC_STR 12
421
Tim Peters97019e42001-11-28 22:43:45 +0000422/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
423 XXX they pass a char buffer without passing a length.
424*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000425void
Fred Drakefd99de62000-07-09 05:02:18 +0000426PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000427{
Tim Peters97019e42001-11-28 22:43:45 +0000428 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000429}
430
Tim Peters72f98e92001-05-08 15:19:57 +0000431void
432PyFloat_AsReprString(char *buf, PyFloatObject *v)
433{
Tim Peters97019e42001-11-28 22:43:45 +0000434 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000435}
436
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000437/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000438static int
Fred Drakefd99de62000-07-09 05:02:18 +0000439float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440{
441 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000442 format_float(buf, sizeof(buf), v,
443 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000444 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000446 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000447 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448}
449
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000451float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000453 char buf[100];
454 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000455
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000456 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000457}
458
459static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000460float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000461{
462 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000463 format_float(buf, sizeof(buf), v, PREC_STR);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000464 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000465}
466
Tim Peters307fa782004-09-23 08:06:40 +0000467/* Comparison is pretty much a nightmare. When comparing float to float,
468 * we do it as straightforwardly (and long-windedly) as conceivable, so
469 * that, e.g., Python x == y delivers the same result as the platform
470 * C x == y when x and/or y is a NaN.
471 * When mixing float with an integer type, there's no good *uniform* approach.
472 * Converting the double to an integer obviously doesn't work, since we
473 * may lose info from fractional bits. Converting the integer to a double
474 * also has two failure modes: (1) a long int may trigger overflow (too
475 * large to fit in the dynamic range of a C double); (2) even a C long may have
476 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
477 * 63 bits of precision, but a C double probably has only 53), and then
478 * we can falsely claim equality when low-order integer bits are lost by
479 * coercion to double. So this part is painful too.
480 */
481
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000482static PyObject*
483float_richcompare(PyObject *v, PyObject *w, int op)
484{
485 double i, j;
486 int r = 0;
487
Tim Peters307fa782004-09-23 08:06:40 +0000488 assert(PyFloat_Check(v));
489 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000490
Tim Peters307fa782004-09-23 08:06:40 +0000491 /* Switch on the type of w. Set i and j to doubles to be compared,
492 * and op to the richcomp to use.
493 */
494 if (PyFloat_Check(w))
495 j = PyFloat_AS_DOUBLE(w);
496
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000497 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000498 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000499 /* If i is an infinity, its magnitude exceeds any
500 * finite integer, so it doesn't matter which int we
501 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000502 */
503 j = 0.0;
504 else
505 goto Unimplemented;
506 }
507
508 else if (PyInt_Check(w)) {
509 long jj = PyInt_AS_LONG(w);
510 /* In the worst realistic case I can imagine, C double is a
511 * Cray single with 48 bits of precision, and long has 64
512 * bits.
513 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000514#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000515 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
516 if (abs >> 48) {
517 /* Needs more than 48 bits. Make it take the
518 * PyLong path.
519 */
520 PyObject *result;
521 PyObject *ww = PyLong_FromLong(jj);
522
523 if (ww == NULL)
524 return NULL;
525 result = float_richcompare(v, ww, op);
526 Py_DECREF(ww);
527 return result;
528 }
529#endif
530 j = (double)jj;
531 assert((long)j == jj);
532 }
533
534 else if (PyLong_Check(w)) {
535 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
536 int wsign = _PyLong_Sign(w);
537 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000538 int exponent;
539
540 if (vsign != wsign) {
541 /* Magnitudes are irrelevant -- the signs alone
542 * determine the outcome.
543 */
544 i = (double)vsign;
545 j = (double)wsign;
546 goto Compare;
547 }
548 /* The signs are the same. */
549 /* Convert w to a double if it fits. In particular, 0 fits. */
550 nbits = _PyLong_NumBits(w);
551 if (nbits == (size_t)-1 && PyErr_Occurred()) {
552 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000553 * to hold the # of bits. Replace with little doubles
554 * that give the same outcome -- w is so large that
555 * its magnitude must exceed the magnitude of any
556 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000557 */
558 PyErr_Clear();
559 i = (double)vsign;
560 assert(wsign != 0);
561 j = wsign * 2.0;
562 goto Compare;
563 }
564 if (nbits <= 48) {
565 j = PyLong_AsDouble(w);
566 /* It's impossible that <= 48 bits overflowed. */
567 assert(j != -1.0 || ! PyErr_Occurred());
568 goto Compare;
569 }
570 assert(wsign != 0); /* else nbits was 0 */
571 assert(vsign != 0); /* if vsign were 0, then since wsign is
572 * not 0, we would have taken the
573 * vsign != wsign branch at the start */
574 /* We want to work with non-negative numbers. */
575 if (vsign < 0) {
576 /* "Multiply both sides" by -1; this also swaps the
577 * comparator.
578 */
579 i = -i;
580 op = _Py_SwappedOp[op];
581 }
582 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000583 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000584 /* exponent is the # of bits in v before the radix point;
585 * we know that nbits (the # of bits in w) > 48 at this point
586 */
587 if (exponent < 0 || (size_t)exponent < nbits) {
588 i = 1.0;
589 j = 2.0;
590 goto Compare;
591 }
592 if ((size_t)exponent > nbits) {
593 i = 2.0;
594 j = 1.0;
595 goto Compare;
596 }
597 /* v and w have the same number of bits before the radix
598 * point. Construct two longs that have the same comparison
599 * outcome.
600 */
601 {
602 double fracpart;
603 double intpart;
604 PyObject *result = NULL;
605 PyObject *one = NULL;
606 PyObject *vv = NULL;
607 PyObject *ww = w;
608
609 if (wsign < 0) {
610 ww = PyNumber_Negative(w);
611 if (ww == NULL)
612 goto Error;
613 }
614 else
615 Py_INCREF(ww);
616
617 fracpart = modf(i, &intpart);
618 vv = PyLong_FromDouble(intpart);
619 if (vv == NULL)
620 goto Error;
621
622 if (fracpart != 0.0) {
623 /* Shift left, and or a 1 bit into vv
624 * to represent the lost fraction.
625 */
626 PyObject *temp;
627
628 one = PyInt_FromLong(1);
629 if (one == NULL)
630 goto Error;
631
632 temp = PyNumber_Lshift(ww, one);
633 if (temp == NULL)
634 goto Error;
635 Py_DECREF(ww);
636 ww = temp;
637
638 temp = PyNumber_Lshift(vv, one);
639 if (temp == NULL)
640 goto Error;
641 Py_DECREF(vv);
642 vv = temp;
643
644 temp = PyNumber_Or(vv, one);
645 if (temp == NULL)
646 goto Error;
647 Py_DECREF(vv);
648 vv = temp;
649 }
650
651 r = PyObject_RichCompareBool(vv, ww, op);
652 if (r < 0)
653 goto Error;
654 result = PyBool_FromLong(r);
655 Error:
656 Py_XDECREF(vv);
657 Py_XDECREF(ww);
658 Py_XDECREF(one);
659 return result;
660 }
661 } /* else if (PyLong_Check(w)) */
662
663 else /* w isn't float, int, or long */
664 goto Unimplemented;
665
666 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000667 PyFPE_START_PROTECT("richcompare", return NULL)
668 switch (op) {
669 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000670 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000671 break;
672 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000673 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000674 break;
675 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000676 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000677 break;
678 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000679 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000680 break;
681 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000682 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000683 break;
684 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000685 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000686 break;
687 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000688 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000689 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000690
691 Unimplemented:
692 Py_INCREF(Py_NotImplemented);
693 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000694}
695
Guido van Rossum9bfef441993-03-29 10:43:31 +0000696static long
Fred Drakefd99de62000-07-09 05:02:18 +0000697float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000698{
Tim Peters39dce292000-08-15 03:34:48 +0000699 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000700}
701
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000702static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000703float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000704{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000705 double a,b;
706 CONVERT_TO_DOUBLE(v, a);
707 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000708 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000709 a = a + b;
710 PyFPE_END_PROTECT(a)
711 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712}
713
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000715float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000716{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000717 double a,b;
718 CONVERT_TO_DOUBLE(v, a);
719 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000720 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000721 a = a - b;
722 PyFPE_END_PROTECT(a)
723 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000724}
725
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000727float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000729 double a,b;
730 CONVERT_TO_DOUBLE(v, a);
731 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000732 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000733 a = a * b;
734 PyFPE_END_PROTECT(a)
735 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736}
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000739float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000740{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000741 double a,b;
742 CONVERT_TO_DOUBLE(v, a);
743 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000744#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000745 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000746 PyErr_SetString(PyExc_ZeroDivisionError,
747 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000748 return NULL;
749 }
Christian Heimes6f341092008-04-18 23:13:07 +0000750#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000751 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000752 a = a / b;
753 PyFPE_END_PROTECT(a)
754 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755}
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000758float_classic_div(PyObject *v, PyObject *w)
759{
760 double a,b;
761 CONVERT_TO_DOUBLE(v, a);
762 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000763 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000764 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
765 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000766#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000767 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000768 PyErr_SetString(PyExc_ZeroDivisionError,
769 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000770 return NULL;
771 }
Christian Heimes6f341092008-04-18 23:13:07 +0000772#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000773 PyFPE_START_PROTECT("divide", return 0)
774 a = a / b;
775 PyFPE_END_PROTECT(a)
776 return PyFloat_FromDouble(a);
777}
778
779static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000780float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000781{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000782 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000783 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000784 CONVERT_TO_DOUBLE(v, vx);
785 CONVERT_TO_DOUBLE(w, wx);
786#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000788 PyErr_SetString(PyExc_ZeroDivisionError,
789 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790 return NULL;
791 }
Christian Heimes6f341092008-04-18 23:13:07 +0000792#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000793 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000794 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000795 /* note: checking mod*wx < 0 is incorrect -- underflows to
796 0 if wx < sqrt(smallest nonzero double) */
797 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000798 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000799 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000800 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000801 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802}
803
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000805float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000806{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000807 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000808 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000809 CONVERT_TO_DOUBLE(v, vx);
810 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000811 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000813 return NULL;
814 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000815 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000816 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000817 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000818 exact multiple of wx. But this is fp arithmetic, and fp
819 vx - mod is an approximation; the result is that div may
820 not be an exact integral value after the division, although
821 it will always be very close to one.
822 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000823 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000824 if (mod) {
825 /* ensure the remainder has the same sign as the denominator */
826 if ((wx < 0) != (mod < 0)) {
827 mod += wx;
828 div -= 1.0;
829 }
830 }
831 else {
832 /* the remainder is zero, and in the presence of signed zeroes
833 fmod returns different results across platforms; ensure
834 it has the same sign as the denominator; we'd like to do
835 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000836 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000837 if (wx < 0.0)
838 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000839 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000840 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000841 if (div) {
842 floordiv = floor(div);
843 if (div - floordiv > 0.5)
844 floordiv += 1.0;
845 }
846 else {
847 /* div is zero - get the same sign as the true quotient */
848 div *= div; /* hide "div = +0" from optimizers */
849 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
850 }
851 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000852 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000853}
854
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000855static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000856float_floor_div(PyObject *v, PyObject *w)
857{
858 PyObject *t, *r;
859
860 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000861 if (t == NULL || t == Py_NotImplemented)
862 return t;
863 assert(PyTuple_CheckExact(t));
864 r = PyTuple_GET_ITEM(t, 0);
865 Py_INCREF(r);
866 Py_DECREF(t);
867 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000868}
869
870static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000871float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872{
873 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000874
875 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000876 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000877 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000878 return NULL;
879 }
880
Neil Schemenauer32117e52001-01-04 01:44:34 +0000881 CONVERT_TO_DOUBLE(v, iv);
882 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000883
884 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000885 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000886 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000887 }
Tim Peters96685bf2001-08-23 22:31:37 +0000888 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000889 if (iw < 0.0) {
890 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000891 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000892 return NULL;
893 }
894 return PyFloat_FromDouble(0.0);
895 }
Christian Heimes6f341092008-04-18 23:13:07 +0000896 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
897 return PyFloat_FromDouble(1.0);
898 }
Tim Peterse87568d2003-05-24 20:18:24 +0000899 if (iv < 0.0) {
900 /* Whether this is an error is a mess, and bumps into libm
901 * bugs so we have to figure it out ourselves.
902 */
903 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000904 PyErr_SetString(PyExc_ValueError, "negative number "
905 "cannot be raised to a fractional power");
906 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000907 }
908 /* iw is an exact integer, albeit perhaps a very large one.
909 * -1 raised to an exact integer should never be exceptional.
910 * Alas, some libms (chiefly glibc as of early 2003) return
911 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
912 * happen to be representable in a *C* integer. That's a
913 * bug; we let that slide in math.pow() (which currently
914 * reflects all platform accidents), but not for Python's **.
915 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000916 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000917 /* Return 1 if iw is even, -1 if iw is odd; there's
918 * no guarantee that any C integral type is big
919 * enough to hold iw, so we have to check this
920 * indirectly.
921 */
922 ix = floor(iw * 0.5) * 2.0;
923 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
924 }
925 /* Else iv != -1.0, and overflow or underflow are possible.
926 * Unless we're to write pow() ourselves, we have to trust
927 * the platform to do this correctly.
928 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000929 }
Tim Peters96685bf2001-08-23 22:31:37 +0000930 errno = 0;
931 PyFPE_START_PROTECT("pow", return NULL)
932 ix = pow(iv, iw);
933 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000934 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000935 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000936 /* We don't expect any errno value other than ERANGE, but
937 * the range of libm bugs appears unbounded.
938 */
Alex Martelli348dc882006-08-23 22:17:59 +0000939 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
940 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000941 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000942 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000944}
945
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000947float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000948{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000949 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000950}
951
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000952static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000953float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000954{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000955 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000956}
957
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000958static int
Fred Drakefd99de62000-07-09 05:02:18 +0000959float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000960{
961 return v->ob_fval != 0.0;
962}
963
Guido van Rossum234f9421993-06-17 12:35:49 +0000964static int
Fred Drakefd99de62000-07-09 05:02:18 +0000965float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000966{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000967 if (PyInt_Check(*pw)) {
968 long x = PyInt_AsLong(*pw);
969 *pw = PyFloat_FromDouble((double)x);
970 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000971 return 0;
972 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000973 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000974 double x = PyLong_AsDouble(*pw);
975 if (x == -1.0 && PyErr_Occurred())
976 return -1;
977 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000978 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000979 return 0;
980 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000981 else if (PyFloat_Check(*pw)) {
982 Py_INCREF(*pv);
983 Py_INCREF(*pw);
984 return 0;
985 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000986 return 1; /* Can't do it */
987}
988
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000990float_is_integer(PyObject *v)
991{
992 double x = PyFloat_AsDouble(v);
993 PyObject *o;
994
995 if (x == -1.0 && PyErr_Occurred())
996 return NULL;
997 if (!Py_IS_FINITE(x))
998 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +0000999 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +00001000 PyFPE_START_PROTECT("is_integer", return NULL)
1001 o = (floor(x) == x) ? Py_True : Py_False;
1002 PyFPE_END_PROTECT(x)
1003 if (errno != 0) {
1004 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1005 PyExc_ValueError);
1006 return NULL;
1007 }
1008 Py_INCREF(o);
1009 return o;
1010}
1011
1012#if 0
1013static PyObject *
1014float_is_inf(PyObject *v)
1015{
1016 double x = PyFloat_AsDouble(v);
1017 if (x == -1.0 && PyErr_Occurred())
1018 return NULL;
1019 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1020}
1021
1022static PyObject *
1023float_is_nan(PyObject *v)
1024{
1025 double x = PyFloat_AsDouble(v);
1026 if (x == -1.0 && PyErr_Occurred())
1027 return NULL;
1028 return PyBool_FromLong((long)Py_IS_NAN(x));
1029}
1030
1031static PyObject *
1032float_is_finite(PyObject *v)
1033{
1034 double x = PyFloat_AsDouble(v);
1035 if (x == -1.0 && PyErr_Occurred())
1036 return NULL;
1037 return PyBool_FromLong((long)Py_IS_FINITE(x));
1038}
1039#endif
1040
1041static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001042float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001043{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001044 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001045 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001046
1047 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001048 /* Try to get out cheap if this fits in a Python int. The attempt
1049 * to cast to long must be protected, as C doesn't define what
1050 * happens if the double is too big to fit in a long. Some rare
1051 * systems raise an exception then (RISCOS was mentioned as one,
1052 * and someone using a non-default option on Sun also bumped into
1053 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1054 * still be vulnerable: if a long has more bits of precision than
1055 * a double, casting MIN/MAX to double may yield an approximation,
1056 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1057 * yield true from the C expression wholepart<=LONG_MAX, despite
1058 * that wholepart is actually greater than LONG_MAX.
1059 */
1060 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1061 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001062 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001063 }
1064 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001065}
1066
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001067static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001068float_long(PyObject *v)
1069{
1070 double x = PyFloat_AsDouble(v);
1071 return PyLong_FromDouble(x);
1072}
1073
1074static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001075float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001076{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001077 if (PyFloat_CheckExact(v))
1078 Py_INCREF(v);
1079 else
1080 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001081 return v;
1082}
1083
Mark Dickinson7103aa42008-07-15 19:08:33 +00001084/* turn ASCII hex characters into integer values and vice versa */
1085
1086static char
1087char_from_hex(int x)
1088{
1089 assert(0 <= x && x < 16);
1090 return "0123456789abcdef"[x];
1091}
1092
1093static int
1094hex_from_char(char c) {
1095 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001096 switch(c) {
1097 case '0':
1098 x = 0;
1099 break;
1100 case '1':
1101 x = 1;
1102 break;
1103 case '2':
1104 x = 2;
1105 break;
1106 case '3':
1107 x = 3;
1108 break;
1109 case '4':
1110 x = 4;
1111 break;
1112 case '5':
1113 x = 5;
1114 break;
1115 case '6':
1116 x = 6;
1117 break;
1118 case '7':
1119 x = 7;
1120 break;
1121 case '8':
1122 x = 8;
1123 break;
1124 case '9':
1125 x = 9;
1126 break;
1127 case 'a':
1128 case 'A':
1129 x = 10;
1130 break;
1131 case 'b':
1132 case 'B':
1133 x = 11;
1134 break;
1135 case 'c':
1136 case 'C':
1137 x = 12;
1138 break;
1139 case 'd':
1140 case 'D':
1141 x = 13;
1142 break;
1143 case 'e':
1144 case 'E':
1145 x = 14;
1146 break;
1147 case 'f':
1148 case 'F':
1149 x = 15;
1150 break;
1151 default:
1152 x = -1;
1153 break;
1154 }
1155 return x;
1156}
1157
1158/* convert a float to a hexadecimal string */
1159
1160/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1161 of the form 4k+1. */
1162#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1163
1164static PyObject *
1165float_hex(PyObject *v)
1166{
1167 double x, m;
1168 int e, shift, i, si, esign;
1169 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1170 trailing NUL byte. */
1171 char s[(TOHEX_NBITS-1)/4+3];
1172
1173 CONVERT_TO_DOUBLE(v, x);
1174
1175 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1176 return float_str((PyFloatObject *)v);
1177
1178 if (x == 0.0) {
1179 if(copysign(1.0, x) == -1.0)
1180 return PyString_FromString("-0x0.0p+0");
1181 else
1182 return PyString_FromString("0x0.0p+0");
1183 }
1184
1185 m = frexp(fabs(x), &e);
1186 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1187 m = ldexp(m, shift);
1188 e -= shift;
1189
1190 si = 0;
1191 s[si] = char_from_hex((int)m);
1192 si++;
1193 m -= (int)m;
1194 s[si] = '.';
1195 si++;
1196 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1197 m *= 16.0;
1198 s[si] = char_from_hex((int)m);
1199 si++;
1200 m -= (int)m;
1201 }
1202 s[si] = '\0';
1203
1204 if (e < 0) {
1205 esign = (int)'-';
1206 e = -e;
1207 }
1208 else
1209 esign = (int)'+';
1210
1211 if (x < 0.0)
1212 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1213 else
1214 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1215}
1216
1217PyDoc_STRVAR(float_hex_doc,
1218"float.hex() -> string\n\
1219\n\
1220Return a hexadecimal representation of a floating-point number.\n\
1221>>> (-0.1).hex()\n\
1222'-0x1.999999999999ap-4'\n\
1223>>> 3.14159.hex()\n\
1224'0x1.921f9f01b866ep+1'");
1225
1226/* Convert a hexadecimal string to a float. */
1227
1228static PyObject *
1229float_fromhex(PyObject *cls, PyObject *arg)
1230{
1231 PyObject *result_as_float, *result;
1232 double x;
1233 long exp, top_exp, lsb, key_digit;
1234 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1235 int half_eps, digit, round_up, sign=1;
1236 Py_ssize_t length, ndigits, fdigits, i;
1237
1238 /*
1239 * For the sake of simplicity and correctness, we impose an artificial
1240 * limit on ndigits, the total number of hex digits in the coefficient
1241 * The limit is chosen to ensure that, writing exp for the exponent,
1242 *
1243 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1244 * guaranteed to overflow (provided it's nonzero)
1245 *
1246 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1247 * guaranteed to underflow to 0.
1248 *
1249 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1250 * overflow in the calculation of exp and top_exp below.
1251 *
1252 * More specifically, ndigits is assumed to satisfy the following
1253 * inequalities:
1254 *
1255 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1256 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1257 *
1258 * If either of these inequalities is not satisfied, a ValueError is
1259 * raised. Otherwise, write x for the value of the hex string, and
1260 * assume x is nonzero. Then
1261 *
1262 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1263 *
1264 * Now if exp > LONG_MAX/2 then:
1265 *
1266 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1267 * = DBL_MAX_EXP
1268 *
1269 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1270 * double, so overflows. If exp < LONG_MIN/2, then
1271 *
1272 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1273 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1274 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1275 *
1276 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1277 * when converted to a C double.
1278 *
1279 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1280 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1281 */
1282
1283 if (PyString_AsStringAndSize(arg, &s, &length))
1284 return NULL;
1285 s_end = s + length;
1286
1287 /********************
1288 * Parse the string *
1289 ********************/
1290
1291 /* leading whitespace and optional sign */
1292 while (isspace(*s))
1293 s++;
1294 if (*s == '-') {
1295 s++;
1296 sign = -1;
1297 }
1298 else if (*s == '+')
1299 s++;
1300
1301 /* infinities and nans */
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001302 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001303 x = Py_NAN;
1304 goto finished;
1305 }
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001306 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1307 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001308 x = sign*Py_HUGE_VAL;
1309 goto finished;
1310 }
1311
1312 /* [0x] */
1313 s_store = s;
1314 if (*s == '0') {
1315 s++;
1316 if (tolower(*s) == (int)'x')
1317 s++;
1318 else
1319 s = s_store;
1320 }
1321
1322 /* coefficient: <integer> [. <fraction>] */
1323 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001324 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001325 s++;
1326 s_store = s;
1327 if (*s == '.') {
1328 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001329 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001330 s++;
1331 coeff_end = s-1;
1332 }
1333 else
1334 coeff_end = s;
1335
1336 /* ndigits = total # of hex digits; fdigits = # after point */
1337 ndigits = coeff_end - coeff_start;
1338 fdigits = coeff_end - s_store;
1339 if (ndigits == 0)
1340 goto parse_error;
1341 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1342 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1343 goto insane_length_error;
1344
1345 /* [p <exponent>] */
1346 if (tolower(*s) == (int)'p') {
1347 s++;
1348 exp_start = s;
1349 if (*s == '-' || *s == '+')
1350 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001351 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001352 goto parse_error;
1353 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001354 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001355 s++;
1356 exp = strtol(exp_start, NULL, 10);
1357 }
1358 else
1359 exp = 0;
1360
1361 /* optional trailing whitespace leading to the end of the string */
1362 while (isspace(*s))
1363 s++;
1364 if (s != s_end)
1365 goto parse_error;
1366
1367/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1368#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1369 coeff_end-(j) : \
1370 coeff_end-1-(j)))
1371
1372 /*******************************************
1373 * Compute rounded value of the hex string *
1374 *******************************************/
1375
1376 /* Discard leading zeros, and catch extreme overflow and underflow */
1377 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1378 ndigits--;
1379 if (ndigits == 0 || exp < LONG_MIN/2) {
1380 x = sign * 0.0;
1381 goto finished;
1382 }
1383 if (exp > LONG_MAX/2)
1384 goto overflow_error;
1385
1386 /* Adjust exponent for fractional part. */
1387 exp = exp - 4*((long)fdigits);
1388
1389 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1390 top_exp = exp + 4*((long)ndigits - 1);
1391 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1392 top_exp++;
1393
1394 /* catch almost all nonextreme cases of overflow and underflow here */
1395 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1396 x = sign * 0.0;
1397 goto finished;
1398 }
1399 if (top_exp > DBL_MAX_EXP)
1400 goto overflow_error;
1401
1402 /* lsb = exponent of least significant bit of the *rounded* value.
1403 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1404 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1405
1406 x = 0.0;
1407 if (exp >= lsb) {
1408 /* no rounding required */
1409 for (i = ndigits-1; i >= 0; i--)
1410 x = 16.0*x + HEX_DIGIT(i);
1411 x = sign * ldexp(x, (int)(exp));
1412 goto finished;
1413 }
1414 /* rounding required. key_digit is the index of the hex digit
1415 containing the first bit to be rounded away. */
1416 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1417 key_digit = (lsb - exp - 1) / 4;
1418 for (i = ndigits-1; i > key_digit; i--)
1419 x = 16.0*x + HEX_DIGIT(i);
1420 digit = HEX_DIGIT(key_digit);
1421 x = 16.0*x + (double)(digit & (16-2*half_eps));
1422
1423 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1424 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1425 if ((digit & half_eps) != 0) {
1426 round_up = 0;
1427 if ((digit & (3*half_eps-1)) != 0 ||
1428 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1429 round_up = 1;
1430 else
1431 for (i = key_digit-1; i >= 0; i--)
1432 if (HEX_DIGIT(i) != 0) {
1433 round_up = 1;
1434 break;
1435 }
1436 if (round_up == 1) {
1437 x += 2*half_eps;
1438 if (top_exp == DBL_MAX_EXP &&
1439 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1440 /* overflow corner case: pre-rounded value <
1441 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1442 goto overflow_error;
1443 }
1444 }
1445 x = sign * ldexp(x, (int)(exp+4*key_digit));
1446
1447 finished:
1448 result_as_float = Py_BuildValue("(d)", x);
1449 if (result_as_float == NULL)
1450 return NULL;
1451 result = PyObject_CallObject(cls, result_as_float);
1452 Py_DECREF(result_as_float);
1453 return result;
1454
1455 overflow_error:
1456 PyErr_SetString(PyExc_OverflowError,
1457 "hexadecimal value too large to represent as a float");
1458 return NULL;
1459
1460 parse_error:
1461 PyErr_SetString(PyExc_ValueError,
1462 "invalid hexadecimal floating-point string");
1463 return NULL;
1464
1465 insane_length_error:
1466 PyErr_SetString(PyExc_ValueError,
1467 "hexadecimal string too long to convert");
1468 return NULL;
1469}
1470
1471PyDoc_STRVAR(float_fromhex_doc,
1472"float.fromhex(string) -> float\n\
1473\n\
1474Create a floating-point number from a hexadecimal string.\n\
1475>>> float.fromhex('0x1.ffffp10')\n\
14762047.984375\n\
1477>>> float.fromhex('-0x1p-1074')\n\
1478-4.9406564584124654e-324");
1479
1480
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001481static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001482float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001483{
1484 double self;
1485 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001486 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001487 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001488
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001489 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001490 PyObject *py_exponent = NULL;
1491 PyObject *numerator = NULL;
1492 PyObject *denominator = NULL;
1493 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001494 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001495
1496#define INPLACE_UPDATE(obj, call) \
1497 prev = obj; \
1498 obj = call; \
1499 Py_DECREF(prev); \
1500
1501 CONVERT_TO_DOUBLE(v, self);
1502
1503 if (Py_IS_INFINITY(self)) {
1504 PyErr_SetString(PyExc_OverflowError,
1505 "Cannot pass infinity to float.as_integer_ratio.");
1506 return NULL;
1507 }
1508#ifdef Py_NAN
1509 if (Py_IS_NAN(self)) {
1510 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001511 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001512 return NULL;
1513 }
1514#endif
1515
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001516 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001517 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001518 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001519
Raymond Hettingerf9859032008-02-01 23:45:44 +00001520 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001521 float_part *= 2.0;
1522 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001523 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001524 /* self == float_part * 2**exponent exactly and float_part is integral.
1525 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1526 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001527
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001528 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001529 if (numerator == NULL) goto error;
1530
Raymond Hettingerf9859032008-02-01 23:45:44 +00001531 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001532 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001533 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001534 if (py_exponent == NULL) goto error;
1535 INPLACE_UPDATE(py_exponent,
1536 long_methods->nb_lshift(denominator, py_exponent));
1537 if (py_exponent == NULL) goto error;
1538 if (exponent > 0) {
1539 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001540 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001541 if (numerator == NULL) goto error;
1542 }
1543 else {
1544 Py_DECREF(denominator);
1545 denominator = py_exponent;
1546 py_exponent = NULL;
1547 }
1548
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001549 /* Returns ints instead of longs where possible */
1550 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1551 if (numerator == NULL) goto error;
1552 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1553 if (denominator == NULL) goto error;
1554
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001555 result_pair = PyTuple_Pack(2, numerator, denominator);
1556
1557#undef INPLACE_UPDATE
1558error:
1559 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001560 Py_XDECREF(denominator);
1561 Py_XDECREF(numerator);
1562 return result_pair;
1563}
1564
1565PyDoc_STRVAR(float_as_integer_ratio_doc,
1566"float.as_integer_ratio() -> (int, int)\n"
1567"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001568"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1569"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001570"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001571"\n"
1572">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001573"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001574">>> (0.0).as_integer_ratio()\n"
1575"(0, 1)\n"
1576">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001577"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001578
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001579
Jeremy Hylton938ace62002-07-17 16:30:39 +00001580static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001581float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1582
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583static PyObject *
1584float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1585{
1586 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001587 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588
Guido van Rossumbef14172001-08-29 15:47:46 +00001589 if (type != &PyFloat_Type)
1590 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1592 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001593 /* If it's a string, but not a string subclass, use
1594 PyFloat_FromString. */
1595 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 return PyFloat_FromString(x, NULL);
1597 return PyNumber_Float(x);
1598}
1599
Guido van Rossumbef14172001-08-29 15:47:46 +00001600/* Wimpy, slow approach to tp_new calls for subtypes of float:
1601 first create a regular float from whatever arguments we got,
1602 then allocate a subtype instance and initialize its ob_fval
1603 from the regular float. The regular float is then thrown away.
1604*/
1605static PyObject *
1606float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1607{
Anthony Baxter377be112006-04-11 06:54:30 +00001608 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001609
1610 assert(PyType_IsSubtype(type, &PyFloat_Type));
1611 tmp = float_new(&PyFloat_Type, args, kwds);
1612 if (tmp == NULL)
1613 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001614 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001615 newobj = type->tp_alloc(type, 0);
1616 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001617 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001618 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001619 }
Anthony Baxter377be112006-04-11 06:54:30 +00001620 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001621 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001622 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001623}
1624
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001625static PyObject *
1626float_getnewargs(PyFloatObject *v)
1627{
1628 return Py_BuildValue("(d)", v->ob_fval);
1629}
1630
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001631/* this is for the benefit of the pack/unpack routines below */
1632
1633typedef enum {
1634 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1635} float_format_type;
1636
1637static float_format_type double_format, float_format;
1638static float_format_type detected_double_format, detected_float_format;
1639
1640static PyObject *
1641float_getformat(PyTypeObject *v, PyObject* arg)
1642{
1643 char* s;
1644 float_format_type r;
1645
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001646 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001647 PyErr_Format(PyExc_TypeError,
1648 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001649 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001650 return NULL;
1651 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001652 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001653 if (strcmp(s, "double") == 0) {
1654 r = double_format;
1655 }
1656 else if (strcmp(s, "float") == 0) {
1657 r = float_format;
1658 }
1659 else {
1660 PyErr_SetString(PyExc_ValueError,
1661 "__getformat__() argument 1 must be "
1662 "'double' or 'float'");
1663 return NULL;
1664 }
1665
1666 switch (r) {
1667 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001668 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001669 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001670 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001672 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673 default:
1674 Py_FatalError("insane float_format or double_format");
1675 return NULL;
1676 }
1677}
1678
1679PyDoc_STRVAR(float_getformat_doc,
1680"float.__getformat__(typestr) -> string\n"
1681"\n"
1682"You probably don't want to use this function. It exists mainly to be\n"
1683"used in Python's test suite.\n"
1684"\n"
1685"typestr must be 'double' or 'float'. This function returns whichever of\n"
1686"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1687"format of floating point numbers used by the C type named by typestr.");
1688
1689static PyObject *
1690float_setformat(PyTypeObject *v, PyObject* args)
1691{
1692 char* typestr;
1693 char* format;
1694 float_format_type f;
1695 float_format_type detected;
1696 float_format_type *p;
1697
1698 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1699 return NULL;
1700
1701 if (strcmp(typestr, "double") == 0) {
1702 p = &double_format;
1703 detected = detected_double_format;
1704 }
1705 else if (strcmp(typestr, "float") == 0) {
1706 p = &float_format;
1707 detected = detected_float_format;
1708 }
1709 else {
1710 PyErr_SetString(PyExc_ValueError,
1711 "__setformat__() argument 1 must "
1712 "be 'double' or 'float'");
1713 return NULL;
1714 }
1715
1716 if (strcmp(format, "unknown") == 0) {
1717 f = unknown_format;
1718 }
1719 else if (strcmp(format, "IEEE, little-endian") == 0) {
1720 f = ieee_little_endian_format;
1721 }
1722 else if (strcmp(format, "IEEE, big-endian") == 0) {
1723 f = ieee_big_endian_format;
1724 }
1725 else {
1726 PyErr_SetString(PyExc_ValueError,
1727 "__setformat__() argument 2 must be "
1728 "'unknown', 'IEEE, little-endian' or "
1729 "'IEEE, big-endian'");
1730 return NULL;
1731
1732 }
1733
1734 if (f != unknown_format && f != detected) {
1735 PyErr_Format(PyExc_ValueError,
1736 "can only set %s format to 'unknown' or the "
1737 "detected platform value", typestr);
1738 return NULL;
1739 }
1740
1741 *p = f;
1742 Py_RETURN_NONE;
1743}
1744
1745PyDoc_STRVAR(float_setformat_doc,
1746"float.__setformat__(typestr, fmt) -> None\n"
1747"\n"
1748"You probably don't want to use this function. It exists mainly to be\n"
1749"used in Python's test suite.\n"
1750"\n"
1751"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1752"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1753"one of the latter two if it appears to match the underlying C reality.\n"
1754"\n"
1755"Overrides the automatic determination of C-level floating point type.\n"
1756"This affects how floats are converted to and from binary strings.");
1757
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001758static PyObject *
1759float_getzero(PyObject *v, void *closure)
1760{
1761 return PyFloat_FromDouble(0.0);
1762}
1763
Eric Smitha9f7d622008-02-17 19:46:49 +00001764static PyObject *
1765float__format__(PyObject *self, PyObject *args)
1766{
1767 PyObject *format_spec;
1768
1769 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1770 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001771 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001772 return _PyFloat_FormatAdvanced(self,
1773 PyBytes_AS_STRING(format_spec),
1774 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001775 if (PyUnicode_Check(format_spec)) {
1776 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001777 PyObject *result;
1778 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001779
Eric Smithdc13b792008-05-30 18:10:04 +00001780 if (str_spec == NULL)
1781 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001782
Eric Smithdc13b792008-05-30 18:10:04 +00001783 result = _PyFloat_FormatAdvanced(self,
1784 PyBytes_AS_STRING(str_spec),
1785 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001786
Eric Smithdc13b792008-05-30 18:10:04 +00001787 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001788 return result;
1789 }
1790 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1791 return NULL;
1792}
1793
1794PyDoc_STRVAR(float__format__doc,
1795"float.__format__(format_spec) -> string\n"
1796"\n"
1797"Formats the float according to format_spec.");
1798
1799
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001800static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001801 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001802 "Returns self, the complex conjugate of any float."},
1803 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1804 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001805 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1806 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001807 {"fromhex", (PyCFunction)float_fromhex,
1808 METH_O|METH_CLASS, float_fromhex_doc},
1809 {"hex", (PyCFunction)float_hex,
1810 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001811 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1812 "Returns True if the float is an integer."},
1813#if 0
1814 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1815 "Returns True if the float is positive or negative infinite."},
1816 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1817 "Returns True if the float is finite, neither infinite nor NaN."},
1818 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1819 "Returns True if the float is not a number (NaN)."},
1820#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001821 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001822 {"__getformat__", (PyCFunction)float_getformat,
1823 METH_O|METH_CLASS, float_getformat_doc},
1824 {"__setformat__", (PyCFunction)float_setformat,
1825 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001826 {"__format__", (PyCFunction)float__format__,
1827 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001828 {NULL, NULL} /* sentinel */
1829};
1830
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001831static PyGetSetDef float_getset[] = {
1832 {"real",
1833 (getter)float_float, (setter)NULL,
1834 "the real part of a complex number",
1835 NULL},
1836 {"imag",
1837 (getter)float_getzero, (setter)NULL,
1838 "the imaginary part of a complex number",
1839 NULL},
1840 {NULL} /* Sentinel */
1841};
1842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001843PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844"float(x) -> floating point number\n\
1845\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001846Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847
1848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001850 float_add, /*nb_add*/
1851 float_sub, /*nb_subtract*/
1852 float_mul, /*nb_multiply*/
1853 float_classic_div, /*nb_divide*/
1854 float_rem, /*nb_remainder*/
1855 float_divmod, /*nb_divmod*/
1856 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001857 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001858 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001859 (unaryfunc)float_abs, /*nb_absolute*/
1860 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001861 0, /*nb_invert*/
1862 0, /*nb_lshift*/
1863 0, /*nb_rshift*/
1864 0, /*nb_and*/
1865 0, /*nb_xor*/
1866 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001867 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001868 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001869 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001870 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001871 0, /* nb_oct */
1872 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001873 0, /* nb_inplace_add */
1874 0, /* nb_inplace_subtract */
1875 0, /* nb_inplace_multiply */
1876 0, /* nb_inplace_divide */
1877 0, /* nb_inplace_remainder */
1878 0, /* nb_inplace_power */
1879 0, /* nb_inplace_lshift */
1880 0, /* nb_inplace_rshift */
1881 0, /* nb_inplace_and */
1882 0, /* nb_inplace_xor */
1883 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001884 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001885 float_div, /* nb_true_divide */
1886 0, /* nb_inplace_floor_divide */
1887 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001888};
1889
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001890PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001891 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001893 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001894 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895 (destructor)float_dealloc, /* tp_dealloc */
1896 (printfunc)float_print, /* tp_print */
1897 0, /* tp_getattr */
1898 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001899 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900 (reprfunc)float_repr, /* tp_repr */
1901 &float_as_number, /* tp_as_number */
1902 0, /* tp_as_sequence */
1903 0, /* tp_as_mapping */
1904 (hashfunc)float_hash, /* tp_hash */
1905 0, /* tp_call */
1906 (reprfunc)float_str, /* tp_str */
1907 PyObject_GenericGetAttr, /* tp_getattro */
1908 0, /* tp_setattro */
1909 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001910 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1911 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912 float_doc, /* tp_doc */
1913 0, /* tp_traverse */
1914 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001915 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 0, /* tp_weaklistoffset */
1917 0, /* tp_iter */
1918 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001919 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001921 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 0, /* tp_base */
1923 0, /* tp_dict */
1924 0, /* tp_descr_get */
1925 0, /* tp_descr_set */
1926 0, /* tp_dictoffset */
1927 0, /* tp_init */
1928 0, /* tp_alloc */
1929 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001930};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001931
1932void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001933_PyFloat_Init(void)
1934{
1935 /* We attempt to determine if this machine is using IEEE
1936 floating point formats by peering at the bits of some
1937 carefully chosen values. If it looks like we are on an
1938 IEEE platform, the float packing/unpacking routines can
1939 just copy bits, if not they resort to arithmetic & shifts
1940 and masks. The shifts & masks approach works on all finite
1941 values, but what happens to infinities, NaNs and signed
1942 zeroes on packing is an accident, and attempting to unpack
1943 a NaN or an infinity will raise an exception.
1944
1945 Note that if we're on some whacked-out platform which uses
1946 IEEE formats but isn't strictly little-endian or big-
1947 endian, we will fall back to the portable shifts & masks
1948 method. */
1949
1950#if SIZEOF_DOUBLE == 8
1951 {
1952 double x = 9006104071832581.0;
1953 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1954 detected_double_format = ieee_big_endian_format;
1955 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1956 detected_double_format = ieee_little_endian_format;
1957 else
1958 detected_double_format = unknown_format;
1959 }
1960#else
1961 detected_double_format = unknown_format;
1962#endif
1963
1964#if SIZEOF_FLOAT == 4
1965 {
1966 float y = 16711938.0;
1967 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1968 detected_float_format = ieee_big_endian_format;
1969 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1970 detected_float_format = ieee_little_endian_format;
1971 else
1972 detected_float_format = unknown_format;
1973 }
1974#else
1975 detected_float_format = unknown_format;
1976#endif
1977
1978 double_format = detected_double_format;
1979 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001980
Christian Heimes796fc312008-01-30 18:58:29 +00001981 /* Init float info */
1982 if (FloatInfoType.tp_name == 0)
1983 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001984}
1985
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001986int
1987PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001988{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001989 PyFloatObject *p;
1990 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001991 int i;
1992 int u; /* remaining unfreed ints per block */
1993 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001994
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001995 list = block_list;
1996 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001997 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001998 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001999 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002000 for (i = 0, p = &list->objects[0];
2001 i < N_FLOATOBJECTS;
2002 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00002003 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002004 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002005 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002006 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002007 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002008 list->next = block_list;
2009 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002010 for (i = 0, p = &list->objects[0];
2011 i < N_FLOATOBJECTS;
2012 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002013 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00002014 Py_REFCNT(p) == 0) {
2015 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002016 free_list;
2017 free_list = p;
2018 }
2019 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002020 }
2021 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002022 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002023 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002024 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00002025 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002026 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002027 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002028}
2029
2030void
2031PyFloat_Fini(void)
2032{
2033 PyFloatObject *p;
2034 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002035 int i;
2036 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002037
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002038 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002039
Guido van Rossum3fce8831999-03-12 19:43:17 +00002040 if (!Py_VerboseFlag)
2041 return;
2042 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002043 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002044 fprintf(stderr, "\n");
2045 }
2046 else {
2047 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002048 ": %d unfreed float%s\n",
2049 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002050 }
2051 if (Py_VerboseFlag > 1) {
2052 list = block_list;
2053 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002054 for (i = 0, p = &list->objects[0];
2055 i < N_FLOATOBJECTS;
2056 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002057 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00002058 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002059 char buf[100];
2060 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002061 /* XXX(twouters) cast refcount to
2062 long until %zd is universally
2063 available
2064 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00002065 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002066 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002067 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00002068 }
2069 }
2070 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002071 }
2072 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002073}
Tim Peters9905b942003-03-20 20:53:32 +00002074
2075/*----------------------------------------------------------------------------
2076 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002077 */
2078int
2079_PyFloat_Pack4(double x, unsigned char *p, int le)
2080{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002081 if (float_format == unknown_format) {
2082 unsigned char sign;
2083 int e;
2084 double f;
2085 unsigned int fbits;
2086 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002087
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088 if (le) {
2089 p += 3;
2090 incr = -1;
2091 }
Tim Peters9905b942003-03-20 20:53:32 +00002092
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002093 if (x < 0) {
2094 sign = 1;
2095 x = -x;
2096 }
2097 else
2098 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002099
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002100 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002101
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102 /* Normalize f to be in the range [1.0, 2.0) */
2103 if (0.5 <= f && f < 1.0) {
2104 f *= 2.0;
2105 e--;
2106 }
2107 else if (f == 0.0)
2108 e = 0;
2109 else {
2110 PyErr_SetString(PyExc_SystemError,
2111 "frexp() result out of range");
2112 return -1;
2113 }
2114
2115 if (e >= 128)
2116 goto Overflow;
2117 else if (e < -126) {
2118 /* Gradual underflow */
2119 f = ldexp(f, 126 + e);
2120 e = 0;
2121 }
2122 else if (!(e == 0 && f == 0.0)) {
2123 e += 127;
2124 f -= 1.0; /* Get rid of leading 1 */
2125 }
2126
2127 f *= 8388608.0; /* 2**23 */
2128 fbits = (unsigned int)(f + 0.5); /* Round */
2129 assert(fbits <= 8388608);
2130 if (fbits >> 23) {
2131 /* The carry propagated out of a string of 23 1 bits. */
2132 fbits = 0;
2133 ++e;
2134 if (e >= 255)
2135 goto Overflow;
2136 }
2137
2138 /* First byte */
2139 *p = (sign << 7) | (e >> 1);
2140 p += incr;
2141
2142 /* Second byte */
2143 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2144 p += incr;
2145
2146 /* Third byte */
2147 *p = (fbits >> 8) & 0xFF;
2148 p += incr;
2149
2150 /* Fourth byte */
2151 *p = fbits & 0xFF;
2152
2153 /* Done */
2154 return 0;
2155
Tim Peters9905b942003-03-20 20:53:32 +00002156 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002157 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002158 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159 const char *s = (char*)&y;
2160 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002161
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002162 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2163 goto Overflow;
2164
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002165 if ((float_format == ieee_little_endian_format && !le)
2166 || (float_format == ieee_big_endian_format && le)) {
2167 p += 3;
2168 incr = -1;
2169 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002170
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171 for (i = 0; i < 4; i++) {
2172 *p = *s++;
2173 p += incr;
2174 }
2175 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002176 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002177 Overflow:
2178 PyErr_SetString(PyExc_OverflowError,
2179 "float too large to pack with f format");
2180 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002181}
2182
2183int
2184_PyFloat_Pack8(double x, unsigned char *p, int le)
2185{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002186 if (double_format == unknown_format) {
2187 unsigned char sign;
2188 int e;
2189 double f;
2190 unsigned int fhi, flo;
2191 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002192
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002193 if (le) {
2194 p += 7;
2195 incr = -1;
2196 }
Tim Peters9905b942003-03-20 20:53:32 +00002197
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002198 if (x < 0) {
2199 sign = 1;
2200 x = -x;
2201 }
2202 else
2203 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002204
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002205 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002206
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002207 /* Normalize f to be in the range [1.0, 2.0) */
2208 if (0.5 <= f && f < 1.0) {
2209 f *= 2.0;
2210 e--;
2211 }
2212 else if (f == 0.0)
2213 e = 0;
2214 else {
2215 PyErr_SetString(PyExc_SystemError,
2216 "frexp() result out of range");
2217 return -1;
2218 }
2219
2220 if (e >= 1024)
2221 goto Overflow;
2222 else if (e < -1022) {
2223 /* Gradual underflow */
2224 f = ldexp(f, 1022 + e);
2225 e = 0;
2226 }
2227 else if (!(e == 0 && f == 0.0)) {
2228 e += 1023;
2229 f -= 1.0; /* Get rid of leading 1 */
2230 }
2231
2232 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2233 f *= 268435456.0; /* 2**28 */
2234 fhi = (unsigned int)f; /* Truncate */
2235 assert(fhi < 268435456);
2236
2237 f -= (double)fhi;
2238 f *= 16777216.0; /* 2**24 */
2239 flo = (unsigned int)(f + 0.5); /* Round */
2240 assert(flo <= 16777216);
2241 if (flo >> 24) {
2242 /* The carry propagated out of a string of 24 1 bits. */
2243 flo = 0;
2244 ++fhi;
2245 if (fhi >> 28) {
2246 /* And it also progagated out of the next 28 bits. */
2247 fhi = 0;
2248 ++e;
2249 if (e >= 2047)
2250 goto Overflow;
2251 }
2252 }
2253
2254 /* First byte */
2255 *p = (sign << 7) | (e >> 4);
2256 p += incr;
2257
2258 /* Second byte */
2259 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2260 p += incr;
2261
2262 /* Third byte */
2263 *p = (fhi >> 16) & 0xFF;
2264 p += incr;
2265
2266 /* Fourth byte */
2267 *p = (fhi >> 8) & 0xFF;
2268 p += incr;
2269
2270 /* Fifth byte */
2271 *p = fhi & 0xFF;
2272 p += incr;
2273
2274 /* Sixth byte */
2275 *p = (flo >> 16) & 0xFF;
2276 p += incr;
2277
2278 /* Seventh byte */
2279 *p = (flo >> 8) & 0xFF;
2280 p += incr;
2281
2282 /* Eighth byte */
2283 *p = flo & 0xFF;
2284 p += incr;
2285
2286 /* Done */
2287 return 0;
2288
2289 Overflow:
2290 PyErr_SetString(PyExc_OverflowError,
2291 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002292 return -1;
2293 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294 else {
2295 const char *s = (char*)&x;
2296 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002297
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298 if ((double_format == ieee_little_endian_format && !le)
2299 || (double_format == ieee_big_endian_format && le)) {
2300 p += 7;
2301 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002302 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303
2304 for (i = 0; i < 8; i++) {
2305 *p = *s++;
2306 p += incr;
2307 }
2308 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002309 }
Tim Peters9905b942003-03-20 20:53:32 +00002310}
2311
2312double
2313_PyFloat_Unpack4(const unsigned char *p, int le)
2314{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315 if (float_format == unknown_format) {
2316 unsigned char sign;
2317 int e;
2318 unsigned int f;
2319 double x;
2320 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002321
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002322 if (le) {
2323 p += 3;
2324 incr = -1;
2325 }
2326
2327 /* First byte */
2328 sign = (*p >> 7) & 1;
2329 e = (*p & 0x7F) << 1;
2330 p += incr;
2331
2332 /* Second byte */
2333 e |= (*p >> 7) & 1;
2334 f = (*p & 0x7F) << 16;
2335 p += incr;
2336
2337 if (e == 255) {
2338 PyErr_SetString(
2339 PyExc_ValueError,
2340 "can't unpack IEEE 754 special value "
2341 "on non-IEEE platform");
2342 return -1;
2343 }
2344
2345 /* Third byte */
2346 f |= *p << 8;
2347 p += incr;
2348
2349 /* Fourth byte */
2350 f |= *p;
2351
2352 x = (double)f / 8388608.0;
2353
2354 /* XXX This sadly ignores Inf/NaN issues */
2355 if (e == 0)
2356 e = -126;
2357 else {
2358 x += 1.0;
2359 e -= 127;
2360 }
2361 x = ldexp(x, e);
2362
2363 if (sign)
2364 x = -x;
2365
2366 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002367 }
Tim Peters9905b942003-03-20 20:53:32 +00002368 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002369 float x;
2370
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002371 if ((float_format == ieee_little_endian_format && !le)
2372 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002373 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374 char *d = &buf[3];
2375 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002376
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002377 for (i = 0; i < 4; i++) {
2378 *d-- = *p++;
2379 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002380 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002381 }
2382 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002383 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002384 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002385
2386 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002387 }
Tim Peters9905b942003-03-20 20:53:32 +00002388}
2389
2390double
2391_PyFloat_Unpack8(const unsigned char *p, int le)
2392{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002393 if (double_format == unknown_format) {
2394 unsigned char sign;
2395 int e;
2396 unsigned int fhi, flo;
2397 double x;
2398 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002399
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002400 if (le) {
2401 p += 7;
2402 incr = -1;
2403 }
2404
2405 /* First byte */
2406 sign = (*p >> 7) & 1;
2407 e = (*p & 0x7F) << 4;
2408
2409 p += incr;
2410
2411 /* Second byte */
2412 e |= (*p >> 4) & 0xF;
2413 fhi = (*p & 0xF) << 24;
2414 p += incr;
2415
2416 if (e == 2047) {
2417 PyErr_SetString(
2418 PyExc_ValueError,
2419 "can't unpack IEEE 754 special value "
2420 "on non-IEEE platform");
2421 return -1.0;
2422 }
2423
2424 /* Third byte */
2425 fhi |= *p << 16;
2426 p += incr;
2427
2428 /* Fourth byte */
2429 fhi |= *p << 8;
2430 p += incr;
2431
2432 /* Fifth byte */
2433 fhi |= *p;
2434 p += incr;
2435
2436 /* Sixth byte */
2437 flo = *p << 16;
2438 p += incr;
2439
2440 /* Seventh byte */
2441 flo |= *p << 8;
2442 p += incr;
2443
2444 /* Eighth byte */
2445 flo |= *p;
2446
2447 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2448 x /= 268435456.0; /* 2**28 */
2449
2450 if (e == 0)
2451 e = -1022;
2452 else {
2453 x += 1.0;
2454 e -= 1023;
2455 }
2456 x = ldexp(x, e);
2457
2458 if (sign)
2459 x = -x;
2460
2461 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002462 }
Tim Peters9905b942003-03-20 20:53:32 +00002463 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002464 double x;
2465
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002466 if ((double_format == ieee_little_endian_format && !le)
2467 || (double_format == ieee_big_endian_format && le)) {
2468 char buf[8];
2469 char *d = &buf[7];
2470 int i;
2471
2472 for (i = 0; i < 8; i++) {
2473 *d-- = *p++;
2474 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002475 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002476 }
2477 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002478 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002479 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002480
2481 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002482 }
Tim Peters9905b942003-03-20 20:53:32 +00002483}