blob: 1bfc57edfb4e87f0faba9a6c01080ebc8a33a635 [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__,
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +000075"sys.float_info\n\
Christian Heimesc94e2b52008-01-14 04:13:37 +000076\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 = {
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +0000102 "sys.float_info", /* name */
Christian Heimesc94e2b52008-01-14 04:13:37 +0000103 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
Mark Dickinson777e4ff2009-05-03 20:59:48 +0000217 while (Py_ISSPACE(*s))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 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. */
Mark Dickinson777e4ff2009-05-03 20:59:48 +0000238 while (Py_ISSPACE(*end))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000239 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
Neil Schemenauer32117e52001-01-04 01:44:34 +0000302/* Macro and helper that convert PyObject obj to a C double and store
303 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000304 slot function. If conversion to double raises an exception, obj is
305 set to NULL, and the function invoking this macro returns NULL. If
306 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
307 stored in obj, and returned from the function invoking this macro.
308*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000309#define CONVERT_TO_DOUBLE(obj, dbl) \
310 if (PyFloat_Check(obj)) \
311 dbl = PyFloat_AS_DOUBLE(obj); \
312 else if (convert_to_double(&(obj), &(dbl)) < 0) \
313 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000314
315static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000316convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000317{
318 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000319
Neil Schemenauer32117e52001-01-04 01:44:34 +0000320 if (PyInt_Check(obj)) {
321 *dbl = (double)PyInt_AS_LONG(obj);
322 }
323 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000324 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000325 if (*dbl == -1.0 && PyErr_Occurred()) {
326 *v = NULL;
327 return -1;
328 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000329 }
330 else {
331 Py_INCREF(Py_NotImplemented);
332 *v = Py_NotImplemented;
333 return -1;
334 }
335 return 0;
336}
337
Eric Smithcfaf79c2009-10-26 14:48:55 +0000338/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
Tim Peters97019e42001-11-28 22:43:45 +0000339 XXX they pass a char buffer without passing a length.
340*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000341void
Fred Drakefd99de62000-07-09 05:02:18 +0000342PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000343{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000344 char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
345 PyFloat_STR_PRECISION,
346 Py_DTSF_ADD_DOT_0, NULL);
347 strcpy(buf, tmp);
348 PyMem_Free(tmp);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000349}
350
Tim Peters72f98e92001-05-08 15:19:57 +0000351void
352PyFloat_AsReprString(char *buf, PyFloatObject *v)
353{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000354 char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
355 Py_DTSF_ADD_DOT_0, NULL);
356 strcpy(buf, tmp);
357 PyMem_Free(tmp);
Tim Peters72f98e92001-05-08 15:19:57 +0000358}
359
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000360/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000361static int
Fred Drakefd99de62000-07-09 05:02:18 +0000362float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000364 char *buf;
365 if (flags & Py_PRINT_RAW)
366 buf = PyOS_double_to_string(v->ob_fval,
367 'g', PyFloat_STR_PRECISION,
368 Py_DTSF_ADD_DOT_0, NULL);
369 else
370 buf = PyOS_double_to_string(v->ob_fval,
371 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
Brett Cannon01531592007-09-17 03:28:34 +0000372 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000374 Py_END_ALLOW_THREADS
Eric Smithcfaf79c2009-10-26 14:48:55 +0000375 PyMem_Free(buf);
Guido van Rossum90933611991-06-07 16:10:43 +0000376 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377}
378
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000379static PyObject *
Eric Smithcfaf79c2009-10-26 14:48:55 +0000380float_str_or_repr(PyFloatObject *v, int precision, char format_code)
381{
382 PyObject *result;
383 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
384 format_code, precision,
385 Py_DTSF_ADD_DOT_0,
386 NULL);
387 if (!buf)
388 return PyErr_NoMemory();
389 result = PyString_FromString(buf);
390 PyMem_Free(buf);
391 return result;
392}
393
394static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000395float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000397 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000398}
399
400static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000401float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000402{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000403 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Tim Peters307fa782004-09-23 08:06:40 +0000406/* Comparison is pretty much a nightmare. When comparing float to float,
407 * we do it as straightforwardly (and long-windedly) as conceivable, so
408 * that, e.g., Python x == y delivers the same result as the platform
409 * C x == y when x and/or y is a NaN.
410 * When mixing float with an integer type, there's no good *uniform* approach.
411 * Converting the double to an integer obviously doesn't work, since we
412 * may lose info from fractional bits. Converting the integer to a double
413 * also has two failure modes: (1) a long int may trigger overflow (too
414 * large to fit in the dynamic range of a C double); (2) even a C long may have
415 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
416 * 63 bits of precision, but a C double probably has only 53), and then
417 * we can falsely claim equality when low-order integer bits are lost by
418 * coercion to double. So this part is painful too.
419 */
420
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000421static PyObject*
422float_richcompare(PyObject *v, PyObject *w, int op)
423{
424 double i, j;
425 int r = 0;
426
Tim Peters307fa782004-09-23 08:06:40 +0000427 assert(PyFloat_Check(v));
428 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000429
Tim Peters307fa782004-09-23 08:06:40 +0000430 /* Switch on the type of w. Set i and j to doubles to be compared,
431 * and op to the richcomp to use.
432 */
433 if (PyFloat_Check(w))
434 j = PyFloat_AS_DOUBLE(w);
435
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000436 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000437 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000438 /* If i is an infinity, its magnitude exceeds any
439 * finite integer, so it doesn't matter which int we
440 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000441 */
442 j = 0.0;
443 else
444 goto Unimplemented;
445 }
446
447 else if (PyInt_Check(w)) {
448 long jj = PyInt_AS_LONG(w);
449 /* In the worst realistic case I can imagine, C double is a
450 * Cray single with 48 bits of precision, and long has 64
451 * bits.
452 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000453#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000454 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
455 if (abs >> 48) {
456 /* Needs more than 48 bits. Make it take the
457 * PyLong path.
458 */
459 PyObject *result;
460 PyObject *ww = PyLong_FromLong(jj);
461
462 if (ww == NULL)
463 return NULL;
464 result = float_richcompare(v, ww, op);
465 Py_DECREF(ww);
466 return result;
467 }
468#endif
469 j = (double)jj;
470 assert((long)j == jj);
471 }
472
473 else if (PyLong_Check(w)) {
474 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
475 int wsign = _PyLong_Sign(w);
476 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000477 int exponent;
478
479 if (vsign != wsign) {
480 /* Magnitudes are irrelevant -- the signs alone
481 * determine the outcome.
482 */
483 i = (double)vsign;
484 j = (double)wsign;
485 goto Compare;
486 }
487 /* The signs are the same. */
488 /* Convert w to a double if it fits. In particular, 0 fits. */
489 nbits = _PyLong_NumBits(w);
490 if (nbits == (size_t)-1 && PyErr_Occurred()) {
491 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000492 * to hold the # of bits. Replace with little doubles
493 * that give the same outcome -- w is so large that
494 * its magnitude must exceed the magnitude of any
495 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000496 */
497 PyErr_Clear();
498 i = (double)vsign;
499 assert(wsign != 0);
500 j = wsign * 2.0;
501 goto Compare;
502 }
503 if (nbits <= 48) {
504 j = PyLong_AsDouble(w);
505 /* It's impossible that <= 48 bits overflowed. */
506 assert(j != -1.0 || ! PyErr_Occurred());
507 goto Compare;
508 }
509 assert(wsign != 0); /* else nbits was 0 */
510 assert(vsign != 0); /* if vsign were 0, then since wsign is
511 * not 0, we would have taken the
512 * vsign != wsign branch at the start */
513 /* We want to work with non-negative numbers. */
514 if (vsign < 0) {
515 /* "Multiply both sides" by -1; this also swaps the
516 * comparator.
517 */
518 i = -i;
519 op = _Py_SwappedOp[op];
520 }
521 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000522 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000523 /* exponent is the # of bits in v before the radix point;
524 * we know that nbits (the # of bits in w) > 48 at this point
525 */
526 if (exponent < 0 || (size_t)exponent < nbits) {
527 i = 1.0;
528 j = 2.0;
529 goto Compare;
530 }
531 if ((size_t)exponent > nbits) {
532 i = 2.0;
533 j = 1.0;
534 goto Compare;
535 }
536 /* v and w have the same number of bits before the radix
537 * point. Construct two longs that have the same comparison
538 * outcome.
539 */
540 {
541 double fracpart;
542 double intpart;
543 PyObject *result = NULL;
544 PyObject *one = NULL;
545 PyObject *vv = NULL;
546 PyObject *ww = w;
547
548 if (wsign < 0) {
549 ww = PyNumber_Negative(w);
550 if (ww == NULL)
551 goto Error;
552 }
553 else
554 Py_INCREF(ww);
555
556 fracpart = modf(i, &intpart);
557 vv = PyLong_FromDouble(intpart);
558 if (vv == NULL)
559 goto Error;
560
561 if (fracpart != 0.0) {
562 /* Shift left, and or a 1 bit into vv
563 * to represent the lost fraction.
564 */
565 PyObject *temp;
566
567 one = PyInt_FromLong(1);
568 if (one == NULL)
569 goto Error;
570
571 temp = PyNumber_Lshift(ww, one);
572 if (temp == NULL)
573 goto Error;
574 Py_DECREF(ww);
575 ww = temp;
576
577 temp = PyNumber_Lshift(vv, one);
578 if (temp == NULL)
579 goto Error;
580 Py_DECREF(vv);
581 vv = temp;
582
583 temp = PyNumber_Or(vv, one);
584 if (temp == NULL)
585 goto Error;
586 Py_DECREF(vv);
587 vv = temp;
588 }
589
590 r = PyObject_RichCompareBool(vv, ww, op);
591 if (r < 0)
592 goto Error;
593 result = PyBool_FromLong(r);
594 Error:
595 Py_XDECREF(vv);
596 Py_XDECREF(ww);
597 Py_XDECREF(one);
598 return result;
599 }
600 } /* else if (PyLong_Check(w)) */
601
602 else /* w isn't float, int, or long */
603 goto Unimplemented;
604
605 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000606 PyFPE_START_PROTECT("richcompare", return NULL)
607 switch (op) {
608 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000609 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000610 break;
611 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000612 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000613 break;
614 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000615 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000616 break;
617 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000618 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000619 break;
620 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000621 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000622 break;
623 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000624 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000625 break;
626 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000627 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000628 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000629
630 Unimplemented:
631 Py_INCREF(Py_NotImplemented);
632 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633}
634
Guido van Rossum9bfef441993-03-29 10:43:31 +0000635static long
Fred Drakefd99de62000-07-09 05:02:18 +0000636float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000637{
Tim Peters39dce292000-08-15 03:34:48 +0000638 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000639}
640
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000641static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000642float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000644 double a,b;
645 CONVERT_TO_DOUBLE(v, a);
646 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000647 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000648 a = a + b;
649 PyFPE_END_PROTECT(a)
650 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651}
652
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000654float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000656 double a,b;
657 CONVERT_TO_DOUBLE(v, a);
658 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000659 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000660 a = a - b;
661 PyFPE_END_PROTECT(a)
662 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000663}
664
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000666float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000668 double a,b;
669 CONVERT_TO_DOUBLE(v, a);
670 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000671 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000672 a = a * b;
673 PyFPE_END_PROTECT(a)
674 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675}
676
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000678float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000680 double a,b;
681 CONVERT_TO_DOUBLE(v, a);
682 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000683#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000684 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000685 PyErr_SetString(PyExc_ZeroDivisionError,
686 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687 return NULL;
688 }
Christian Heimes6f341092008-04-18 23:13:07 +0000689#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000690 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000691 a = a / b;
692 PyFPE_END_PROTECT(a)
693 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694}
695
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000697float_classic_div(PyObject *v, PyObject *w)
698{
699 double a,b;
700 CONVERT_TO_DOUBLE(v, a);
701 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000702 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000703 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
704 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000705#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000706 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000707 PyErr_SetString(PyExc_ZeroDivisionError,
708 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000709 return NULL;
710 }
Christian Heimes6f341092008-04-18 23:13:07 +0000711#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000712 PyFPE_START_PROTECT("divide", return 0)
713 a = a / b;
714 PyFPE_END_PROTECT(a)
715 return PyFloat_FromDouble(a);
716}
717
718static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000719float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000720{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000721 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000722 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000723 CONVERT_TO_DOUBLE(v, vx);
724 CONVERT_TO_DOUBLE(w, wx);
725#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000727 PyErr_SetString(PyExc_ZeroDivisionError,
728 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729 return NULL;
730 }
Christian Heimes6f341092008-04-18 23:13:07 +0000731#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000732 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000733 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000734 /* note: checking mod*wx < 0 is incorrect -- underflows to
735 0 if wx < sqrt(smallest nonzero double) */
736 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000737 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000738 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000739 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000741}
742
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000744float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000745{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000746 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000747 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000748 CONVERT_TO_DOUBLE(v, vx);
749 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000750 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000751 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000752 return NULL;
753 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000754 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000755 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000756 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000757 exact multiple of wx. But this is fp arithmetic, and fp
758 vx - mod is an approximation; the result is that div may
759 not be an exact integral value after the division, although
760 it will always be very close to one.
761 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000762 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000763 if (mod) {
764 /* ensure the remainder has the same sign as the denominator */
765 if ((wx < 0) != (mod < 0)) {
766 mod += wx;
767 div -= 1.0;
768 }
769 }
770 else {
771 /* the remainder is zero, and in the presence of signed zeroes
772 fmod returns different results across platforms; ensure
773 it has the same sign as the denominator; we'd like to do
774 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000775 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000776 if (wx < 0.0)
777 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000778 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000779 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000780 if (div) {
781 floordiv = floor(div);
782 if (div - floordiv > 0.5)
783 floordiv += 1.0;
784 }
785 else {
786 /* div is zero - get the same sign as the true quotient */
787 div *= div; /* hide "div = +0" from optimizers */
788 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
789 }
790 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000791 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000792}
793
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000794static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000795float_floor_div(PyObject *v, PyObject *w)
796{
797 PyObject *t, *r;
798
799 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000800 if (t == NULL || t == Py_NotImplemented)
801 return t;
802 assert(PyTuple_CheckExact(t));
803 r = PyTuple_GET_ITEM(t, 0);
804 Py_INCREF(r);
805 Py_DECREF(t);
806 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000807}
808
809static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000810float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
812 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000813
814 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000815 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000816 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000817 return NULL;
818 }
819
Neil Schemenauer32117e52001-01-04 01:44:34 +0000820 CONVERT_TO_DOUBLE(v, iv);
821 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000822
823 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000824 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000825 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000826 }
Tim Peters96685bf2001-08-23 22:31:37 +0000827 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000828 if (iw < 0.0) {
829 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000830 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000831 return NULL;
832 }
833 return PyFloat_FromDouble(0.0);
834 }
Christian Heimes6f341092008-04-18 23:13:07 +0000835 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
836 return PyFloat_FromDouble(1.0);
837 }
Tim Peterse87568d2003-05-24 20:18:24 +0000838 if (iv < 0.0) {
839 /* Whether this is an error is a mess, and bumps into libm
840 * bugs so we have to figure it out ourselves.
841 */
842 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000843 PyErr_SetString(PyExc_ValueError, "negative number "
844 "cannot be raised to a fractional power");
845 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000846 }
847 /* iw is an exact integer, albeit perhaps a very large one.
848 * -1 raised to an exact integer should never be exceptional.
849 * Alas, some libms (chiefly glibc as of early 2003) return
850 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
851 * happen to be representable in a *C* integer. That's a
852 * bug; we let that slide in math.pow() (which currently
853 * reflects all platform accidents), but not for Python's **.
854 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000855 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000856 /* Return 1 if iw is even, -1 if iw is odd; there's
857 * no guarantee that any C integral type is big
858 * enough to hold iw, so we have to check this
859 * indirectly.
860 */
861 ix = floor(iw * 0.5) * 2.0;
862 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
863 }
864 /* Else iv != -1.0, and overflow or underflow are possible.
865 * Unless we're to write pow() ourselves, we have to trust
866 * the platform to do this correctly.
867 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000868 }
Tim Peters96685bf2001-08-23 22:31:37 +0000869 errno = 0;
870 PyFPE_START_PROTECT("pow", return NULL)
871 ix = pow(iv, iw);
872 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000873 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000874 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000875 /* We don't expect any errno value other than ERANGE, but
876 * the range of libm bugs appears unbounded.
877 */
Alex Martelli348dc882006-08-23 22:17:59 +0000878 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
879 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000881 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000882 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000883}
884
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000886float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000887{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000888 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889}
890
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000891static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000892float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000893{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000894 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000895}
896
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000897static int
Fred Drakefd99de62000-07-09 05:02:18 +0000898float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000899{
900 return v->ob_fval != 0.0;
901}
902
Guido van Rossum234f9421993-06-17 12:35:49 +0000903static int
Fred Drakefd99de62000-07-09 05:02:18 +0000904float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000905{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000906 if (PyInt_Check(*pw)) {
907 long x = PyInt_AsLong(*pw);
908 *pw = PyFloat_FromDouble((double)x);
909 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000910 return 0;
911 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000912 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000913 double x = PyLong_AsDouble(*pw);
914 if (x == -1.0 && PyErr_Occurred())
915 return -1;
916 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000917 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000918 return 0;
919 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000920 else if (PyFloat_Check(*pw)) {
921 Py_INCREF(*pv);
922 Py_INCREF(*pw);
923 return 0;
924 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000925 return 1; /* Can't do it */
926}
927
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000928static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000929float_is_integer(PyObject *v)
930{
931 double x = PyFloat_AsDouble(v);
932 PyObject *o;
933
934 if (x == -1.0 && PyErr_Occurred())
935 return NULL;
936 if (!Py_IS_FINITE(x))
937 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +0000938 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000939 PyFPE_START_PROTECT("is_integer", return NULL)
940 o = (floor(x) == x) ? Py_True : Py_False;
941 PyFPE_END_PROTECT(x)
942 if (errno != 0) {
943 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
944 PyExc_ValueError);
945 return NULL;
946 }
947 Py_INCREF(o);
948 return o;
949}
950
951#if 0
952static PyObject *
953float_is_inf(PyObject *v)
954{
955 double x = PyFloat_AsDouble(v);
956 if (x == -1.0 && PyErr_Occurred())
957 return NULL;
958 return PyBool_FromLong((long)Py_IS_INFINITY(x));
959}
960
961static PyObject *
962float_is_nan(PyObject *v)
963{
964 double x = PyFloat_AsDouble(v);
965 if (x == -1.0 && PyErr_Occurred())
966 return NULL;
967 return PyBool_FromLong((long)Py_IS_NAN(x));
968}
969
970static PyObject *
971float_is_finite(PyObject *v)
972{
973 double x = PyFloat_AsDouble(v);
974 if (x == -1.0 && PyErr_Occurred())
975 return NULL;
976 return PyBool_FromLong((long)Py_IS_FINITE(x));
977}
978#endif
979
980static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000981float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000982{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000984 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000985
986 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000987 /* Try to get out cheap if this fits in a Python int. The attempt
988 * to cast to long must be protected, as C doesn't define what
989 * happens if the double is too big to fit in a long. Some rare
990 * systems raise an exception then (RISCOS was mentioned as one,
991 * and someone using a non-default option on Sun also bumped into
992 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
993 * still be vulnerable: if a long has more bits of precision than
994 * a double, casting MIN/MAX to double may yield an approximation,
995 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
996 * yield true from the C expression wholepart<=LONG_MAX, despite
997 * that wholepart is actually greater than LONG_MAX.
998 */
999 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1000 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001001 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001002 }
1003 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001004}
1005
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001007float_long(PyObject *v)
1008{
1009 double x = PyFloat_AsDouble(v);
1010 return PyLong_FromDouble(x);
1011}
1012
1013static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001014float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001015{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001016 if (PyFloat_CheckExact(v))
1017 Py_INCREF(v);
1018 else
1019 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001020 return v;
1021}
1022
Mark Dickinson7103aa42008-07-15 19:08:33 +00001023/* turn ASCII hex characters into integer values and vice versa */
1024
1025static char
1026char_from_hex(int x)
1027{
1028 assert(0 <= x && x < 16);
1029 return "0123456789abcdef"[x];
1030}
1031
1032static int
1033hex_from_char(char c) {
1034 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001035 switch(c) {
1036 case '0':
1037 x = 0;
1038 break;
1039 case '1':
1040 x = 1;
1041 break;
1042 case '2':
1043 x = 2;
1044 break;
1045 case '3':
1046 x = 3;
1047 break;
1048 case '4':
1049 x = 4;
1050 break;
1051 case '5':
1052 x = 5;
1053 break;
1054 case '6':
1055 x = 6;
1056 break;
1057 case '7':
1058 x = 7;
1059 break;
1060 case '8':
1061 x = 8;
1062 break;
1063 case '9':
1064 x = 9;
1065 break;
1066 case 'a':
1067 case 'A':
1068 x = 10;
1069 break;
1070 case 'b':
1071 case 'B':
1072 x = 11;
1073 break;
1074 case 'c':
1075 case 'C':
1076 x = 12;
1077 break;
1078 case 'd':
1079 case 'D':
1080 x = 13;
1081 break;
1082 case 'e':
1083 case 'E':
1084 x = 14;
1085 break;
1086 case 'f':
1087 case 'F':
1088 x = 15;
1089 break;
1090 default:
1091 x = -1;
1092 break;
1093 }
1094 return x;
1095}
1096
1097/* convert a float to a hexadecimal string */
1098
1099/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1100 of the form 4k+1. */
1101#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1102
1103static PyObject *
1104float_hex(PyObject *v)
1105{
1106 double x, m;
1107 int e, shift, i, si, esign;
1108 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1109 trailing NUL byte. */
1110 char s[(TOHEX_NBITS-1)/4+3];
1111
1112 CONVERT_TO_DOUBLE(v, x);
1113
1114 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1115 return float_str((PyFloatObject *)v);
1116
1117 if (x == 0.0) {
1118 if(copysign(1.0, x) == -1.0)
1119 return PyString_FromString("-0x0.0p+0");
1120 else
1121 return PyString_FromString("0x0.0p+0");
1122 }
1123
1124 m = frexp(fabs(x), &e);
1125 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1126 m = ldexp(m, shift);
1127 e -= shift;
1128
1129 si = 0;
1130 s[si] = char_from_hex((int)m);
1131 si++;
1132 m -= (int)m;
1133 s[si] = '.';
1134 si++;
1135 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1136 m *= 16.0;
1137 s[si] = char_from_hex((int)m);
1138 si++;
1139 m -= (int)m;
1140 }
1141 s[si] = '\0';
1142
1143 if (e < 0) {
1144 esign = (int)'-';
1145 e = -e;
1146 }
1147 else
1148 esign = (int)'+';
1149
1150 if (x < 0.0)
1151 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1152 else
1153 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1154}
1155
1156PyDoc_STRVAR(float_hex_doc,
1157"float.hex() -> string\n\
1158\n\
1159Return a hexadecimal representation of a floating-point number.\n\
1160>>> (-0.1).hex()\n\
1161'-0x1.999999999999ap-4'\n\
1162>>> 3.14159.hex()\n\
1163'0x1.921f9f01b866ep+1'");
1164
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001165/* Case-insensitive locale-independent string match used for nan and inf
1166 detection. t should be lower-case and null-terminated. Return a nonzero
1167 result if the first strlen(t) characters of s match t and 0 otherwise. */
1168
1169static int
1170case_insensitive_match(const char *s, const char *t)
1171{
1172 while(*t && Py_TOLOWER(*s) == *t) {
1173 s++;
1174 t++;
1175 }
1176 return *t ? 0 : 1;
1177}
1178
Mark Dickinson7103aa42008-07-15 19:08:33 +00001179/* Convert a hexadecimal string to a float. */
1180
1181static PyObject *
1182float_fromhex(PyObject *cls, PyObject *arg)
1183{
1184 PyObject *result_as_float, *result;
1185 double x;
1186 long exp, top_exp, lsb, key_digit;
1187 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1188 int half_eps, digit, round_up, sign=1;
1189 Py_ssize_t length, ndigits, fdigits, i;
1190
1191 /*
1192 * For the sake of simplicity and correctness, we impose an artificial
1193 * limit on ndigits, the total number of hex digits in the coefficient
1194 * The limit is chosen to ensure that, writing exp for the exponent,
1195 *
1196 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1197 * guaranteed to overflow (provided it's nonzero)
1198 *
1199 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1200 * guaranteed to underflow to 0.
1201 *
1202 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1203 * overflow in the calculation of exp and top_exp below.
1204 *
1205 * More specifically, ndigits is assumed to satisfy the following
1206 * inequalities:
1207 *
1208 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1209 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1210 *
1211 * If either of these inequalities is not satisfied, a ValueError is
1212 * raised. Otherwise, write x for the value of the hex string, and
1213 * assume x is nonzero. Then
1214 *
1215 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1216 *
1217 * Now if exp > LONG_MAX/2 then:
1218 *
1219 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1220 * = DBL_MAX_EXP
1221 *
1222 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1223 * double, so overflows. If exp < LONG_MIN/2, then
1224 *
1225 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1226 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1227 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1228 *
1229 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1230 * when converted to a C double.
1231 *
1232 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1233 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1234 */
1235
1236 if (PyString_AsStringAndSize(arg, &s, &length))
1237 return NULL;
1238 s_end = s + length;
1239
1240 /********************
1241 * Parse the string *
1242 ********************/
1243
1244 /* leading whitespace and optional sign */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001245 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001246 s++;
1247 if (*s == '-') {
1248 s++;
1249 sign = -1;
1250 }
1251 else if (*s == '+')
1252 s++;
1253
1254 /* infinities and nans */
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001255 if (*s == 'i' || *s == 'I') {
1256 if (!case_insensitive_match(s+1, "nf"))
1257 goto parse_error;
1258 s += 3;
1259 x = Py_HUGE_VAL;
1260 if (case_insensitive_match(s, "inity"))
1261 s += 5;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001262 goto finished;
1263 }
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001264 if (*s == 'n' || *s == 'N') {
1265 if (!case_insensitive_match(s+1, "an"))
1266 goto parse_error;
1267 s += 3;
1268 x = Py_NAN;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001269 goto finished;
1270 }
1271
1272 /* [0x] */
1273 s_store = s;
1274 if (*s == '0') {
1275 s++;
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001276 if (*s == 'x' || *s == 'X')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001277 s++;
1278 else
1279 s = s_store;
1280 }
1281
1282 /* coefficient: <integer> [. <fraction>] */
1283 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001284 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001285 s++;
1286 s_store = s;
1287 if (*s == '.') {
1288 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001289 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001290 s++;
1291 coeff_end = s-1;
1292 }
1293 else
1294 coeff_end = s;
1295
1296 /* ndigits = total # of hex digits; fdigits = # after point */
1297 ndigits = coeff_end - coeff_start;
1298 fdigits = coeff_end - s_store;
1299 if (ndigits == 0)
1300 goto parse_error;
1301 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1302 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1303 goto insane_length_error;
1304
1305 /* [p <exponent>] */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001306 if (*s == 'p' || *s == 'P') {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001307 s++;
1308 exp_start = s;
1309 if (*s == '-' || *s == '+')
1310 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001311 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001312 goto parse_error;
1313 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001314 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001315 s++;
1316 exp = strtol(exp_start, NULL, 10);
1317 }
1318 else
1319 exp = 0;
1320
Mark Dickinson7103aa42008-07-15 19:08:33 +00001321/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1322#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1323 coeff_end-(j) : \
1324 coeff_end-1-(j)))
1325
1326 /*******************************************
1327 * Compute rounded value of the hex string *
1328 *******************************************/
1329
1330 /* Discard leading zeros, and catch extreme overflow and underflow */
1331 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1332 ndigits--;
1333 if (ndigits == 0 || exp < LONG_MIN/2) {
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001334 x = 0.0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001335 goto finished;
1336 }
1337 if (exp > LONG_MAX/2)
1338 goto overflow_error;
1339
1340 /* Adjust exponent for fractional part. */
1341 exp = exp - 4*((long)fdigits);
1342
1343 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1344 top_exp = exp + 4*((long)ndigits - 1);
1345 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1346 top_exp++;
1347
1348 /* catch almost all nonextreme cases of overflow and underflow here */
1349 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001350 x = 0.0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001351 goto finished;
1352 }
1353 if (top_exp > DBL_MAX_EXP)
1354 goto overflow_error;
1355
1356 /* lsb = exponent of least significant bit of the *rounded* value.
1357 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1358 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1359
1360 x = 0.0;
1361 if (exp >= lsb) {
1362 /* no rounding required */
1363 for (i = ndigits-1; i >= 0; i--)
1364 x = 16.0*x + HEX_DIGIT(i);
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001365 x = ldexp(x, (int)(exp));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001366 goto finished;
1367 }
1368 /* rounding required. key_digit is the index of the hex digit
1369 containing the first bit to be rounded away. */
1370 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1371 key_digit = (lsb - exp - 1) / 4;
1372 for (i = ndigits-1; i > key_digit; i--)
1373 x = 16.0*x + HEX_DIGIT(i);
1374 digit = HEX_DIGIT(key_digit);
1375 x = 16.0*x + (double)(digit & (16-2*half_eps));
1376
1377 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1378 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1379 if ((digit & half_eps) != 0) {
1380 round_up = 0;
1381 if ((digit & (3*half_eps-1)) != 0 ||
1382 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1383 round_up = 1;
1384 else
1385 for (i = key_digit-1; i >= 0; i--)
1386 if (HEX_DIGIT(i) != 0) {
1387 round_up = 1;
1388 break;
1389 }
1390 if (round_up == 1) {
1391 x += 2*half_eps;
1392 if (top_exp == DBL_MAX_EXP &&
1393 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1394 /* overflow corner case: pre-rounded value <
1395 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1396 goto overflow_error;
1397 }
1398 }
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001399 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001400
1401 finished:
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001402 /* optional trailing whitespace leading to the end of the string */
1403 while (Py_ISSPACE(*s))
1404 s++;
1405 if (s != s_end)
1406 goto parse_error;
1407 result_as_float = Py_BuildValue("(d)", sign * x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001408 if (result_as_float == NULL)
1409 return NULL;
1410 result = PyObject_CallObject(cls, result_as_float);
1411 Py_DECREF(result_as_float);
1412 return result;
1413
1414 overflow_error:
1415 PyErr_SetString(PyExc_OverflowError,
1416 "hexadecimal value too large to represent as a float");
1417 return NULL;
1418
1419 parse_error:
1420 PyErr_SetString(PyExc_ValueError,
1421 "invalid hexadecimal floating-point string");
1422 return NULL;
1423
1424 insane_length_error:
1425 PyErr_SetString(PyExc_ValueError,
1426 "hexadecimal string too long to convert");
1427 return NULL;
1428}
1429
1430PyDoc_STRVAR(float_fromhex_doc,
1431"float.fromhex(string) -> float\n\
1432\n\
1433Create a floating-point number from a hexadecimal string.\n\
1434>>> float.fromhex('0x1.ffffp10')\n\
14352047.984375\n\
1436>>> float.fromhex('-0x1p-1074')\n\
1437-4.9406564584124654e-324");
1438
1439
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001440static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001441float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001442{
1443 double self;
1444 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001445 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001446 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001447
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001448 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001449 PyObject *py_exponent = NULL;
1450 PyObject *numerator = NULL;
1451 PyObject *denominator = NULL;
1452 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001453 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001454
1455#define INPLACE_UPDATE(obj, call) \
1456 prev = obj; \
1457 obj = call; \
1458 Py_DECREF(prev); \
1459
1460 CONVERT_TO_DOUBLE(v, self);
1461
1462 if (Py_IS_INFINITY(self)) {
1463 PyErr_SetString(PyExc_OverflowError,
1464 "Cannot pass infinity to float.as_integer_ratio.");
1465 return NULL;
1466 }
1467#ifdef Py_NAN
1468 if (Py_IS_NAN(self)) {
1469 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001470 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001471 return NULL;
1472 }
1473#endif
1474
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001475 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001476 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001477 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001478
Raymond Hettingerf9859032008-02-01 23:45:44 +00001479 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001480 float_part *= 2.0;
1481 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001482 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001483 /* self == float_part * 2**exponent exactly and float_part is integral.
1484 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1485 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001486
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001487 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001488 if (numerator == NULL) goto error;
1489
Raymond Hettingerf9859032008-02-01 23:45:44 +00001490 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001491 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001492 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001493 if (py_exponent == NULL) goto error;
1494 INPLACE_UPDATE(py_exponent,
1495 long_methods->nb_lshift(denominator, py_exponent));
1496 if (py_exponent == NULL) goto error;
1497 if (exponent > 0) {
1498 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001499 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001500 if (numerator == NULL) goto error;
1501 }
1502 else {
1503 Py_DECREF(denominator);
1504 denominator = py_exponent;
1505 py_exponent = NULL;
1506 }
1507
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001508 /* Returns ints instead of longs where possible */
1509 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1510 if (numerator == NULL) goto error;
1511 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1512 if (denominator == NULL) goto error;
1513
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001514 result_pair = PyTuple_Pack(2, numerator, denominator);
1515
1516#undef INPLACE_UPDATE
1517error:
1518 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001519 Py_XDECREF(denominator);
1520 Py_XDECREF(numerator);
1521 return result_pair;
1522}
1523
1524PyDoc_STRVAR(float_as_integer_ratio_doc,
1525"float.as_integer_ratio() -> (int, int)\n"
1526"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001527"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1528"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001529"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001530"\n"
1531">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001532"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001533">>> (0.0).as_integer_ratio()\n"
1534"(0, 1)\n"
1535">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001536"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001537
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001538
Jeremy Hylton938ace62002-07-17 16:30:39 +00001539static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001540float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1541
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542static PyObject *
1543float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1544{
1545 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001546 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547
Guido van Rossumbef14172001-08-29 15:47:46 +00001548 if (type != &PyFloat_Type)
1549 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1551 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001552 /* If it's a string, but not a string subclass, use
1553 PyFloat_FromString. */
1554 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555 return PyFloat_FromString(x, NULL);
1556 return PyNumber_Float(x);
1557}
1558
Guido van Rossumbef14172001-08-29 15:47:46 +00001559/* Wimpy, slow approach to tp_new calls for subtypes of float:
1560 first create a regular float from whatever arguments we got,
1561 then allocate a subtype instance and initialize its ob_fval
1562 from the regular float. The regular float is then thrown away.
1563*/
1564static PyObject *
1565float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1566{
Anthony Baxter377be112006-04-11 06:54:30 +00001567 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001568
1569 assert(PyType_IsSubtype(type, &PyFloat_Type));
1570 tmp = float_new(&PyFloat_Type, args, kwds);
1571 if (tmp == NULL)
1572 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001573 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001574 newobj = type->tp_alloc(type, 0);
1575 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001576 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001577 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001578 }
Anthony Baxter377be112006-04-11 06:54:30 +00001579 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001580 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001581 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001582}
1583
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001584static PyObject *
1585float_getnewargs(PyFloatObject *v)
1586{
1587 return Py_BuildValue("(d)", v->ob_fval);
1588}
1589
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001590/* this is for the benefit of the pack/unpack routines below */
1591
1592typedef enum {
1593 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1594} float_format_type;
1595
1596static float_format_type double_format, float_format;
1597static float_format_type detected_double_format, detected_float_format;
1598
1599static PyObject *
1600float_getformat(PyTypeObject *v, PyObject* arg)
1601{
1602 char* s;
1603 float_format_type r;
1604
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001605 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001606 PyErr_Format(PyExc_TypeError,
1607 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001608 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001609 return NULL;
1610 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001611 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001612 if (strcmp(s, "double") == 0) {
1613 r = double_format;
1614 }
1615 else if (strcmp(s, "float") == 0) {
1616 r = float_format;
1617 }
1618 else {
1619 PyErr_SetString(PyExc_ValueError,
1620 "__getformat__() argument 1 must be "
1621 "'double' or 'float'");
1622 return NULL;
1623 }
1624
1625 switch (r) {
1626 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001627 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001628 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001629 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001630 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001631 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001632 default:
1633 Py_FatalError("insane float_format or double_format");
1634 return NULL;
1635 }
1636}
1637
1638PyDoc_STRVAR(float_getformat_doc,
1639"float.__getformat__(typestr) -> string\n"
1640"\n"
1641"You probably don't want to use this function. It exists mainly to be\n"
1642"used in Python's test suite.\n"
1643"\n"
1644"typestr must be 'double' or 'float'. This function returns whichever of\n"
1645"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1646"format of floating point numbers used by the C type named by typestr.");
1647
1648static PyObject *
1649float_setformat(PyTypeObject *v, PyObject* args)
1650{
1651 char* typestr;
1652 char* format;
1653 float_format_type f;
1654 float_format_type detected;
1655 float_format_type *p;
1656
1657 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1658 return NULL;
1659
1660 if (strcmp(typestr, "double") == 0) {
1661 p = &double_format;
1662 detected = detected_double_format;
1663 }
1664 else if (strcmp(typestr, "float") == 0) {
1665 p = &float_format;
1666 detected = detected_float_format;
1667 }
1668 else {
1669 PyErr_SetString(PyExc_ValueError,
1670 "__setformat__() argument 1 must "
1671 "be 'double' or 'float'");
1672 return NULL;
1673 }
1674
1675 if (strcmp(format, "unknown") == 0) {
1676 f = unknown_format;
1677 }
1678 else if (strcmp(format, "IEEE, little-endian") == 0) {
1679 f = ieee_little_endian_format;
1680 }
1681 else if (strcmp(format, "IEEE, big-endian") == 0) {
1682 f = ieee_big_endian_format;
1683 }
1684 else {
1685 PyErr_SetString(PyExc_ValueError,
1686 "__setformat__() argument 2 must be "
1687 "'unknown', 'IEEE, little-endian' or "
1688 "'IEEE, big-endian'");
1689 return NULL;
1690
1691 }
1692
1693 if (f != unknown_format && f != detected) {
1694 PyErr_Format(PyExc_ValueError,
1695 "can only set %s format to 'unknown' or the "
1696 "detected platform value", typestr);
1697 return NULL;
1698 }
1699
1700 *p = f;
1701 Py_RETURN_NONE;
1702}
1703
1704PyDoc_STRVAR(float_setformat_doc,
1705"float.__setformat__(typestr, fmt) -> None\n"
1706"\n"
1707"You probably don't want to use this function. It exists mainly to be\n"
1708"used in Python's test suite.\n"
1709"\n"
1710"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1711"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1712"one of the latter two if it appears to match the underlying C reality.\n"
1713"\n"
1714"Overrides the automatic determination of C-level floating point type.\n"
1715"This affects how floats are converted to and from binary strings.");
1716
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001717static PyObject *
1718float_getzero(PyObject *v, void *closure)
1719{
1720 return PyFloat_FromDouble(0.0);
1721}
1722
Eric Smitha9f7d622008-02-17 19:46:49 +00001723static PyObject *
1724float__format__(PyObject *self, PyObject *args)
1725{
1726 PyObject *format_spec;
1727
1728 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1729 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001730 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001731 return _PyFloat_FormatAdvanced(self,
1732 PyBytes_AS_STRING(format_spec),
1733 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001734 if (PyUnicode_Check(format_spec)) {
1735 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001736 PyObject *result;
1737 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001738
Eric Smithdc13b792008-05-30 18:10:04 +00001739 if (str_spec == NULL)
1740 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001741
Eric Smithdc13b792008-05-30 18:10:04 +00001742 result = _PyFloat_FormatAdvanced(self,
1743 PyBytes_AS_STRING(str_spec),
1744 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001745
Eric Smithdc13b792008-05-30 18:10:04 +00001746 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001747 return result;
1748 }
1749 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1750 return NULL;
1751}
1752
1753PyDoc_STRVAR(float__format__doc,
1754"float.__format__(format_spec) -> string\n"
1755"\n"
1756"Formats the float according to format_spec.");
1757
1758
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001759static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001760 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001761 "Returns self, the complex conjugate of any float."},
1762 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1763 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001764 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1765 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001766 {"fromhex", (PyCFunction)float_fromhex,
1767 METH_O|METH_CLASS, float_fromhex_doc},
1768 {"hex", (PyCFunction)float_hex,
1769 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001770 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1771 "Returns True if the float is an integer."},
1772#if 0
1773 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1774 "Returns True if the float is positive or negative infinite."},
1775 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1776 "Returns True if the float is finite, neither infinite nor NaN."},
1777 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1778 "Returns True if the float is not a number (NaN)."},
1779#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001780 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001781 {"__getformat__", (PyCFunction)float_getformat,
1782 METH_O|METH_CLASS, float_getformat_doc},
1783 {"__setformat__", (PyCFunction)float_setformat,
1784 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001785 {"__format__", (PyCFunction)float__format__,
1786 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001787 {NULL, NULL} /* sentinel */
1788};
1789
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001790static PyGetSetDef float_getset[] = {
1791 {"real",
1792 (getter)float_float, (setter)NULL,
1793 "the real part of a complex number",
1794 NULL},
1795 {"imag",
1796 (getter)float_getzero, (setter)NULL,
1797 "the imaginary part of a complex number",
1798 NULL},
1799 {NULL} /* Sentinel */
1800};
1801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803"float(x) -> floating point number\n\
1804\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001805Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806
1807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001808static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001809 float_add, /*nb_add*/
1810 float_sub, /*nb_subtract*/
1811 float_mul, /*nb_multiply*/
1812 float_classic_div, /*nb_divide*/
1813 float_rem, /*nb_remainder*/
1814 float_divmod, /*nb_divmod*/
1815 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001816 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001817 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001818 (unaryfunc)float_abs, /*nb_absolute*/
1819 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001820 0, /*nb_invert*/
1821 0, /*nb_lshift*/
1822 0, /*nb_rshift*/
1823 0, /*nb_and*/
1824 0, /*nb_xor*/
1825 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001826 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001827 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001828 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001829 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001830 0, /* nb_oct */
1831 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001832 0, /* nb_inplace_add */
1833 0, /* nb_inplace_subtract */
1834 0, /* nb_inplace_multiply */
1835 0, /* nb_inplace_divide */
1836 0, /* nb_inplace_remainder */
1837 0, /* nb_inplace_power */
1838 0, /* nb_inplace_lshift */
1839 0, /* nb_inplace_rshift */
1840 0, /* nb_inplace_and */
1841 0, /* nb_inplace_xor */
1842 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001843 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001844 float_div, /* nb_true_divide */
1845 0, /* nb_inplace_floor_divide */
1846 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847};
1848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001850 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854 (destructor)float_dealloc, /* tp_dealloc */
1855 (printfunc)float_print, /* tp_print */
1856 0, /* tp_getattr */
1857 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001858 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 (reprfunc)float_repr, /* tp_repr */
1860 &float_as_number, /* tp_as_number */
1861 0, /* tp_as_sequence */
1862 0, /* tp_as_mapping */
1863 (hashfunc)float_hash, /* tp_hash */
1864 0, /* tp_call */
1865 (reprfunc)float_str, /* tp_str */
1866 PyObject_GenericGetAttr, /* tp_getattro */
1867 0, /* tp_setattro */
1868 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001869 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1870 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871 float_doc, /* tp_doc */
1872 0, /* tp_traverse */
1873 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001874 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 0, /* tp_weaklistoffset */
1876 0, /* tp_iter */
1877 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001878 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001880 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 0, /* tp_base */
1882 0, /* tp_dict */
1883 0, /* tp_descr_get */
1884 0, /* tp_descr_set */
1885 0, /* tp_dictoffset */
1886 0, /* tp_init */
1887 0, /* tp_alloc */
1888 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001889};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001890
1891void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892_PyFloat_Init(void)
1893{
1894 /* We attempt to determine if this machine is using IEEE
1895 floating point formats by peering at the bits of some
1896 carefully chosen values. If it looks like we are on an
1897 IEEE platform, the float packing/unpacking routines can
1898 just copy bits, if not they resort to arithmetic & shifts
1899 and masks. The shifts & masks approach works on all finite
1900 values, but what happens to infinities, NaNs and signed
1901 zeroes on packing is an accident, and attempting to unpack
1902 a NaN or an infinity will raise an exception.
1903
1904 Note that if we're on some whacked-out platform which uses
1905 IEEE formats but isn't strictly little-endian or big-
1906 endian, we will fall back to the portable shifts & masks
1907 method. */
1908
1909#if SIZEOF_DOUBLE == 8
1910 {
1911 double x = 9006104071832581.0;
1912 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1913 detected_double_format = ieee_big_endian_format;
1914 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1915 detected_double_format = ieee_little_endian_format;
1916 else
1917 detected_double_format = unknown_format;
1918 }
1919#else
1920 detected_double_format = unknown_format;
1921#endif
1922
1923#if SIZEOF_FLOAT == 4
1924 {
1925 float y = 16711938.0;
1926 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1927 detected_float_format = ieee_big_endian_format;
1928 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1929 detected_float_format = ieee_little_endian_format;
1930 else
1931 detected_float_format = unknown_format;
1932 }
1933#else
1934 detected_float_format = unknown_format;
1935#endif
1936
1937 double_format = detected_double_format;
1938 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001939
Christian Heimes796fc312008-01-30 18:58:29 +00001940 /* Init float info */
1941 if (FloatInfoType.tp_name == 0)
1942 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943}
1944
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001945int
1946PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001947{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001948 PyFloatObject *p;
1949 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001950 int i;
1951 int u; /* remaining unfreed ints per block */
1952 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001953
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001954 list = block_list;
1955 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001956 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001957 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001958 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001959 for (i = 0, p = &list->objects[0];
1960 i < N_FLOATOBJECTS;
1961 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001962 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001963 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001964 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001965 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001966 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001967 list->next = block_list;
1968 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001969 for (i = 0, p = &list->objects[0];
1970 i < N_FLOATOBJECTS;
1971 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001972 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001973 Py_REFCNT(p) == 0) {
1974 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001975 free_list;
1976 free_list = p;
1977 }
1978 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001979 }
1980 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001981 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001982 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001983 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001984 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001985 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001986 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001987}
1988
1989void
1990PyFloat_Fini(void)
1991{
1992 PyFloatObject *p;
1993 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001994 int i;
1995 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001996
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001997 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00001998
Guido van Rossum3fce8831999-03-12 19:43:17 +00001999 if (!Py_VerboseFlag)
2000 return;
2001 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002002 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002003 fprintf(stderr, "\n");
2004 }
2005 else {
2006 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002007 ": %d unfreed float%s\n",
2008 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002009 }
2010 if (Py_VerboseFlag > 1) {
2011 list = block_list;
2012 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002013 for (i = 0, p = &list->objects[0];
2014 i < N_FLOATOBJECTS;
2015 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002016 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00002017 Py_REFCNT(p) != 0) {
Eric Smithb3272582009-10-16 14:26:36 +00002018 char *buf = PyOS_double_to_string(
2019 PyFloat_AS_DOUBLE(p), 'r',
2020 0, 0, NULL);
2021 if (buf) {
2022 /* XXX(twouters) cast
2023 refcount to long
2024 until %zd is
2025 universally
2026 available
2027 */
2028 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002029 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002030 p, (long)Py_REFCNT(p), buf);
Eric Smithb3272582009-10-16 14:26:36 +00002031 PyMem_Free(buf);
2032 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002033 }
2034 }
2035 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002036 }
2037 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002038}
Tim Peters9905b942003-03-20 20:53:32 +00002039
2040/*----------------------------------------------------------------------------
2041 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002042 */
2043int
2044_PyFloat_Pack4(double x, unsigned char *p, int le)
2045{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002046 if (float_format == unknown_format) {
2047 unsigned char sign;
2048 int e;
2049 double f;
2050 unsigned int fbits;
2051 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002052
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002053 if (le) {
2054 p += 3;
2055 incr = -1;
2056 }
Tim Peters9905b942003-03-20 20:53:32 +00002057
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002058 if (x < 0) {
2059 sign = 1;
2060 x = -x;
2061 }
2062 else
2063 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002064
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002065 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002066
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002067 /* Normalize f to be in the range [1.0, 2.0) */
2068 if (0.5 <= f && f < 1.0) {
2069 f *= 2.0;
2070 e--;
2071 }
2072 else if (f == 0.0)
2073 e = 0;
2074 else {
2075 PyErr_SetString(PyExc_SystemError,
2076 "frexp() result out of range");
2077 return -1;
2078 }
2079
2080 if (e >= 128)
2081 goto Overflow;
2082 else if (e < -126) {
2083 /* Gradual underflow */
2084 f = ldexp(f, 126 + e);
2085 e = 0;
2086 }
2087 else if (!(e == 0 && f == 0.0)) {
2088 e += 127;
2089 f -= 1.0; /* Get rid of leading 1 */
2090 }
2091
2092 f *= 8388608.0; /* 2**23 */
2093 fbits = (unsigned int)(f + 0.5); /* Round */
2094 assert(fbits <= 8388608);
2095 if (fbits >> 23) {
2096 /* The carry propagated out of a string of 23 1 bits. */
2097 fbits = 0;
2098 ++e;
2099 if (e >= 255)
2100 goto Overflow;
2101 }
2102
2103 /* First byte */
2104 *p = (sign << 7) | (e >> 1);
2105 p += incr;
2106
2107 /* Second byte */
2108 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2109 p += incr;
2110
2111 /* Third byte */
2112 *p = (fbits >> 8) & 0xFF;
2113 p += incr;
2114
2115 /* Fourth byte */
2116 *p = fbits & 0xFF;
2117
2118 /* Done */
2119 return 0;
2120
Tim Peters9905b942003-03-20 20:53:32 +00002121 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002123 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124 const char *s = (char*)&y;
2125 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002126
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002127 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2128 goto Overflow;
2129
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002130 if ((float_format == ieee_little_endian_format && !le)
2131 || (float_format == ieee_big_endian_format && le)) {
2132 p += 3;
2133 incr = -1;
2134 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002135
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002136 for (i = 0; i < 4; i++) {
2137 *p = *s++;
2138 p += incr;
2139 }
2140 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002141 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002142 Overflow:
2143 PyErr_SetString(PyExc_OverflowError,
2144 "float too large to pack with f format");
2145 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002146}
2147
2148int
2149_PyFloat_Pack8(double x, unsigned char *p, int le)
2150{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002151 if (double_format == unknown_format) {
2152 unsigned char sign;
2153 int e;
2154 double f;
2155 unsigned int fhi, flo;
2156 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002157
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158 if (le) {
2159 p += 7;
2160 incr = -1;
2161 }
Tim Peters9905b942003-03-20 20:53:32 +00002162
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002163 if (x < 0) {
2164 sign = 1;
2165 x = -x;
2166 }
2167 else
2168 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002169
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002170 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002171
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002172 /* Normalize f to be in the range [1.0, 2.0) */
2173 if (0.5 <= f && f < 1.0) {
2174 f *= 2.0;
2175 e--;
2176 }
2177 else if (f == 0.0)
2178 e = 0;
2179 else {
2180 PyErr_SetString(PyExc_SystemError,
2181 "frexp() result out of range");
2182 return -1;
2183 }
2184
2185 if (e >= 1024)
2186 goto Overflow;
2187 else if (e < -1022) {
2188 /* Gradual underflow */
2189 f = ldexp(f, 1022 + e);
2190 e = 0;
2191 }
2192 else if (!(e == 0 && f == 0.0)) {
2193 e += 1023;
2194 f -= 1.0; /* Get rid of leading 1 */
2195 }
2196
2197 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2198 f *= 268435456.0; /* 2**28 */
2199 fhi = (unsigned int)f; /* Truncate */
2200 assert(fhi < 268435456);
2201
2202 f -= (double)fhi;
2203 f *= 16777216.0; /* 2**24 */
2204 flo = (unsigned int)(f + 0.5); /* Round */
2205 assert(flo <= 16777216);
2206 if (flo >> 24) {
2207 /* The carry propagated out of a string of 24 1 bits. */
2208 flo = 0;
2209 ++fhi;
2210 if (fhi >> 28) {
2211 /* And it also progagated out of the next 28 bits. */
2212 fhi = 0;
2213 ++e;
2214 if (e >= 2047)
2215 goto Overflow;
2216 }
2217 }
2218
2219 /* First byte */
2220 *p = (sign << 7) | (e >> 4);
2221 p += incr;
2222
2223 /* Second byte */
2224 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2225 p += incr;
2226
2227 /* Third byte */
2228 *p = (fhi >> 16) & 0xFF;
2229 p += incr;
2230
2231 /* Fourth byte */
2232 *p = (fhi >> 8) & 0xFF;
2233 p += incr;
2234
2235 /* Fifth byte */
2236 *p = fhi & 0xFF;
2237 p += incr;
2238
2239 /* Sixth byte */
2240 *p = (flo >> 16) & 0xFF;
2241 p += incr;
2242
2243 /* Seventh byte */
2244 *p = (flo >> 8) & 0xFF;
2245 p += incr;
2246
2247 /* Eighth byte */
2248 *p = flo & 0xFF;
2249 p += incr;
2250
2251 /* Done */
2252 return 0;
2253
2254 Overflow:
2255 PyErr_SetString(PyExc_OverflowError,
2256 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002257 return -1;
2258 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002259 else {
2260 const char *s = (char*)&x;
2261 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002262
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002263 if ((double_format == ieee_little_endian_format && !le)
2264 || (double_format == ieee_big_endian_format && le)) {
2265 p += 7;
2266 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002267 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002268
2269 for (i = 0; i < 8; i++) {
2270 *p = *s++;
2271 p += incr;
2272 }
2273 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002274 }
Tim Peters9905b942003-03-20 20:53:32 +00002275}
2276
2277double
2278_PyFloat_Unpack4(const unsigned char *p, int le)
2279{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002280 if (float_format == unknown_format) {
2281 unsigned char sign;
2282 int e;
2283 unsigned int f;
2284 double x;
2285 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002286
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002287 if (le) {
2288 p += 3;
2289 incr = -1;
2290 }
2291
2292 /* First byte */
2293 sign = (*p >> 7) & 1;
2294 e = (*p & 0x7F) << 1;
2295 p += incr;
2296
2297 /* Second byte */
2298 e |= (*p >> 7) & 1;
2299 f = (*p & 0x7F) << 16;
2300 p += incr;
2301
2302 if (e == 255) {
2303 PyErr_SetString(
2304 PyExc_ValueError,
2305 "can't unpack IEEE 754 special value "
2306 "on non-IEEE platform");
2307 return -1;
2308 }
2309
2310 /* Third byte */
2311 f |= *p << 8;
2312 p += incr;
2313
2314 /* Fourth byte */
2315 f |= *p;
2316
2317 x = (double)f / 8388608.0;
2318
2319 /* XXX This sadly ignores Inf/NaN issues */
2320 if (e == 0)
2321 e = -126;
2322 else {
2323 x += 1.0;
2324 e -= 127;
2325 }
2326 x = ldexp(x, e);
2327
2328 if (sign)
2329 x = -x;
2330
2331 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002332 }
Tim Peters9905b942003-03-20 20:53:32 +00002333 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002334 float x;
2335
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336 if ((float_format == ieee_little_endian_format && !le)
2337 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002338 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002339 char *d = &buf[3];
2340 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002341
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002342 for (i = 0; i < 4; i++) {
2343 *d-- = *p++;
2344 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002345 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002346 }
2347 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002348 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002349 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002350
2351 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002352 }
Tim Peters9905b942003-03-20 20:53:32 +00002353}
2354
2355double
2356_PyFloat_Unpack8(const unsigned char *p, int le)
2357{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002358 if (double_format == unknown_format) {
2359 unsigned char sign;
2360 int e;
2361 unsigned int fhi, flo;
2362 double x;
2363 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002364
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002365 if (le) {
2366 p += 7;
2367 incr = -1;
2368 }
2369
2370 /* First byte */
2371 sign = (*p >> 7) & 1;
2372 e = (*p & 0x7F) << 4;
2373
2374 p += incr;
2375
2376 /* Second byte */
2377 e |= (*p >> 4) & 0xF;
2378 fhi = (*p & 0xF) << 24;
2379 p += incr;
2380
2381 if (e == 2047) {
2382 PyErr_SetString(
2383 PyExc_ValueError,
2384 "can't unpack IEEE 754 special value "
2385 "on non-IEEE platform");
2386 return -1.0;
2387 }
2388
2389 /* Third byte */
2390 fhi |= *p << 16;
2391 p += incr;
2392
2393 /* Fourth byte */
2394 fhi |= *p << 8;
2395 p += incr;
2396
2397 /* Fifth byte */
2398 fhi |= *p;
2399 p += incr;
2400
2401 /* Sixth byte */
2402 flo = *p << 16;
2403 p += incr;
2404
2405 /* Seventh byte */
2406 flo |= *p << 8;
2407 p += incr;
2408
2409 /* Eighth byte */
2410 flo |= *p;
2411
2412 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2413 x /= 268435456.0; /* 2**28 */
2414
2415 if (e == 0)
2416 e = -1022;
2417 else {
2418 x += 1.0;
2419 e -= 1023;
2420 }
2421 x = ldexp(x, e);
2422
2423 if (sign)
2424 x = -x;
2425
2426 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002427 }
Tim Peters9905b942003-03-20 20:53:32 +00002428 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002429 double x;
2430
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002431 if ((double_format == ieee_little_endian_format && !le)
2432 || (double_format == ieee_big_endian_format && le)) {
2433 char buf[8];
2434 char *d = &buf[7];
2435 int i;
2436
2437 for (i = 0; i < 8; i++) {
2438 *d-- = *p++;
2439 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002440 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002441 }
2442 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002443 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002444 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002445
2446 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002447 }
Tim Peters9905b942003-03-20 20:53:32 +00002448}