blob: 73d7903805d95cac406b282f2c68dcb16ecff54c [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
Tim Peters97019e42001-11-28 22:43:45 +0000338/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
339 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 Smitha985a3a2009-05-05 18:26:08 +0000344 _PyOS_double_to_string(buf, 100, v->ob_fval, 'g', PyFloat_STR_PRECISION,
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000345 Py_DTSF_ADD_DOT_0, NULL);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000346}
347
Tim Peters72f98e92001-05-08 15:19:57 +0000348void
349PyFloat_AsReprString(char *buf, PyFloatObject *v)
350{
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000351 _PyOS_double_to_string(buf, 100, v->ob_fval, 'r', 0,
352 Py_DTSF_ADD_DOT_0, NULL);
Tim Peters72f98e92001-05-08 15:19:57 +0000353}
354
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000355/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000356static int
Fred Drakefd99de62000-07-09 05:02:18 +0000357float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358{
359 char buf[100];
Eric Smitha985a3a2009-05-05 18:26:08 +0000360 if (flags & Py_PRINT_RAW)
361 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval,
362 'g', PyFloat_STR_PRECISION,
363 Py_DTSF_ADD_DOT_0, NULL);
364 else
365 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval,
366 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
Brett Cannon01531592007-09-17 03:28:34 +0000367 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000369 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000370 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371}
372
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000374float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000376 char buf[100];
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000377 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval, 'r', 0,
378 Py_DTSF_ADD_DOT_0, NULL);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000379 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000380}
381
382static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000383float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000384{
385 char buf[100];
Eric Smitha985a3a2009-05-05 18:26:08 +0000386 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval, 'g',
387 PyFloat_STR_PRECISION,
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000388 Py_DTSF_ADD_DOT_0, NULL);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000389 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390}
391
Tim Peters307fa782004-09-23 08:06:40 +0000392/* Comparison is pretty much a nightmare. When comparing float to float,
393 * we do it as straightforwardly (and long-windedly) as conceivable, so
394 * that, e.g., Python x == y delivers the same result as the platform
395 * C x == y when x and/or y is a NaN.
396 * When mixing float with an integer type, there's no good *uniform* approach.
397 * Converting the double to an integer obviously doesn't work, since we
398 * may lose info from fractional bits. Converting the integer to a double
399 * also has two failure modes: (1) a long int may trigger overflow (too
400 * large to fit in the dynamic range of a C double); (2) even a C long may have
401 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
402 * 63 bits of precision, but a C double probably has only 53), and then
403 * we can falsely claim equality when low-order integer bits are lost by
404 * coercion to double. So this part is painful too.
405 */
406
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000407static PyObject*
408float_richcompare(PyObject *v, PyObject *w, int op)
409{
410 double i, j;
411 int r = 0;
412
Tim Peters307fa782004-09-23 08:06:40 +0000413 assert(PyFloat_Check(v));
414 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000415
Tim Peters307fa782004-09-23 08:06:40 +0000416 /* Switch on the type of w. Set i and j to doubles to be compared,
417 * and op to the richcomp to use.
418 */
419 if (PyFloat_Check(w))
420 j = PyFloat_AS_DOUBLE(w);
421
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000422 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000423 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000424 /* If i is an infinity, its magnitude exceeds any
425 * finite integer, so it doesn't matter which int we
426 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000427 */
428 j = 0.0;
429 else
430 goto Unimplemented;
431 }
432
433 else if (PyInt_Check(w)) {
434 long jj = PyInt_AS_LONG(w);
435 /* In the worst realistic case I can imagine, C double is a
436 * Cray single with 48 bits of precision, and long has 64
437 * bits.
438 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000439#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000440 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
441 if (abs >> 48) {
442 /* Needs more than 48 bits. Make it take the
443 * PyLong path.
444 */
445 PyObject *result;
446 PyObject *ww = PyLong_FromLong(jj);
447
448 if (ww == NULL)
449 return NULL;
450 result = float_richcompare(v, ww, op);
451 Py_DECREF(ww);
452 return result;
453 }
454#endif
455 j = (double)jj;
456 assert((long)j == jj);
457 }
458
459 else if (PyLong_Check(w)) {
460 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
461 int wsign = _PyLong_Sign(w);
462 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000463 int exponent;
464
465 if (vsign != wsign) {
466 /* Magnitudes are irrelevant -- the signs alone
467 * determine the outcome.
468 */
469 i = (double)vsign;
470 j = (double)wsign;
471 goto Compare;
472 }
473 /* The signs are the same. */
474 /* Convert w to a double if it fits. In particular, 0 fits. */
475 nbits = _PyLong_NumBits(w);
476 if (nbits == (size_t)-1 && PyErr_Occurred()) {
477 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000478 * to hold the # of bits. Replace with little doubles
479 * that give the same outcome -- w is so large that
480 * its magnitude must exceed the magnitude of any
481 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000482 */
483 PyErr_Clear();
484 i = (double)vsign;
485 assert(wsign != 0);
486 j = wsign * 2.0;
487 goto Compare;
488 }
489 if (nbits <= 48) {
490 j = PyLong_AsDouble(w);
491 /* It's impossible that <= 48 bits overflowed. */
492 assert(j != -1.0 || ! PyErr_Occurred());
493 goto Compare;
494 }
495 assert(wsign != 0); /* else nbits was 0 */
496 assert(vsign != 0); /* if vsign were 0, then since wsign is
497 * not 0, we would have taken the
498 * vsign != wsign branch at the start */
499 /* We want to work with non-negative numbers. */
500 if (vsign < 0) {
501 /* "Multiply both sides" by -1; this also swaps the
502 * comparator.
503 */
504 i = -i;
505 op = _Py_SwappedOp[op];
506 }
507 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000508 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000509 /* exponent is the # of bits in v before the radix point;
510 * we know that nbits (the # of bits in w) > 48 at this point
511 */
512 if (exponent < 0 || (size_t)exponent < nbits) {
513 i = 1.0;
514 j = 2.0;
515 goto Compare;
516 }
517 if ((size_t)exponent > nbits) {
518 i = 2.0;
519 j = 1.0;
520 goto Compare;
521 }
522 /* v and w have the same number of bits before the radix
523 * point. Construct two longs that have the same comparison
524 * outcome.
525 */
526 {
527 double fracpart;
528 double intpart;
529 PyObject *result = NULL;
530 PyObject *one = NULL;
531 PyObject *vv = NULL;
532 PyObject *ww = w;
533
534 if (wsign < 0) {
535 ww = PyNumber_Negative(w);
536 if (ww == NULL)
537 goto Error;
538 }
539 else
540 Py_INCREF(ww);
541
542 fracpart = modf(i, &intpart);
543 vv = PyLong_FromDouble(intpart);
544 if (vv == NULL)
545 goto Error;
546
547 if (fracpart != 0.0) {
548 /* Shift left, and or a 1 bit into vv
549 * to represent the lost fraction.
550 */
551 PyObject *temp;
552
553 one = PyInt_FromLong(1);
554 if (one == NULL)
555 goto Error;
556
557 temp = PyNumber_Lshift(ww, one);
558 if (temp == NULL)
559 goto Error;
560 Py_DECREF(ww);
561 ww = temp;
562
563 temp = PyNumber_Lshift(vv, one);
564 if (temp == NULL)
565 goto Error;
566 Py_DECREF(vv);
567 vv = temp;
568
569 temp = PyNumber_Or(vv, one);
570 if (temp == NULL)
571 goto Error;
572 Py_DECREF(vv);
573 vv = temp;
574 }
575
576 r = PyObject_RichCompareBool(vv, ww, op);
577 if (r < 0)
578 goto Error;
579 result = PyBool_FromLong(r);
580 Error:
581 Py_XDECREF(vv);
582 Py_XDECREF(ww);
583 Py_XDECREF(one);
584 return result;
585 }
586 } /* else if (PyLong_Check(w)) */
587
588 else /* w isn't float, int, or long */
589 goto Unimplemented;
590
591 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000592 PyFPE_START_PROTECT("richcompare", return NULL)
593 switch (op) {
594 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000595 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000596 break;
597 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000598 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000599 break;
600 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000601 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000602 break;
603 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000604 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000605 break;
606 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000607 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000608 break;
609 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000610 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000611 break;
612 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000613 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000614 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000615
616 Unimplemented:
617 Py_INCREF(Py_NotImplemented);
618 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000619}
620
Guido van Rossum9bfef441993-03-29 10:43:31 +0000621static long
Fred Drakefd99de62000-07-09 05:02:18 +0000622float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000623{
Tim Peters39dce292000-08-15 03:34:48 +0000624 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000625}
626
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000628float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000630 double a,b;
631 CONVERT_TO_DOUBLE(v, a);
632 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000633 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000634 a = a + b;
635 PyFPE_END_PROTECT(a)
636 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000640float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000642 double a,b;
643 CONVERT_TO_DOUBLE(v, a);
644 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000645 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000646 a = a - b;
647 PyFPE_END_PROTECT(a)
648 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649}
650
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000651static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000652float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000654 double a,b;
655 CONVERT_TO_DOUBLE(v, a);
656 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000657 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000658 a = a * b;
659 PyFPE_END_PROTECT(a)
660 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661}
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000664float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000665{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000666 double a,b;
667 CONVERT_TO_DOUBLE(v, a);
668 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000669#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000670 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000671 PyErr_SetString(PyExc_ZeroDivisionError,
672 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000673 return NULL;
674 }
Christian Heimes6f341092008-04-18 23:13:07 +0000675#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000676 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677 a = a / b;
678 PyFPE_END_PROTECT(a)
679 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680}
681
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000683float_classic_div(PyObject *v, PyObject *w)
684{
685 double a,b;
686 CONVERT_TO_DOUBLE(v, a);
687 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000688 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000689 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
690 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000691#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000692 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000693 PyErr_SetString(PyExc_ZeroDivisionError,
694 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000695 return NULL;
696 }
Christian Heimes6f341092008-04-18 23:13:07 +0000697#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000698 PyFPE_START_PROTECT("divide", return 0)
699 a = a / b;
700 PyFPE_END_PROTECT(a)
701 return PyFloat_FromDouble(a);
702}
703
704static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000705float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000706{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000707 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000708 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000709 CONVERT_TO_DOUBLE(v, vx);
710 CONVERT_TO_DOUBLE(w, wx);
711#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000713 PyErr_SetString(PyExc_ZeroDivisionError,
714 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715 return NULL;
716 }
Christian Heimes6f341092008-04-18 23:13:07 +0000717#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000718 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000719 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000720 /* note: checking mod*wx < 0 is incorrect -- underflows to
721 0 if wx < sqrt(smallest nonzero double) */
722 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000723 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000724 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000725 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727}
728
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000730float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000731{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000732 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000733 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000734 CONVERT_TO_DOUBLE(v, vx);
735 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000736 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000738 return NULL;
739 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000740 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000741 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000742 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000743 exact multiple of wx. But this is fp arithmetic, and fp
744 vx - mod is an approximation; the result is that div may
745 not be an exact integral value after the division, although
746 it will always be very close to one.
747 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000748 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000749 if (mod) {
750 /* ensure the remainder has the same sign as the denominator */
751 if ((wx < 0) != (mod < 0)) {
752 mod += wx;
753 div -= 1.0;
754 }
755 }
756 else {
757 /* the remainder is zero, and in the presence of signed zeroes
758 fmod returns different results across platforms; ensure
759 it has the same sign as the denominator; we'd like to do
760 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000761 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000762 if (wx < 0.0)
763 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000764 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000765 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000766 if (div) {
767 floordiv = floor(div);
768 if (div - floordiv > 0.5)
769 floordiv += 1.0;
770 }
771 else {
772 /* div is zero - get the same sign as the true quotient */
773 div *= div; /* hide "div = +0" from optimizers */
774 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
775 }
776 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000777 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000778}
779
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000780static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000781float_floor_div(PyObject *v, PyObject *w)
782{
783 PyObject *t, *r;
784
785 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000786 if (t == NULL || t == Py_NotImplemented)
787 return t;
788 assert(PyTuple_CheckExact(t));
789 r = PyTuple_GET_ITEM(t, 0);
790 Py_INCREF(r);
791 Py_DECREF(t);
792 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000793}
794
795static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000796float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000797{
798 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000799
800 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000801 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000802 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000803 return NULL;
804 }
805
Neil Schemenauer32117e52001-01-04 01:44:34 +0000806 CONVERT_TO_DOUBLE(v, iv);
807 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000808
809 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000810 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000811 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000812 }
Tim Peters96685bf2001-08-23 22:31:37 +0000813 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000814 if (iw < 0.0) {
815 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000816 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000817 return NULL;
818 }
819 return PyFloat_FromDouble(0.0);
820 }
Christian Heimes6f341092008-04-18 23:13:07 +0000821 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
822 return PyFloat_FromDouble(1.0);
823 }
Tim Peterse87568d2003-05-24 20:18:24 +0000824 if (iv < 0.0) {
825 /* Whether this is an error is a mess, and bumps into libm
826 * bugs so we have to figure it out ourselves.
827 */
828 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000829 PyErr_SetString(PyExc_ValueError, "negative number "
830 "cannot be raised to a fractional power");
831 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000832 }
833 /* iw is an exact integer, albeit perhaps a very large one.
834 * -1 raised to an exact integer should never be exceptional.
835 * Alas, some libms (chiefly glibc as of early 2003) return
836 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
837 * happen to be representable in a *C* integer. That's a
838 * bug; we let that slide in math.pow() (which currently
839 * reflects all platform accidents), but not for Python's **.
840 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000841 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000842 /* Return 1 if iw is even, -1 if iw is odd; there's
843 * no guarantee that any C integral type is big
844 * enough to hold iw, so we have to check this
845 * indirectly.
846 */
847 ix = floor(iw * 0.5) * 2.0;
848 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
849 }
850 /* Else iv != -1.0, and overflow or underflow are possible.
851 * Unless we're to write pow() ourselves, we have to trust
852 * the platform to do this correctly.
853 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000854 }
Tim Peters96685bf2001-08-23 22:31:37 +0000855 errno = 0;
856 PyFPE_START_PROTECT("pow", return NULL)
857 ix = pow(iv, iw);
858 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000859 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000860 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000861 /* We don't expect any errno value other than ERANGE, but
862 * the range of libm bugs appears unbounded.
863 */
Alex Martelli348dc882006-08-23 22:17:59 +0000864 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
865 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000866 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000867 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000868 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869}
870
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000871static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000872float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000873{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000874 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875}
876
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000878float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000879{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000880 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000881}
882
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000883static int
Fred Drakefd99de62000-07-09 05:02:18 +0000884float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000885{
886 return v->ob_fval != 0.0;
887}
888
Guido van Rossum234f9421993-06-17 12:35:49 +0000889static int
Fred Drakefd99de62000-07-09 05:02:18 +0000890float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000891{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000892 if (PyInt_Check(*pw)) {
893 long x = PyInt_AsLong(*pw);
894 *pw = PyFloat_FromDouble((double)x);
895 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000896 return 0;
897 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000898 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000899 double x = PyLong_AsDouble(*pw);
900 if (x == -1.0 && PyErr_Occurred())
901 return -1;
902 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000903 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000904 return 0;
905 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000906 else if (PyFloat_Check(*pw)) {
907 Py_INCREF(*pv);
908 Py_INCREF(*pw);
909 return 0;
910 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000911 return 1; /* Can't do it */
912}
913
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000914static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000915float_is_integer(PyObject *v)
916{
917 double x = PyFloat_AsDouble(v);
918 PyObject *o;
919
920 if (x == -1.0 && PyErr_Occurred())
921 return NULL;
922 if (!Py_IS_FINITE(x))
923 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +0000924 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000925 PyFPE_START_PROTECT("is_integer", return NULL)
926 o = (floor(x) == x) ? Py_True : Py_False;
927 PyFPE_END_PROTECT(x)
928 if (errno != 0) {
929 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
930 PyExc_ValueError);
931 return NULL;
932 }
933 Py_INCREF(o);
934 return o;
935}
936
937#if 0
938static PyObject *
939float_is_inf(PyObject *v)
940{
941 double x = PyFloat_AsDouble(v);
942 if (x == -1.0 && PyErr_Occurred())
943 return NULL;
944 return PyBool_FromLong((long)Py_IS_INFINITY(x));
945}
946
947static PyObject *
948float_is_nan(PyObject *v)
949{
950 double x = PyFloat_AsDouble(v);
951 if (x == -1.0 && PyErr_Occurred())
952 return NULL;
953 return PyBool_FromLong((long)Py_IS_NAN(x));
954}
955
956static PyObject *
957float_is_finite(PyObject *v)
958{
959 double x = PyFloat_AsDouble(v);
960 if (x == -1.0 && PyErr_Occurred())
961 return NULL;
962 return PyBool_FromLong((long)Py_IS_FINITE(x));
963}
964#endif
965
966static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000967float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000968{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000969 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000970 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000971
972 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000973 /* Try to get out cheap if this fits in a Python int. The attempt
974 * to cast to long must be protected, as C doesn't define what
975 * happens if the double is too big to fit in a long. Some rare
976 * systems raise an exception then (RISCOS was mentioned as one,
977 * and someone using a non-default option on Sun also bumped into
978 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
979 * still be vulnerable: if a long has more bits of precision than
980 * a double, casting MIN/MAX to double may yield an approximation,
981 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
982 * yield true from the C expression wholepart<=LONG_MAX, despite
983 * that wholepart is actually greater than LONG_MAX.
984 */
985 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
986 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000987 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000988 }
989 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000990}
991
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +0000993float_long(PyObject *v)
994{
995 double x = PyFloat_AsDouble(v);
996 return PyLong_FromDouble(x);
997}
998
999static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001000float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001001{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001002 if (PyFloat_CheckExact(v))
1003 Py_INCREF(v);
1004 else
1005 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001006 return v;
1007}
1008
Mark Dickinson7103aa42008-07-15 19:08:33 +00001009/* turn ASCII hex characters into integer values and vice versa */
1010
1011static char
1012char_from_hex(int x)
1013{
1014 assert(0 <= x && x < 16);
1015 return "0123456789abcdef"[x];
1016}
1017
1018static int
1019hex_from_char(char c) {
1020 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001021 switch(c) {
1022 case '0':
1023 x = 0;
1024 break;
1025 case '1':
1026 x = 1;
1027 break;
1028 case '2':
1029 x = 2;
1030 break;
1031 case '3':
1032 x = 3;
1033 break;
1034 case '4':
1035 x = 4;
1036 break;
1037 case '5':
1038 x = 5;
1039 break;
1040 case '6':
1041 x = 6;
1042 break;
1043 case '7':
1044 x = 7;
1045 break;
1046 case '8':
1047 x = 8;
1048 break;
1049 case '9':
1050 x = 9;
1051 break;
1052 case 'a':
1053 case 'A':
1054 x = 10;
1055 break;
1056 case 'b':
1057 case 'B':
1058 x = 11;
1059 break;
1060 case 'c':
1061 case 'C':
1062 x = 12;
1063 break;
1064 case 'd':
1065 case 'D':
1066 x = 13;
1067 break;
1068 case 'e':
1069 case 'E':
1070 x = 14;
1071 break;
1072 case 'f':
1073 case 'F':
1074 x = 15;
1075 break;
1076 default:
1077 x = -1;
1078 break;
1079 }
1080 return x;
1081}
1082
1083/* convert a float to a hexadecimal string */
1084
1085/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1086 of the form 4k+1. */
1087#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1088
1089static PyObject *
1090float_hex(PyObject *v)
1091{
1092 double x, m;
1093 int e, shift, i, si, esign;
1094 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1095 trailing NUL byte. */
1096 char s[(TOHEX_NBITS-1)/4+3];
1097
1098 CONVERT_TO_DOUBLE(v, x);
1099
1100 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1101 return float_str((PyFloatObject *)v);
1102
1103 if (x == 0.0) {
1104 if(copysign(1.0, x) == -1.0)
1105 return PyString_FromString("-0x0.0p+0");
1106 else
1107 return PyString_FromString("0x0.0p+0");
1108 }
1109
1110 m = frexp(fabs(x), &e);
1111 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1112 m = ldexp(m, shift);
1113 e -= shift;
1114
1115 si = 0;
1116 s[si] = char_from_hex((int)m);
1117 si++;
1118 m -= (int)m;
1119 s[si] = '.';
1120 si++;
1121 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1122 m *= 16.0;
1123 s[si] = char_from_hex((int)m);
1124 si++;
1125 m -= (int)m;
1126 }
1127 s[si] = '\0';
1128
1129 if (e < 0) {
1130 esign = (int)'-';
1131 e = -e;
1132 }
1133 else
1134 esign = (int)'+';
1135
1136 if (x < 0.0)
1137 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1138 else
1139 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1140}
1141
1142PyDoc_STRVAR(float_hex_doc,
1143"float.hex() -> string\n\
1144\n\
1145Return a hexadecimal representation of a floating-point number.\n\
1146>>> (-0.1).hex()\n\
1147'-0x1.999999999999ap-4'\n\
1148>>> 3.14159.hex()\n\
1149'0x1.921f9f01b866ep+1'");
1150
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001151/* Case-insensitive locale-independent string match used for nan and inf
1152 detection. t should be lower-case and null-terminated. Return a nonzero
1153 result if the first strlen(t) characters of s match t and 0 otherwise. */
1154
1155static int
1156case_insensitive_match(const char *s, const char *t)
1157{
1158 while(*t && Py_TOLOWER(*s) == *t) {
1159 s++;
1160 t++;
1161 }
1162 return *t ? 0 : 1;
1163}
1164
Mark Dickinson7103aa42008-07-15 19:08:33 +00001165/* Convert a hexadecimal string to a float. */
1166
1167static PyObject *
1168float_fromhex(PyObject *cls, PyObject *arg)
1169{
1170 PyObject *result_as_float, *result;
1171 double x;
1172 long exp, top_exp, lsb, key_digit;
1173 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1174 int half_eps, digit, round_up, sign=1;
1175 Py_ssize_t length, ndigits, fdigits, i;
1176
1177 /*
1178 * For the sake of simplicity and correctness, we impose an artificial
1179 * limit on ndigits, the total number of hex digits in the coefficient
1180 * The limit is chosen to ensure that, writing exp for the exponent,
1181 *
1182 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1183 * guaranteed to overflow (provided it's nonzero)
1184 *
1185 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1186 * guaranteed to underflow to 0.
1187 *
1188 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1189 * overflow in the calculation of exp and top_exp below.
1190 *
1191 * More specifically, ndigits is assumed to satisfy the following
1192 * inequalities:
1193 *
1194 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1195 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1196 *
1197 * If either of these inequalities is not satisfied, a ValueError is
1198 * raised. Otherwise, write x for the value of the hex string, and
1199 * assume x is nonzero. Then
1200 *
1201 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1202 *
1203 * Now if exp > LONG_MAX/2 then:
1204 *
1205 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1206 * = DBL_MAX_EXP
1207 *
1208 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1209 * double, so overflows. If exp < LONG_MIN/2, then
1210 *
1211 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1212 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1213 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1214 *
1215 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1216 * when converted to a C double.
1217 *
1218 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1219 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1220 */
1221
1222 if (PyString_AsStringAndSize(arg, &s, &length))
1223 return NULL;
1224 s_end = s + length;
1225
1226 /********************
1227 * Parse the string *
1228 ********************/
1229
1230 /* leading whitespace and optional sign */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001231 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001232 s++;
1233 if (*s == '-') {
1234 s++;
1235 sign = -1;
1236 }
1237 else if (*s == '+')
1238 s++;
1239
1240 /* infinities and nans */
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001241 if (*s == 'i' || *s == 'I') {
1242 if (!case_insensitive_match(s+1, "nf"))
1243 goto parse_error;
1244 s += 3;
1245 x = Py_HUGE_VAL;
1246 if (case_insensitive_match(s, "inity"))
1247 s += 5;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001248 goto finished;
1249 }
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001250 if (*s == 'n' || *s == 'N') {
1251 if (!case_insensitive_match(s+1, "an"))
1252 goto parse_error;
1253 s += 3;
1254 x = Py_NAN;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001255 goto finished;
1256 }
1257
1258 /* [0x] */
1259 s_store = s;
1260 if (*s == '0') {
1261 s++;
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001262 if (*s == 'x' || *s == 'X')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001263 s++;
1264 else
1265 s = s_store;
1266 }
1267
1268 /* coefficient: <integer> [. <fraction>] */
1269 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001270 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001271 s++;
1272 s_store = s;
1273 if (*s == '.') {
1274 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001275 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001276 s++;
1277 coeff_end = s-1;
1278 }
1279 else
1280 coeff_end = s;
1281
1282 /* ndigits = total # of hex digits; fdigits = # after point */
1283 ndigits = coeff_end - coeff_start;
1284 fdigits = coeff_end - s_store;
1285 if (ndigits == 0)
1286 goto parse_error;
1287 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1288 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1289 goto insane_length_error;
1290
1291 /* [p <exponent>] */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001292 if (*s == 'p' || *s == 'P') {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001293 s++;
1294 exp_start = s;
1295 if (*s == '-' || *s == '+')
1296 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001297 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001298 goto parse_error;
1299 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001300 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001301 s++;
1302 exp = strtol(exp_start, NULL, 10);
1303 }
1304 else
1305 exp = 0;
1306
Mark Dickinson7103aa42008-07-15 19:08:33 +00001307/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1308#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1309 coeff_end-(j) : \
1310 coeff_end-1-(j)))
1311
1312 /*******************************************
1313 * Compute rounded value of the hex string *
1314 *******************************************/
1315
1316 /* Discard leading zeros, and catch extreme overflow and underflow */
1317 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1318 ndigits--;
1319 if (ndigits == 0 || exp < LONG_MIN/2) {
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001320 x = 0.0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001321 goto finished;
1322 }
1323 if (exp > LONG_MAX/2)
1324 goto overflow_error;
1325
1326 /* Adjust exponent for fractional part. */
1327 exp = exp - 4*((long)fdigits);
1328
1329 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1330 top_exp = exp + 4*((long)ndigits - 1);
1331 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1332 top_exp++;
1333
1334 /* catch almost all nonextreme cases of overflow and underflow here */
1335 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001336 x = 0.0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001337 goto finished;
1338 }
1339 if (top_exp > DBL_MAX_EXP)
1340 goto overflow_error;
1341
1342 /* lsb = exponent of least significant bit of the *rounded* value.
1343 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1344 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1345
1346 x = 0.0;
1347 if (exp >= lsb) {
1348 /* no rounding required */
1349 for (i = ndigits-1; i >= 0; i--)
1350 x = 16.0*x + HEX_DIGIT(i);
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001351 x = ldexp(x, (int)(exp));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001352 goto finished;
1353 }
1354 /* rounding required. key_digit is the index of the hex digit
1355 containing the first bit to be rounded away. */
1356 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1357 key_digit = (lsb - exp - 1) / 4;
1358 for (i = ndigits-1; i > key_digit; i--)
1359 x = 16.0*x + HEX_DIGIT(i);
1360 digit = HEX_DIGIT(key_digit);
1361 x = 16.0*x + (double)(digit & (16-2*half_eps));
1362
1363 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1364 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1365 if ((digit & half_eps) != 0) {
1366 round_up = 0;
1367 if ((digit & (3*half_eps-1)) != 0 ||
1368 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1369 round_up = 1;
1370 else
1371 for (i = key_digit-1; i >= 0; i--)
1372 if (HEX_DIGIT(i) != 0) {
1373 round_up = 1;
1374 break;
1375 }
1376 if (round_up == 1) {
1377 x += 2*half_eps;
1378 if (top_exp == DBL_MAX_EXP &&
1379 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1380 /* overflow corner case: pre-rounded value <
1381 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1382 goto overflow_error;
1383 }
1384 }
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001385 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001386
1387 finished:
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001388 /* optional trailing whitespace leading to the end of the string */
1389 while (Py_ISSPACE(*s))
1390 s++;
1391 if (s != s_end)
1392 goto parse_error;
1393 result_as_float = Py_BuildValue("(d)", sign * x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001394 if (result_as_float == NULL)
1395 return NULL;
1396 result = PyObject_CallObject(cls, result_as_float);
1397 Py_DECREF(result_as_float);
1398 return result;
1399
1400 overflow_error:
1401 PyErr_SetString(PyExc_OverflowError,
1402 "hexadecimal value too large to represent as a float");
1403 return NULL;
1404
1405 parse_error:
1406 PyErr_SetString(PyExc_ValueError,
1407 "invalid hexadecimal floating-point string");
1408 return NULL;
1409
1410 insane_length_error:
1411 PyErr_SetString(PyExc_ValueError,
1412 "hexadecimal string too long to convert");
1413 return NULL;
1414}
1415
1416PyDoc_STRVAR(float_fromhex_doc,
1417"float.fromhex(string) -> float\n\
1418\n\
1419Create a floating-point number from a hexadecimal string.\n\
1420>>> float.fromhex('0x1.ffffp10')\n\
14212047.984375\n\
1422>>> float.fromhex('-0x1p-1074')\n\
1423-4.9406564584124654e-324");
1424
1425
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001426static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001427float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001428{
1429 double self;
1430 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001431 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001432 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001433
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001434 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001435 PyObject *py_exponent = NULL;
1436 PyObject *numerator = NULL;
1437 PyObject *denominator = NULL;
1438 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001439 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001440
1441#define INPLACE_UPDATE(obj, call) \
1442 prev = obj; \
1443 obj = call; \
1444 Py_DECREF(prev); \
1445
1446 CONVERT_TO_DOUBLE(v, self);
1447
1448 if (Py_IS_INFINITY(self)) {
1449 PyErr_SetString(PyExc_OverflowError,
1450 "Cannot pass infinity to float.as_integer_ratio.");
1451 return NULL;
1452 }
1453#ifdef Py_NAN
1454 if (Py_IS_NAN(self)) {
1455 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001456 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001457 return NULL;
1458 }
1459#endif
1460
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001461 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001462 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001463 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001464
Raymond Hettingerf9859032008-02-01 23:45:44 +00001465 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001466 float_part *= 2.0;
1467 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001468 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001469 /* self == float_part * 2**exponent exactly and float_part is integral.
1470 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1471 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001472
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001473 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001474 if (numerator == NULL) goto error;
1475
Raymond Hettingerf9859032008-02-01 23:45:44 +00001476 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001477 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001478 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001479 if (py_exponent == NULL) goto error;
1480 INPLACE_UPDATE(py_exponent,
1481 long_methods->nb_lshift(denominator, py_exponent));
1482 if (py_exponent == NULL) goto error;
1483 if (exponent > 0) {
1484 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001485 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001486 if (numerator == NULL) goto error;
1487 }
1488 else {
1489 Py_DECREF(denominator);
1490 denominator = py_exponent;
1491 py_exponent = NULL;
1492 }
1493
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001494 /* Returns ints instead of longs where possible */
1495 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1496 if (numerator == NULL) goto error;
1497 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1498 if (denominator == NULL) goto error;
1499
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001500 result_pair = PyTuple_Pack(2, numerator, denominator);
1501
1502#undef INPLACE_UPDATE
1503error:
1504 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001505 Py_XDECREF(denominator);
1506 Py_XDECREF(numerator);
1507 return result_pair;
1508}
1509
1510PyDoc_STRVAR(float_as_integer_ratio_doc,
1511"float.as_integer_ratio() -> (int, int)\n"
1512"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001513"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1514"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001515"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001516"\n"
1517">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001518"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001519">>> (0.0).as_integer_ratio()\n"
1520"(0, 1)\n"
1521">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001522"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001523
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001524
Jeremy Hylton938ace62002-07-17 16:30:39 +00001525static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001526float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1527
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528static PyObject *
1529float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1530{
1531 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001532 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533
Guido van Rossumbef14172001-08-29 15:47:46 +00001534 if (type != &PyFloat_Type)
1535 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1537 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001538 /* If it's a string, but not a string subclass, use
1539 PyFloat_FromString. */
1540 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 return PyFloat_FromString(x, NULL);
1542 return PyNumber_Float(x);
1543}
1544
Guido van Rossumbef14172001-08-29 15:47:46 +00001545/* Wimpy, slow approach to tp_new calls for subtypes of float:
1546 first create a regular float from whatever arguments we got,
1547 then allocate a subtype instance and initialize its ob_fval
1548 from the regular float. The regular float is then thrown away.
1549*/
1550static PyObject *
1551float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1552{
Anthony Baxter377be112006-04-11 06:54:30 +00001553 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001554
1555 assert(PyType_IsSubtype(type, &PyFloat_Type));
1556 tmp = float_new(&PyFloat_Type, args, kwds);
1557 if (tmp == NULL)
1558 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001559 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001560 newobj = type->tp_alloc(type, 0);
1561 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001562 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001563 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001564 }
Anthony Baxter377be112006-04-11 06:54:30 +00001565 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001566 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001567 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001568}
1569
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001570static PyObject *
1571float_getnewargs(PyFloatObject *v)
1572{
1573 return Py_BuildValue("(d)", v->ob_fval);
1574}
1575
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001576/* this is for the benefit of the pack/unpack routines below */
1577
1578typedef enum {
1579 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1580} float_format_type;
1581
1582static float_format_type double_format, float_format;
1583static float_format_type detected_double_format, detected_float_format;
1584
1585static PyObject *
1586float_getformat(PyTypeObject *v, PyObject* arg)
1587{
1588 char* s;
1589 float_format_type r;
1590
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001591 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001592 PyErr_Format(PyExc_TypeError,
1593 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001594 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001595 return NULL;
1596 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001597 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001598 if (strcmp(s, "double") == 0) {
1599 r = double_format;
1600 }
1601 else if (strcmp(s, "float") == 0) {
1602 r = float_format;
1603 }
1604 else {
1605 PyErr_SetString(PyExc_ValueError,
1606 "__getformat__() argument 1 must be "
1607 "'double' or 'float'");
1608 return NULL;
1609 }
1610
1611 switch (r) {
1612 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001613 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001615 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001616 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001617 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618 default:
1619 Py_FatalError("insane float_format or double_format");
1620 return NULL;
1621 }
1622}
1623
1624PyDoc_STRVAR(float_getformat_doc,
1625"float.__getformat__(typestr) -> string\n"
1626"\n"
1627"You probably don't want to use this function. It exists mainly to be\n"
1628"used in Python's test suite.\n"
1629"\n"
1630"typestr must be 'double' or 'float'. This function returns whichever of\n"
1631"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1632"format of floating point numbers used by the C type named by typestr.");
1633
1634static PyObject *
1635float_setformat(PyTypeObject *v, PyObject* args)
1636{
1637 char* typestr;
1638 char* format;
1639 float_format_type f;
1640 float_format_type detected;
1641 float_format_type *p;
1642
1643 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1644 return NULL;
1645
1646 if (strcmp(typestr, "double") == 0) {
1647 p = &double_format;
1648 detected = detected_double_format;
1649 }
1650 else if (strcmp(typestr, "float") == 0) {
1651 p = &float_format;
1652 detected = detected_float_format;
1653 }
1654 else {
1655 PyErr_SetString(PyExc_ValueError,
1656 "__setformat__() argument 1 must "
1657 "be 'double' or 'float'");
1658 return NULL;
1659 }
1660
1661 if (strcmp(format, "unknown") == 0) {
1662 f = unknown_format;
1663 }
1664 else if (strcmp(format, "IEEE, little-endian") == 0) {
1665 f = ieee_little_endian_format;
1666 }
1667 else if (strcmp(format, "IEEE, big-endian") == 0) {
1668 f = ieee_big_endian_format;
1669 }
1670 else {
1671 PyErr_SetString(PyExc_ValueError,
1672 "__setformat__() argument 2 must be "
1673 "'unknown', 'IEEE, little-endian' or "
1674 "'IEEE, big-endian'");
1675 return NULL;
1676
1677 }
1678
1679 if (f != unknown_format && f != detected) {
1680 PyErr_Format(PyExc_ValueError,
1681 "can only set %s format to 'unknown' or the "
1682 "detected platform value", typestr);
1683 return NULL;
1684 }
1685
1686 *p = f;
1687 Py_RETURN_NONE;
1688}
1689
1690PyDoc_STRVAR(float_setformat_doc,
1691"float.__setformat__(typestr, fmt) -> None\n"
1692"\n"
1693"You probably don't want to use this function. It exists mainly to be\n"
1694"used in Python's test suite.\n"
1695"\n"
1696"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1697"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1698"one of the latter two if it appears to match the underlying C reality.\n"
1699"\n"
1700"Overrides the automatic determination of C-level floating point type.\n"
1701"This affects how floats are converted to and from binary strings.");
1702
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001703static PyObject *
1704float_getzero(PyObject *v, void *closure)
1705{
1706 return PyFloat_FromDouble(0.0);
1707}
1708
Eric Smitha9f7d622008-02-17 19:46:49 +00001709static PyObject *
1710float__format__(PyObject *self, PyObject *args)
1711{
1712 PyObject *format_spec;
1713
1714 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1715 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001716 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001717 return _PyFloat_FormatAdvanced(self,
1718 PyBytes_AS_STRING(format_spec),
1719 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001720 if (PyUnicode_Check(format_spec)) {
1721 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001722 PyObject *result;
1723 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001724
Eric Smithdc13b792008-05-30 18:10:04 +00001725 if (str_spec == NULL)
1726 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001727
Eric Smithdc13b792008-05-30 18:10:04 +00001728 result = _PyFloat_FormatAdvanced(self,
1729 PyBytes_AS_STRING(str_spec),
1730 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001731
Eric Smithdc13b792008-05-30 18:10:04 +00001732 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001733 return result;
1734 }
1735 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1736 return NULL;
1737}
1738
1739PyDoc_STRVAR(float__format__doc,
1740"float.__format__(format_spec) -> string\n"
1741"\n"
1742"Formats the float according to format_spec.");
1743
1744
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001745static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001746 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001747 "Returns self, the complex conjugate of any float."},
1748 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1749 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001750 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1751 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001752 {"fromhex", (PyCFunction)float_fromhex,
1753 METH_O|METH_CLASS, float_fromhex_doc},
1754 {"hex", (PyCFunction)float_hex,
1755 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001756 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1757 "Returns True if the float is an integer."},
1758#if 0
1759 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1760 "Returns True if the float is positive or negative infinite."},
1761 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1762 "Returns True if the float is finite, neither infinite nor NaN."},
1763 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1764 "Returns True if the float is not a number (NaN)."},
1765#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001766 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001767 {"__getformat__", (PyCFunction)float_getformat,
1768 METH_O|METH_CLASS, float_getformat_doc},
1769 {"__setformat__", (PyCFunction)float_setformat,
1770 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001771 {"__format__", (PyCFunction)float__format__,
1772 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001773 {NULL, NULL} /* sentinel */
1774};
1775
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001776static PyGetSetDef float_getset[] = {
1777 {"real",
1778 (getter)float_float, (setter)NULL,
1779 "the real part of a complex number",
1780 NULL},
1781 {"imag",
1782 (getter)float_getzero, (setter)NULL,
1783 "the imaginary part of a complex number",
1784 NULL},
1785 {NULL} /* Sentinel */
1786};
1787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001788PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789"float(x) -> floating point number\n\
1790\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001791Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792
1793
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001794static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001795 float_add, /*nb_add*/
1796 float_sub, /*nb_subtract*/
1797 float_mul, /*nb_multiply*/
1798 float_classic_div, /*nb_divide*/
1799 float_rem, /*nb_remainder*/
1800 float_divmod, /*nb_divmod*/
1801 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001802 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001803 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001804 (unaryfunc)float_abs, /*nb_absolute*/
1805 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001806 0, /*nb_invert*/
1807 0, /*nb_lshift*/
1808 0, /*nb_rshift*/
1809 0, /*nb_and*/
1810 0, /*nb_xor*/
1811 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001812 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001813 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001814 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001815 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001816 0, /* nb_oct */
1817 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001818 0, /* nb_inplace_add */
1819 0, /* nb_inplace_subtract */
1820 0, /* nb_inplace_multiply */
1821 0, /* nb_inplace_divide */
1822 0, /* nb_inplace_remainder */
1823 0, /* nb_inplace_power */
1824 0, /* nb_inplace_lshift */
1825 0, /* nb_inplace_rshift */
1826 0, /* nb_inplace_and */
1827 0, /* nb_inplace_xor */
1828 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001829 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001830 float_div, /* nb_true_divide */
1831 0, /* nb_inplace_floor_divide */
1832 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001833};
1834
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001835PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001836 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001837 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001838 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001839 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 (destructor)float_dealloc, /* tp_dealloc */
1841 (printfunc)float_print, /* tp_print */
1842 0, /* tp_getattr */
1843 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001844 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 (reprfunc)float_repr, /* tp_repr */
1846 &float_as_number, /* tp_as_number */
1847 0, /* tp_as_sequence */
1848 0, /* tp_as_mapping */
1849 (hashfunc)float_hash, /* tp_hash */
1850 0, /* tp_call */
1851 (reprfunc)float_str, /* tp_str */
1852 PyObject_GenericGetAttr, /* tp_getattro */
1853 0, /* tp_setattro */
1854 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001855 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1856 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857 float_doc, /* tp_doc */
1858 0, /* tp_traverse */
1859 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001860 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 0, /* tp_weaklistoffset */
1862 0, /* tp_iter */
1863 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001864 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001866 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 0, /* tp_base */
1868 0, /* tp_dict */
1869 0, /* tp_descr_get */
1870 0, /* tp_descr_set */
1871 0, /* tp_dictoffset */
1872 0, /* tp_init */
1873 0, /* tp_alloc */
1874 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001875};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001876
1877void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001878_PyFloat_Init(void)
1879{
1880 /* We attempt to determine if this machine is using IEEE
1881 floating point formats by peering at the bits of some
1882 carefully chosen values. If it looks like we are on an
1883 IEEE platform, the float packing/unpacking routines can
1884 just copy bits, if not they resort to arithmetic & shifts
1885 and masks. The shifts & masks approach works on all finite
1886 values, but what happens to infinities, NaNs and signed
1887 zeroes on packing is an accident, and attempting to unpack
1888 a NaN or an infinity will raise an exception.
1889
1890 Note that if we're on some whacked-out platform which uses
1891 IEEE formats but isn't strictly little-endian or big-
1892 endian, we will fall back to the portable shifts & masks
1893 method. */
1894
1895#if SIZEOF_DOUBLE == 8
1896 {
1897 double x = 9006104071832581.0;
1898 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1899 detected_double_format = ieee_big_endian_format;
1900 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1901 detected_double_format = ieee_little_endian_format;
1902 else
1903 detected_double_format = unknown_format;
1904 }
1905#else
1906 detected_double_format = unknown_format;
1907#endif
1908
1909#if SIZEOF_FLOAT == 4
1910 {
1911 float y = 16711938.0;
1912 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1913 detected_float_format = ieee_big_endian_format;
1914 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1915 detected_float_format = ieee_little_endian_format;
1916 else
1917 detected_float_format = unknown_format;
1918 }
1919#else
1920 detected_float_format = unknown_format;
1921#endif
1922
1923 double_format = detected_double_format;
1924 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001925
Christian Heimes796fc312008-01-30 18:58:29 +00001926 /* Init float info */
1927 if (FloatInfoType.tp_name == 0)
1928 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001929}
1930
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001931int
1932PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001933{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001934 PyFloatObject *p;
1935 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001936 int i;
1937 int u; /* remaining unfreed ints per block */
1938 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001939
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001940 list = block_list;
1941 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001942 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001943 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001944 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001945 for (i = 0, p = &list->objects[0];
1946 i < N_FLOATOBJECTS;
1947 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001948 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001949 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001950 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001951 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001952 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001953 list->next = block_list;
1954 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001955 for (i = 0, p = &list->objects[0];
1956 i < N_FLOATOBJECTS;
1957 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001958 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001959 Py_REFCNT(p) == 0) {
1960 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001961 free_list;
1962 free_list = p;
1963 }
1964 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001965 }
1966 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001967 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001968 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001969 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001970 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001971 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001972 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001973}
1974
1975void
1976PyFloat_Fini(void)
1977{
1978 PyFloatObject *p;
1979 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001980 int i;
1981 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001982
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001983 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00001984
Guido van Rossum3fce8831999-03-12 19:43:17 +00001985 if (!Py_VerboseFlag)
1986 return;
1987 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001988 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001989 fprintf(stderr, "\n");
1990 }
1991 else {
1992 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001993 ": %d unfreed float%s\n",
1994 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001995 }
1996 if (Py_VerboseFlag > 1) {
1997 list = block_list;
1998 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001999 for (i = 0, p = &list->objects[0];
2000 i < N_FLOATOBJECTS;
2001 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002002 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00002003 Py_REFCNT(p) != 0) {
Eric Smithb3272582009-10-16 14:26:36 +00002004 char *buf = PyOS_double_to_string(
2005 PyFloat_AS_DOUBLE(p), 'r',
2006 0, 0, NULL);
2007 if (buf) {
2008 /* XXX(twouters) cast
2009 refcount to long
2010 until %zd is
2011 universally
2012 available
2013 */
2014 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002015 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002016 p, (long)Py_REFCNT(p), buf);
Eric Smithb3272582009-10-16 14:26:36 +00002017 PyMem_Free(buf);
2018 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002019 }
2020 }
2021 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002022 }
2023 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002024}
Tim Peters9905b942003-03-20 20:53:32 +00002025
2026/*----------------------------------------------------------------------------
2027 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002028 */
2029int
2030_PyFloat_Pack4(double x, unsigned char *p, int le)
2031{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002032 if (float_format == unknown_format) {
2033 unsigned char sign;
2034 int e;
2035 double f;
2036 unsigned int fbits;
2037 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002038
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002039 if (le) {
2040 p += 3;
2041 incr = -1;
2042 }
Tim Peters9905b942003-03-20 20:53:32 +00002043
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002044 if (x < 0) {
2045 sign = 1;
2046 x = -x;
2047 }
2048 else
2049 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002050
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002051 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002052
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002053 /* Normalize f to be in the range [1.0, 2.0) */
2054 if (0.5 <= f && f < 1.0) {
2055 f *= 2.0;
2056 e--;
2057 }
2058 else if (f == 0.0)
2059 e = 0;
2060 else {
2061 PyErr_SetString(PyExc_SystemError,
2062 "frexp() result out of range");
2063 return -1;
2064 }
2065
2066 if (e >= 128)
2067 goto Overflow;
2068 else if (e < -126) {
2069 /* Gradual underflow */
2070 f = ldexp(f, 126 + e);
2071 e = 0;
2072 }
2073 else if (!(e == 0 && f == 0.0)) {
2074 e += 127;
2075 f -= 1.0; /* Get rid of leading 1 */
2076 }
2077
2078 f *= 8388608.0; /* 2**23 */
2079 fbits = (unsigned int)(f + 0.5); /* Round */
2080 assert(fbits <= 8388608);
2081 if (fbits >> 23) {
2082 /* The carry propagated out of a string of 23 1 bits. */
2083 fbits = 0;
2084 ++e;
2085 if (e >= 255)
2086 goto Overflow;
2087 }
2088
2089 /* First byte */
2090 *p = (sign << 7) | (e >> 1);
2091 p += incr;
2092
2093 /* Second byte */
2094 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2095 p += incr;
2096
2097 /* Third byte */
2098 *p = (fbits >> 8) & 0xFF;
2099 p += incr;
2100
2101 /* Fourth byte */
2102 *p = fbits & 0xFF;
2103
2104 /* Done */
2105 return 0;
2106
Tim Peters9905b942003-03-20 20:53:32 +00002107 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002108 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002109 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002110 const char *s = (char*)&y;
2111 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002112
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002113 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2114 goto Overflow;
2115
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002116 if ((float_format == ieee_little_endian_format && !le)
2117 || (float_format == ieee_big_endian_format && le)) {
2118 p += 3;
2119 incr = -1;
2120 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002121
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 for (i = 0; i < 4; i++) {
2123 *p = *s++;
2124 p += incr;
2125 }
2126 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002127 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002128 Overflow:
2129 PyErr_SetString(PyExc_OverflowError,
2130 "float too large to pack with f format");
2131 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002132}
2133
2134int
2135_PyFloat_Pack8(double x, unsigned char *p, int le)
2136{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002137 if (double_format == unknown_format) {
2138 unsigned char sign;
2139 int e;
2140 double f;
2141 unsigned int fhi, flo;
2142 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002143
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002144 if (le) {
2145 p += 7;
2146 incr = -1;
2147 }
Tim Peters9905b942003-03-20 20:53:32 +00002148
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002149 if (x < 0) {
2150 sign = 1;
2151 x = -x;
2152 }
2153 else
2154 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002155
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002156 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002157
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158 /* Normalize f to be in the range [1.0, 2.0) */
2159 if (0.5 <= f && f < 1.0) {
2160 f *= 2.0;
2161 e--;
2162 }
2163 else if (f == 0.0)
2164 e = 0;
2165 else {
2166 PyErr_SetString(PyExc_SystemError,
2167 "frexp() result out of range");
2168 return -1;
2169 }
2170
2171 if (e >= 1024)
2172 goto Overflow;
2173 else if (e < -1022) {
2174 /* Gradual underflow */
2175 f = ldexp(f, 1022 + e);
2176 e = 0;
2177 }
2178 else if (!(e == 0 && f == 0.0)) {
2179 e += 1023;
2180 f -= 1.0; /* Get rid of leading 1 */
2181 }
2182
2183 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2184 f *= 268435456.0; /* 2**28 */
2185 fhi = (unsigned int)f; /* Truncate */
2186 assert(fhi < 268435456);
2187
2188 f -= (double)fhi;
2189 f *= 16777216.0; /* 2**24 */
2190 flo = (unsigned int)(f + 0.5); /* Round */
2191 assert(flo <= 16777216);
2192 if (flo >> 24) {
2193 /* The carry propagated out of a string of 24 1 bits. */
2194 flo = 0;
2195 ++fhi;
2196 if (fhi >> 28) {
2197 /* And it also progagated out of the next 28 bits. */
2198 fhi = 0;
2199 ++e;
2200 if (e >= 2047)
2201 goto Overflow;
2202 }
2203 }
2204
2205 /* First byte */
2206 *p = (sign << 7) | (e >> 4);
2207 p += incr;
2208
2209 /* Second byte */
2210 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2211 p += incr;
2212
2213 /* Third byte */
2214 *p = (fhi >> 16) & 0xFF;
2215 p += incr;
2216
2217 /* Fourth byte */
2218 *p = (fhi >> 8) & 0xFF;
2219 p += incr;
2220
2221 /* Fifth byte */
2222 *p = fhi & 0xFF;
2223 p += incr;
2224
2225 /* Sixth byte */
2226 *p = (flo >> 16) & 0xFF;
2227 p += incr;
2228
2229 /* Seventh byte */
2230 *p = (flo >> 8) & 0xFF;
2231 p += incr;
2232
2233 /* Eighth byte */
2234 *p = flo & 0xFF;
2235 p += incr;
2236
2237 /* Done */
2238 return 0;
2239
2240 Overflow:
2241 PyErr_SetString(PyExc_OverflowError,
2242 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002243 return -1;
2244 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245 else {
2246 const char *s = (char*)&x;
2247 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002248
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002249 if ((double_format == ieee_little_endian_format && !le)
2250 || (double_format == ieee_big_endian_format && le)) {
2251 p += 7;
2252 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002253 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002254
2255 for (i = 0; i < 8; i++) {
2256 *p = *s++;
2257 p += incr;
2258 }
2259 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002260 }
Tim Peters9905b942003-03-20 20:53:32 +00002261}
2262
2263double
2264_PyFloat_Unpack4(const unsigned char *p, int le)
2265{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002266 if (float_format == unknown_format) {
2267 unsigned char sign;
2268 int e;
2269 unsigned int f;
2270 double x;
2271 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002272
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002273 if (le) {
2274 p += 3;
2275 incr = -1;
2276 }
2277
2278 /* First byte */
2279 sign = (*p >> 7) & 1;
2280 e = (*p & 0x7F) << 1;
2281 p += incr;
2282
2283 /* Second byte */
2284 e |= (*p >> 7) & 1;
2285 f = (*p & 0x7F) << 16;
2286 p += incr;
2287
2288 if (e == 255) {
2289 PyErr_SetString(
2290 PyExc_ValueError,
2291 "can't unpack IEEE 754 special value "
2292 "on non-IEEE platform");
2293 return -1;
2294 }
2295
2296 /* Third byte */
2297 f |= *p << 8;
2298 p += incr;
2299
2300 /* Fourth byte */
2301 f |= *p;
2302
2303 x = (double)f / 8388608.0;
2304
2305 /* XXX This sadly ignores Inf/NaN issues */
2306 if (e == 0)
2307 e = -126;
2308 else {
2309 x += 1.0;
2310 e -= 127;
2311 }
2312 x = ldexp(x, e);
2313
2314 if (sign)
2315 x = -x;
2316
2317 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002318 }
Tim Peters9905b942003-03-20 20:53:32 +00002319 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002320 float x;
2321
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002322 if ((float_format == ieee_little_endian_format && !le)
2323 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002324 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325 char *d = &buf[3];
2326 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002327
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328 for (i = 0; i < 4; i++) {
2329 *d-- = *p++;
2330 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002331 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332 }
2333 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002334 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002336
2337 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338 }
Tim Peters9905b942003-03-20 20:53:32 +00002339}
2340
2341double
2342_PyFloat_Unpack8(const unsigned char *p, int le)
2343{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344 if (double_format == unknown_format) {
2345 unsigned char sign;
2346 int e;
2347 unsigned int fhi, flo;
2348 double x;
2349 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002350
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002351 if (le) {
2352 p += 7;
2353 incr = -1;
2354 }
2355
2356 /* First byte */
2357 sign = (*p >> 7) & 1;
2358 e = (*p & 0x7F) << 4;
2359
2360 p += incr;
2361
2362 /* Second byte */
2363 e |= (*p >> 4) & 0xF;
2364 fhi = (*p & 0xF) << 24;
2365 p += incr;
2366
2367 if (e == 2047) {
2368 PyErr_SetString(
2369 PyExc_ValueError,
2370 "can't unpack IEEE 754 special value "
2371 "on non-IEEE platform");
2372 return -1.0;
2373 }
2374
2375 /* Third byte */
2376 fhi |= *p << 16;
2377 p += incr;
2378
2379 /* Fourth byte */
2380 fhi |= *p << 8;
2381 p += incr;
2382
2383 /* Fifth byte */
2384 fhi |= *p;
2385 p += incr;
2386
2387 /* Sixth byte */
2388 flo = *p << 16;
2389 p += incr;
2390
2391 /* Seventh byte */
2392 flo |= *p << 8;
2393 p += incr;
2394
2395 /* Eighth byte */
2396 flo |= *p;
2397
2398 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2399 x /= 268435456.0; /* 2**28 */
2400
2401 if (e == 0)
2402 e = -1022;
2403 else {
2404 x += 1.0;
2405 e -= 1023;
2406 }
2407 x = ldexp(x, e);
2408
2409 if (sign)
2410 x = -x;
2411
2412 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002413 }
Tim Peters9905b942003-03-20 20:53:32 +00002414 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002415 double x;
2416
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002417 if ((double_format == ieee_little_endian_format && !le)
2418 || (double_format == ieee_big_endian_format && le)) {
2419 char buf[8];
2420 char *d = &buf[7];
2421 int i;
2422
2423 for (i = 0; i < 8; i++) {
2424 *d-- = *p++;
2425 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002426 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002427 }
2428 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002429 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002430 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002431
2432 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002433 }
Tim Peters9905b942003-03-20 20:53:32 +00002434}