blob: 9a0dbb33c210cc6e5f0602b34da5d98719ab94a1 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson7103aa42008-07-15 19:08:33 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Neal Norwitz5f95a792008-01-25 08:04:16 +000022#ifdef _OSF_SOURCE
23/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24extern int finite(double);
25#endif
26
Guido van Rossum93ad0df1997-05-13 21:00:42 +000027/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000029#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000030#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000031
Guido van Rossum3fce8831999-03-12 19:43:17 +000032struct _floatblock {
33 struct _floatblock *next;
34 PyFloatObject objects[N_FLOATOBJECTS];
35};
36
37typedef struct _floatblock PyFloatBlock;
38
39static PyFloatBlock *block_list = NULL;
40static PyFloatObject *free_list = NULL;
41
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000043fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044{
45 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000049 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000050 ((PyFloatBlock *)p)->next = block_list;
51 block_list = (PyFloatBlock *)p;
52 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053 q = p + N_FLOATOBJECTS;
54 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000055 Py_TYPE(q) = (struct _typeobject *)(q-1);
56 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000057 return p + N_FLOATOBJECTS - 1;
58}
59
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060double
61PyFloat_GetMax(void)
62{
63 return DBL_MAX;
64}
65
66double
67PyFloat_GetMin(void)
68{
69 return DBL_MIN;
70}
71
Christian Heimes796fc312008-01-30 18:58:29 +000072static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000073
74PyDoc_STRVAR(floatinfo__doc__,
75"sys.floatinfo\n\
76\n\
77A structseq holding information about the float type. It contains low level\n\
78information about the precision and internal representation. Please study\n\
79your system's :file:`float.h` for more information.");
80
81static PyStructSequence_Field floatinfo_fields[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
84 "is representable"},
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
86 "is representable"},
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
91 "a normalized"},
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
98 {0}
99};
100
101static PyStructSequence_Desc floatinfo_desc = {
102 "sys.floatinfo", /* name */
103 floatinfo__doc__, /* doc */
104 floatinfo_fields, /* fields */
105 11
106};
107
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108PyObject *
109PyFloat_GetInfo(void)
110{
Christian Heimes796fc312008-01-30 18:58:29 +0000111 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000112 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114 floatinfo = PyStructSequence_New(&FloatInfoType);
115 if (floatinfo == NULL) {
116 return NULL;
117 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Christian Heimesc94e2b52008-01-14 04:13:37 +0000119#define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121#define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000123
Christian Heimesc94e2b52008-01-14 04:13:37 +0000124 SetDblFlag(DBL_MAX);
125 SetIntFlag(DBL_MAX_EXP);
126 SetIntFlag(DBL_MAX_10_EXP);
127 SetDblFlag(DBL_MIN);
128 SetIntFlag(DBL_MIN_EXP);
129 SetIntFlag(DBL_MIN_10_EXP);
130 SetIntFlag(DBL_DIG);
131 SetIntFlag(DBL_MANT_DIG);
132 SetDblFlag(DBL_EPSILON);
133 SetIntFlag(FLT_RADIX);
134 SetIntFlag(FLT_ROUNDS);
135#undef SetIntFlag
136#undef SetDblFlag
137
138 if (PyErr_Occurred()) {
139 Py_CLEAR(floatinfo);
140 return NULL;
141 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000142 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
152 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000153 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000155 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Tim Petersef14d732000-09-23 03:39:17 +0000161/**************************************************************************
162RED_FLAG 22-Sep-2000 tim
163PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
164
1651. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
168
1692. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
172
173Since we can't change the interface of a public API function, pend is
174still supported but now *officially* useless: if pend is not NULL,
175*pend is set to NULL.
176**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000178PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179{
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000180 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000182 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000184 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000185#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187
Tim Petersef14d732000-09-23 03:39:17 +0000188 if (pend)
189 *pend = NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000190 if (PyString_Check(v)) {
191 s = PyString_AS_STRING(v);
192 len = PyString_GET_SIZE(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000194#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000195 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000196 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000198 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 return NULL;
200 }
Tim Petersef14d732000-09-23 03:39:17 +0000201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000203 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 NULL))
205 return NULL;
206 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000207 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000208 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000210 else if (PyObject_AsCharBuffer(v, &s, &len)) {
211 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000212 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000215 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000216
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
Tim Peters97019e42001-11-28 22:43:45 +0000302/* XXX PyFloat_AsStringEx should not be a public API function (for one
303 XXX thing, its signature passes a buffer without a length; for another,
304 XXX it isn't useful outside this file).
305*/
306void
307PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
308{
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000309 _PyOS_double_to_string(buf, 100, v->ob_fval, 'g', precision,
310 Py_DTSF_ADD_DOT_0, NULL);
Tim Peters97019e42001-11-28 22:43:45 +0000311}
312
Neil Schemenauer32117e52001-01-04 01:44:34 +0000313/* Macro and helper that convert PyObject obj to a C double and store
314 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000315 slot function. If conversion to double raises an exception, obj is
316 set to NULL, and the function invoking this macro returns NULL. If
317 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
318 stored in obj, and returned from the function invoking this macro.
319*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000320#define CONVERT_TO_DOUBLE(obj, dbl) \
321 if (PyFloat_Check(obj)) \
322 dbl = PyFloat_AS_DOUBLE(obj); \
323 else if (convert_to_double(&(obj), &(dbl)) < 0) \
324 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000325
326static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000327convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000328{
329 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000330
Neil Schemenauer32117e52001-01-04 01:44:34 +0000331 if (PyInt_Check(obj)) {
332 *dbl = (double)PyInt_AS_LONG(obj);
333 }
334 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000335 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000336 if (*dbl == -1.0 && PyErr_Occurred()) {
337 *v = NULL;
338 return -1;
339 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000340 }
341 else {
342 Py_INCREF(Py_NotImplemented);
343 *v = Py_NotImplemented;
344 return -1;
345 }
346 return 0;
347}
348
Tim Peters97019e42001-11-28 22:43:45 +0000349/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
350 XXX they pass a char buffer without passing a length.
351*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000352void
Fred Drakefd99de62000-07-09 05:02:18 +0000353PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000354{
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000355 _PyOS_double_to_string(buf, 100, v->ob_fval, 's', 0,
356 Py_DTSF_ADD_DOT_0, NULL);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000357}
358
Tim Peters72f98e92001-05-08 15:19:57 +0000359void
360PyFloat_AsReprString(char *buf, PyFloatObject *v)
361{
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000362 _PyOS_double_to_string(buf, 100, v->ob_fval, 'r', 0,
363 Py_DTSF_ADD_DOT_0, NULL);
Tim Peters72f98e92001-05-08 15:19:57 +0000364}
365
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000366/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000367static int
Fred Drakefd99de62000-07-09 05:02:18 +0000368float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
370 char buf[100];
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000371 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval,
372 (flags & Py_PRINT_RAW) ? 's' : 'r',
373 0, Py_DTSF_ADD_DOT_0, NULL);
Brett Cannon01531592007-09-17 03:28:34 +0000374 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000376 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000377 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378}
379
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000381float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000383 char buf[100];
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000384 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval, 'r', 0,
385 Py_DTSF_ADD_DOT_0, NULL);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000386 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000387}
388
389static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000390float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000391{
392 char buf[100];
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000393 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval, 's', 0,
394 Py_DTSF_ADD_DOT_0, NULL);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000395 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Tim Peters307fa782004-09-23 08:06:40 +0000398/* Comparison is pretty much a nightmare. When comparing float to float,
399 * we do it as straightforwardly (and long-windedly) as conceivable, so
400 * that, e.g., Python x == y delivers the same result as the platform
401 * C x == y when x and/or y is a NaN.
402 * When mixing float with an integer type, there's no good *uniform* approach.
403 * Converting the double to an integer obviously doesn't work, since we
404 * may lose info from fractional bits. Converting the integer to a double
405 * also has two failure modes: (1) a long int may trigger overflow (too
406 * large to fit in the dynamic range of a C double); (2) even a C long may have
407 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
408 * 63 bits of precision, but a C double probably has only 53), and then
409 * we can falsely claim equality when low-order integer bits are lost by
410 * coercion to double. So this part is painful too.
411 */
412
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000413static PyObject*
414float_richcompare(PyObject *v, PyObject *w, int op)
415{
416 double i, j;
417 int r = 0;
418
Tim Peters307fa782004-09-23 08:06:40 +0000419 assert(PyFloat_Check(v));
420 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000421
Tim Peters307fa782004-09-23 08:06:40 +0000422 /* Switch on the type of w. Set i and j to doubles to be compared,
423 * and op to the richcomp to use.
424 */
425 if (PyFloat_Check(w))
426 j = PyFloat_AS_DOUBLE(w);
427
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000428 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000429 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000430 /* If i is an infinity, its magnitude exceeds any
431 * finite integer, so it doesn't matter which int we
432 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000433 */
434 j = 0.0;
435 else
436 goto Unimplemented;
437 }
438
439 else if (PyInt_Check(w)) {
440 long jj = PyInt_AS_LONG(w);
441 /* In the worst realistic case I can imagine, C double is a
442 * Cray single with 48 bits of precision, and long has 64
443 * bits.
444 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000445#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000446 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
447 if (abs >> 48) {
448 /* Needs more than 48 bits. Make it take the
449 * PyLong path.
450 */
451 PyObject *result;
452 PyObject *ww = PyLong_FromLong(jj);
453
454 if (ww == NULL)
455 return NULL;
456 result = float_richcompare(v, ww, op);
457 Py_DECREF(ww);
458 return result;
459 }
460#endif
461 j = (double)jj;
462 assert((long)j == jj);
463 }
464
465 else if (PyLong_Check(w)) {
466 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
467 int wsign = _PyLong_Sign(w);
468 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000469 int exponent;
470
471 if (vsign != wsign) {
472 /* Magnitudes are irrelevant -- the signs alone
473 * determine the outcome.
474 */
475 i = (double)vsign;
476 j = (double)wsign;
477 goto Compare;
478 }
479 /* The signs are the same. */
480 /* Convert w to a double if it fits. In particular, 0 fits. */
481 nbits = _PyLong_NumBits(w);
482 if (nbits == (size_t)-1 && PyErr_Occurred()) {
483 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000484 * to hold the # of bits. Replace with little doubles
485 * that give the same outcome -- w is so large that
486 * its magnitude must exceed the magnitude of any
487 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000488 */
489 PyErr_Clear();
490 i = (double)vsign;
491 assert(wsign != 0);
492 j = wsign * 2.0;
493 goto Compare;
494 }
495 if (nbits <= 48) {
496 j = PyLong_AsDouble(w);
497 /* It's impossible that <= 48 bits overflowed. */
498 assert(j != -1.0 || ! PyErr_Occurred());
499 goto Compare;
500 }
501 assert(wsign != 0); /* else nbits was 0 */
502 assert(vsign != 0); /* if vsign were 0, then since wsign is
503 * not 0, we would have taken the
504 * vsign != wsign branch at the start */
505 /* We want to work with non-negative numbers. */
506 if (vsign < 0) {
507 /* "Multiply both sides" by -1; this also swaps the
508 * comparator.
509 */
510 i = -i;
511 op = _Py_SwappedOp[op];
512 }
513 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000514 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000515 /* exponent is the # of bits in v before the radix point;
516 * we know that nbits (the # of bits in w) > 48 at this point
517 */
518 if (exponent < 0 || (size_t)exponent < nbits) {
519 i = 1.0;
520 j = 2.0;
521 goto Compare;
522 }
523 if ((size_t)exponent > nbits) {
524 i = 2.0;
525 j = 1.0;
526 goto Compare;
527 }
528 /* v and w have the same number of bits before the radix
529 * point. Construct two longs that have the same comparison
530 * outcome.
531 */
532 {
533 double fracpart;
534 double intpart;
535 PyObject *result = NULL;
536 PyObject *one = NULL;
537 PyObject *vv = NULL;
538 PyObject *ww = w;
539
540 if (wsign < 0) {
541 ww = PyNumber_Negative(w);
542 if (ww == NULL)
543 goto Error;
544 }
545 else
546 Py_INCREF(ww);
547
548 fracpart = modf(i, &intpart);
549 vv = PyLong_FromDouble(intpart);
550 if (vv == NULL)
551 goto Error;
552
553 if (fracpart != 0.0) {
554 /* Shift left, and or a 1 bit into vv
555 * to represent the lost fraction.
556 */
557 PyObject *temp;
558
559 one = PyInt_FromLong(1);
560 if (one == NULL)
561 goto Error;
562
563 temp = PyNumber_Lshift(ww, one);
564 if (temp == NULL)
565 goto Error;
566 Py_DECREF(ww);
567 ww = temp;
568
569 temp = PyNumber_Lshift(vv, one);
570 if (temp == NULL)
571 goto Error;
572 Py_DECREF(vv);
573 vv = temp;
574
575 temp = PyNumber_Or(vv, one);
576 if (temp == NULL)
577 goto Error;
578 Py_DECREF(vv);
579 vv = temp;
580 }
581
582 r = PyObject_RichCompareBool(vv, ww, op);
583 if (r < 0)
584 goto Error;
585 result = PyBool_FromLong(r);
586 Error:
587 Py_XDECREF(vv);
588 Py_XDECREF(ww);
589 Py_XDECREF(one);
590 return result;
591 }
592 } /* else if (PyLong_Check(w)) */
593
594 else /* w isn't float, int, or long */
595 goto Unimplemented;
596
597 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000598 PyFPE_START_PROTECT("richcompare", return NULL)
599 switch (op) {
600 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000601 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000602 break;
603 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000604 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000605 break;
606 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000607 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000608 break;
609 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000610 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000611 break;
612 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000613 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000614 break;
615 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000616 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000617 break;
618 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000619 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000620 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000621
622 Unimplemented:
623 Py_INCREF(Py_NotImplemented);
624 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000625}
626
Guido van Rossum9bfef441993-03-29 10:43:31 +0000627static long
Fred Drakefd99de62000-07-09 05:02:18 +0000628float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000629{
Tim Peters39dce292000-08-15 03:34:48 +0000630 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000631}
632
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000634float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000635{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000636 double a,b;
637 CONVERT_TO_DOUBLE(v, a);
638 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000639 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000640 a = a + b;
641 PyFPE_END_PROTECT(a)
642 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643}
644
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000645static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000646float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000648 double a,b;
649 CONVERT_TO_DOUBLE(v, a);
650 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000651 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000652 a = a - b;
653 PyFPE_END_PROTECT(a)
654 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655}
656
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000658float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000659{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000660 double a,b;
661 CONVERT_TO_DOUBLE(v, a);
662 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000663 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000664 a = a * b;
665 PyFPE_END_PROTECT(a)
666 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667}
668
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000670float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000671{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000672 double a,b;
673 CONVERT_TO_DOUBLE(v, a);
674 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000675#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000676 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000677 PyErr_SetString(PyExc_ZeroDivisionError,
678 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679 return NULL;
680 }
Christian Heimes6f341092008-04-18 23:13:07 +0000681#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000682 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000683 a = a / b;
684 PyFPE_END_PROTECT(a)
685 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686}
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000689float_classic_div(PyObject *v, PyObject *w)
690{
691 double a,b;
692 CONVERT_TO_DOUBLE(v, a);
693 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000694 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000695 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
696 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000697#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000698 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000699 PyErr_SetString(PyExc_ZeroDivisionError,
700 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000701 return NULL;
702 }
Christian Heimes6f341092008-04-18 23:13:07 +0000703#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000704 PyFPE_START_PROTECT("divide", return 0)
705 a = a / b;
706 PyFPE_END_PROTECT(a)
707 return PyFloat_FromDouble(a);
708}
709
710static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000711float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000713 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000714 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000715 CONVERT_TO_DOUBLE(v, vx);
716 CONVERT_TO_DOUBLE(w, wx);
717#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000719 PyErr_SetString(PyExc_ZeroDivisionError,
720 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721 return NULL;
722 }
Christian Heimes6f341092008-04-18 23:13:07 +0000723#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000724 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000725 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000726 /* note: checking mod*wx < 0 is incorrect -- underflows to
727 0 if wx < sqrt(smallest nonzero double) */
728 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000729 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000730 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000731 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733}
734
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000736float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000737{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000738 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000739 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000740 CONVERT_TO_DOUBLE(v, vx);
741 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000742 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000744 return NULL;
745 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000746 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000747 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000748 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000749 exact multiple of wx. But this is fp arithmetic, and fp
750 vx - mod is an approximation; the result is that div may
751 not be an exact integral value after the division, although
752 it will always be very close to one.
753 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000754 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000755 if (mod) {
756 /* ensure the remainder has the same sign as the denominator */
757 if ((wx < 0) != (mod < 0)) {
758 mod += wx;
759 div -= 1.0;
760 }
761 }
762 else {
763 /* the remainder is zero, and in the presence of signed zeroes
764 fmod returns different results across platforms; ensure
765 it has the same sign as the denominator; we'd like to do
766 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000767 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000768 if (wx < 0.0)
769 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000770 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000771 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000772 if (div) {
773 floordiv = floor(div);
774 if (div - floordiv > 0.5)
775 floordiv += 1.0;
776 }
777 else {
778 /* div is zero - get the same sign as the true quotient */
779 div *= div; /* hide "div = +0" from optimizers */
780 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
781 }
782 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000783 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000784}
785
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000786static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000787float_floor_div(PyObject *v, PyObject *w)
788{
789 PyObject *t, *r;
790
791 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000792 if (t == NULL || t == Py_NotImplemented)
793 return t;
794 assert(PyTuple_CheckExact(t));
795 r = PyTuple_GET_ITEM(t, 0);
796 Py_INCREF(r);
797 Py_DECREF(t);
798 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000799}
800
801static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000802float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803{
804 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000805
806 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000807 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000808 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000809 return NULL;
810 }
811
Neil Schemenauer32117e52001-01-04 01:44:34 +0000812 CONVERT_TO_DOUBLE(v, iv);
813 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000814
815 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000816 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000817 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000818 }
Tim Peters96685bf2001-08-23 22:31:37 +0000819 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000820 if (iw < 0.0) {
821 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000822 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000823 return NULL;
824 }
825 return PyFloat_FromDouble(0.0);
826 }
Christian Heimes6f341092008-04-18 23:13:07 +0000827 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
828 return PyFloat_FromDouble(1.0);
829 }
Tim Peterse87568d2003-05-24 20:18:24 +0000830 if (iv < 0.0) {
831 /* Whether this is an error is a mess, and bumps into libm
832 * bugs so we have to figure it out ourselves.
833 */
834 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000835 PyErr_SetString(PyExc_ValueError, "negative number "
836 "cannot be raised to a fractional power");
837 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000838 }
839 /* iw is an exact integer, albeit perhaps a very large one.
840 * -1 raised to an exact integer should never be exceptional.
841 * Alas, some libms (chiefly glibc as of early 2003) return
842 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
843 * happen to be representable in a *C* integer. That's a
844 * bug; we let that slide in math.pow() (which currently
845 * reflects all platform accidents), but not for Python's **.
846 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000847 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000848 /* Return 1 if iw is even, -1 if iw is odd; there's
849 * no guarantee that any C integral type is big
850 * enough to hold iw, so we have to check this
851 * indirectly.
852 */
853 ix = floor(iw * 0.5) * 2.0;
854 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
855 }
856 /* Else iv != -1.0, and overflow or underflow are possible.
857 * Unless we're to write pow() ourselves, we have to trust
858 * the platform to do this correctly.
859 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000860 }
Tim Peters96685bf2001-08-23 22:31:37 +0000861 errno = 0;
862 PyFPE_START_PROTECT("pow", return NULL)
863 ix = pow(iv, iw);
864 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000865 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000866 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000867 /* We don't expect any errno value other than ERANGE, but
868 * the range of libm bugs appears unbounded.
869 */
Alex Martelli348dc882006-08-23 22:17:59 +0000870 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
871 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000873 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000874 return PyFloat_FromDouble(ix);
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_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000880 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000881}
882
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000883static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000884float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000885{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000886 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000887}
888
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000889static int
Fred Drakefd99de62000-07-09 05:02:18 +0000890float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000891{
892 return v->ob_fval != 0.0;
893}
894
Guido van Rossum234f9421993-06-17 12:35:49 +0000895static int
Fred Drakefd99de62000-07-09 05:02:18 +0000896float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000897{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000898 if (PyInt_Check(*pw)) {
899 long x = PyInt_AsLong(*pw);
900 *pw = PyFloat_FromDouble((double)x);
901 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000902 return 0;
903 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000904 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000905 double x = PyLong_AsDouble(*pw);
906 if (x == -1.0 && PyErr_Occurred())
907 return -1;
908 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000909 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000910 return 0;
911 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000912 else if (PyFloat_Check(*pw)) {
913 Py_INCREF(*pv);
914 Py_INCREF(*pw);
915 return 0;
916 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000917 return 1; /* Can't do it */
918}
919
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000920static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000921float_is_integer(PyObject *v)
922{
923 double x = PyFloat_AsDouble(v);
924 PyObject *o;
925
926 if (x == -1.0 && PyErr_Occurred())
927 return NULL;
928 if (!Py_IS_FINITE(x))
929 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +0000930 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000931 PyFPE_START_PROTECT("is_integer", return NULL)
932 o = (floor(x) == x) ? Py_True : Py_False;
933 PyFPE_END_PROTECT(x)
934 if (errno != 0) {
935 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
936 PyExc_ValueError);
937 return NULL;
938 }
939 Py_INCREF(o);
940 return o;
941}
942
943#if 0
944static PyObject *
945float_is_inf(PyObject *v)
946{
947 double x = PyFloat_AsDouble(v);
948 if (x == -1.0 && PyErr_Occurred())
949 return NULL;
950 return PyBool_FromLong((long)Py_IS_INFINITY(x));
951}
952
953static PyObject *
954float_is_nan(PyObject *v)
955{
956 double x = PyFloat_AsDouble(v);
957 if (x == -1.0 && PyErr_Occurred())
958 return NULL;
959 return PyBool_FromLong((long)Py_IS_NAN(x));
960}
961
962static PyObject *
963float_is_finite(PyObject *v)
964{
965 double x = PyFloat_AsDouble(v);
966 if (x == -1.0 && PyErr_Occurred())
967 return NULL;
968 return PyBool_FromLong((long)Py_IS_FINITE(x));
969}
970#endif
971
972static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000973float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000974{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000976 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000977
978 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000979 /* Try to get out cheap if this fits in a Python int. The attempt
980 * to cast to long must be protected, as C doesn't define what
981 * happens if the double is too big to fit in a long. Some rare
982 * systems raise an exception then (RISCOS was mentioned as one,
983 * and someone using a non-default option on Sun also bumped into
984 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
985 * still be vulnerable: if a long has more bits of precision than
986 * a double, casting MIN/MAX to double may yield an approximation,
987 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
988 * yield true from the C expression wholepart<=LONG_MAX, despite
989 * that wholepart is actually greater than LONG_MAX.
990 */
991 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
992 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000993 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000994 }
995 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000996}
997
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000998static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +0000999float_long(PyObject *v)
1000{
1001 double x = PyFloat_AsDouble(v);
1002 return PyLong_FromDouble(x);
1003}
1004
1005static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001006float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001007{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001008 if (PyFloat_CheckExact(v))
1009 Py_INCREF(v);
1010 else
1011 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001012 return v;
1013}
1014
Mark Dickinson7103aa42008-07-15 19:08:33 +00001015/* turn ASCII hex characters into integer values and vice versa */
1016
1017static char
1018char_from_hex(int x)
1019{
1020 assert(0 <= x && x < 16);
1021 return "0123456789abcdef"[x];
1022}
1023
1024static int
1025hex_from_char(char c) {
1026 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001027 switch(c) {
1028 case '0':
1029 x = 0;
1030 break;
1031 case '1':
1032 x = 1;
1033 break;
1034 case '2':
1035 x = 2;
1036 break;
1037 case '3':
1038 x = 3;
1039 break;
1040 case '4':
1041 x = 4;
1042 break;
1043 case '5':
1044 x = 5;
1045 break;
1046 case '6':
1047 x = 6;
1048 break;
1049 case '7':
1050 x = 7;
1051 break;
1052 case '8':
1053 x = 8;
1054 break;
1055 case '9':
1056 x = 9;
1057 break;
1058 case 'a':
1059 case 'A':
1060 x = 10;
1061 break;
1062 case 'b':
1063 case 'B':
1064 x = 11;
1065 break;
1066 case 'c':
1067 case 'C':
1068 x = 12;
1069 break;
1070 case 'd':
1071 case 'D':
1072 x = 13;
1073 break;
1074 case 'e':
1075 case 'E':
1076 x = 14;
1077 break;
1078 case 'f':
1079 case 'F':
1080 x = 15;
1081 break;
1082 default:
1083 x = -1;
1084 break;
1085 }
1086 return x;
1087}
1088
1089/* convert a float to a hexadecimal string */
1090
1091/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1092 of the form 4k+1. */
1093#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1094
1095static PyObject *
1096float_hex(PyObject *v)
1097{
1098 double x, m;
1099 int e, shift, i, si, esign;
1100 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1101 trailing NUL byte. */
1102 char s[(TOHEX_NBITS-1)/4+3];
1103
1104 CONVERT_TO_DOUBLE(v, x);
1105
1106 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1107 return float_str((PyFloatObject *)v);
1108
1109 if (x == 0.0) {
1110 if(copysign(1.0, x) == -1.0)
1111 return PyString_FromString("-0x0.0p+0");
1112 else
1113 return PyString_FromString("0x0.0p+0");
1114 }
1115
1116 m = frexp(fabs(x), &e);
1117 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1118 m = ldexp(m, shift);
1119 e -= shift;
1120
1121 si = 0;
1122 s[si] = char_from_hex((int)m);
1123 si++;
1124 m -= (int)m;
1125 s[si] = '.';
1126 si++;
1127 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1128 m *= 16.0;
1129 s[si] = char_from_hex((int)m);
1130 si++;
1131 m -= (int)m;
1132 }
1133 s[si] = '\0';
1134
1135 if (e < 0) {
1136 esign = (int)'-';
1137 e = -e;
1138 }
1139 else
1140 esign = (int)'+';
1141
1142 if (x < 0.0)
1143 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1144 else
1145 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1146}
1147
1148PyDoc_STRVAR(float_hex_doc,
1149"float.hex() -> string\n\
1150\n\
1151Return a hexadecimal representation of a floating-point number.\n\
1152>>> (-0.1).hex()\n\
1153'-0x1.999999999999ap-4'\n\
1154>>> 3.14159.hex()\n\
1155'0x1.921f9f01b866ep+1'");
1156
1157/* Convert a hexadecimal string to a float. */
1158
1159static PyObject *
1160float_fromhex(PyObject *cls, PyObject *arg)
1161{
1162 PyObject *result_as_float, *result;
1163 double x;
1164 long exp, top_exp, lsb, key_digit;
1165 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1166 int half_eps, digit, round_up, sign=1;
1167 Py_ssize_t length, ndigits, fdigits, i;
1168
1169 /*
1170 * For the sake of simplicity and correctness, we impose an artificial
1171 * limit on ndigits, the total number of hex digits in the coefficient
1172 * The limit is chosen to ensure that, writing exp for the exponent,
1173 *
1174 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1175 * guaranteed to overflow (provided it's nonzero)
1176 *
1177 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1178 * guaranteed to underflow to 0.
1179 *
1180 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1181 * overflow in the calculation of exp and top_exp below.
1182 *
1183 * More specifically, ndigits is assumed to satisfy the following
1184 * inequalities:
1185 *
1186 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1187 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1188 *
1189 * If either of these inequalities is not satisfied, a ValueError is
1190 * raised. Otherwise, write x for the value of the hex string, and
1191 * assume x is nonzero. Then
1192 *
1193 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1194 *
1195 * Now if exp > LONG_MAX/2 then:
1196 *
1197 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1198 * = DBL_MAX_EXP
1199 *
1200 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1201 * double, so overflows. If exp < LONG_MIN/2, then
1202 *
1203 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1204 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1205 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1206 *
1207 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1208 * when converted to a C double.
1209 *
1210 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1211 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1212 */
1213
1214 if (PyString_AsStringAndSize(arg, &s, &length))
1215 return NULL;
1216 s_end = s + length;
1217
1218 /********************
1219 * Parse the string *
1220 ********************/
1221
1222 /* leading whitespace and optional sign */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001223 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001224 s++;
1225 if (*s == '-') {
1226 s++;
1227 sign = -1;
1228 }
1229 else if (*s == '+')
1230 s++;
1231
1232 /* infinities and nans */
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001233 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001234 x = Py_NAN;
1235 goto finished;
1236 }
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001237 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1238 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001239 x = sign*Py_HUGE_VAL;
1240 goto finished;
1241 }
1242
1243 /* [0x] */
1244 s_store = s;
1245 if (*s == '0') {
1246 s++;
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001247 if (*s == 'x' || *s == 'X')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001248 s++;
1249 else
1250 s = s_store;
1251 }
1252
1253 /* coefficient: <integer> [. <fraction>] */
1254 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001255 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001256 s++;
1257 s_store = s;
1258 if (*s == '.') {
1259 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001260 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001261 s++;
1262 coeff_end = s-1;
1263 }
1264 else
1265 coeff_end = s;
1266
1267 /* ndigits = total # of hex digits; fdigits = # after point */
1268 ndigits = coeff_end - coeff_start;
1269 fdigits = coeff_end - s_store;
1270 if (ndigits == 0)
1271 goto parse_error;
1272 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1273 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1274 goto insane_length_error;
1275
1276 /* [p <exponent>] */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001277 if (*s == 'p' || *s == 'P') {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001278 s++;
1279 exp_start = s;
1280 if (*s == '-' || *s == '+')
1281 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001282 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001283 goto parse_error;
1284 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001285 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001286 s++;
1287 exp = strtol(exp_start, NULL, 10);
1288 }
1289 else
1290 exp = 0;
1291
1292 /* optional trailing whitespace leading to the end of the string */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001293 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001294 s++;
1295 if (s != s_end)
1296 goto parse_error;
1297
1298/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1299#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1300 coeff_end-(j) : \
1301 coeff_end-1-(j)))
1302
1303 /*******************************************
1304 * Compute rounded value of the hex string *
1305 *******************************************/
1306
1307 /* Discard leading zeros, and catch extreme overflow and underflow */
1308 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1309 ndigits--;
1310 if (ndigits == 0 || exp < LONG_MIN/2) {
1311 x = sign * 0.0;
1312 goto finished;
1313 }
1314 if (exp > LONG_MAX/2)
1315 goto overflow_error;
1316
1317 /* Adjust exponent for fractional part. */
1318 exp = exp - 4*((long)fdigits);
1319
1320 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1321 top_exp = exp + 4*((long)ndigits - 1);
1322 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1323 top_exp++;
1324
1325 /* catch almost all nonextreme cases of overflow and underflow here */
1326 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1327 x = sign * 0.0;
1328 goto finished;
1329 }
1330 if (top_exp > DBL_MAX_EXP)
1331 goto overflow_error;
1332
1333 /* lsb = exponent of least significant bit of the *rounded* value.
1334 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1335 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1336
1337 x = 0.0;
1338 if (exp >= lsb) {
1339 /* no rounding required */
1340 for (i = ndigits-1; i >= 0; i--)
1341 x = 16.0*x + HEX_DIGIT(i);
1342 x = sign * ldexp(x, (int)(exp));
1343 goto finished;
1344 }
1345 /* rounding required. key_digit is the index of the hex digit
1346 containing the first bit to be rounded away. */
1347 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1348 key_digit = (lsb - exp - 1) / 4;
1349 for (i = ndigits-1; i > key_digit; i--)
1350 x = 16.0*x + HEX_DIGIT(i);
1351 digit = HEX_DIGIT(key_digit);
1352 x = 16.0*x + (double)(digit & (16-2*half_eps));
1353
1354 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1355 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1356 if ((digit & half_eps) != 0) {
1357 round_up = 0;
1358 if ((digit & (3*half_eps-1)) != 0 ||
1359 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1360 round_up = 1;
1361 else
1362 for (i = key_digit-1; i >= 0; i--)
1363 if (HEX_DIGIT(i) != 0) {
1364 round_up = 1;
1365 break;
1366 }
1367 if (round_up == 1) {
1368 x += 2*half_eps;
1369 if (top_exp == DBL_MAX_EXP &&
1370 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1371 /* overflow corner case: pre-rounded value <
1372 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1373 goto overflow_error;
1374 }
1375 }
1376 x = sign * ldexp(x, (int)(exp+4*key_digit));
1377
1378 finished:
1379 result_as_float = Py_BuildValue("(d)", x);
1380 if (result_as_float == NULL)
1381 return NULL;
1382 result = PyObject_CallObject(cls, result_as_float);
1383 Py_DECREF(result_as_float);
1384 return result;
1385
1386 overflow_error:
1387 PyErr_SetString(PyExc_OverflowError,
1388 "hexadecimal value too large to represent as a float");
1389 return NULL;
1390
1391 parse_error:
1392 PyErr_SetString(PyExc_ValueError,
1393 "invalid hexadecimal floating-point string");
1394 return NULL;
1395
1396 insane_length_error:
1397 PyErr_SetString(PyExc_ValueError,
1398 "hexadecimal string too long to convert");
1399 return NULL;
1400}
1401
1402PyDoc_STRVAR(float_fromhex_doc,
1403"float.fromhex(string) -> float\n\
1404\n\
1405Create a floating-point number from a hexadecimal string.\n\
1406>>> float.fromhex('0x1.ffffp10')\n\
14072047.984375\n\
1408>>> float.fromhex('-0x1p-1074')\n\
1409-4.9406564584124654e-324");
1410
1411
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001412static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001413float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001414{
1415 double self;
1416 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001417 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001418 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001419
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001420 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001421 PyObject *py_exponent = NULL;
1422 PyObject *numerator = NULL;
1423 PyObject *denominator = NULL;
1424 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001425 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001426
1427#define INPLACE_UPDATE(obj, call) \
1428 prev = obj; \
1429 obj = call; \
1430 Py_DECREF(prev); \
1431
1432 CONVERT_TO_DOUBLE(v, self);
1433
1434 if (Py_IS_INFINITY(self)) {
1435 PyErr_SetString(PyExc_OverflowError,
1436 "Cannot pass infinity to float.as_integer_ratio.");
1437 return NULL;
1438 }
1439#ifdef Py_NAN
1440 if (Py_IS_NAN(self)) {
1441 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001442 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001443 return NULL;
1444 }
1445#endif
1446
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001447 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001448 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001449 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001450
Raymond Hettingerf9859032008-02-01 23:45:44 +00001451 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001452 float_part *= 2.0;
1453 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001454 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001455 /* self == float_part * 2**exponent exactly and float_part is integral.
1456 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1457 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001458
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001459 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001460 if (numerator == NULL) goto error;
1461
Raymond Hettingerf9859032008-02-01 23:45:44 +00001462 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001463 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001464 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001465 if (py_exponent == NULL) goto error;
1466 INPLACE_UPDATE(py_exponent,
1467 long_methods->nb_lshift(denominator, py_exponent));
1468 if (py_exponent == NULL) goto error;
1469 if (exponent > 0) {
1470 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001471 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001472 if (numerator == NULL) goto error;
1473 }
1474 else {
1475 Py_DECREF(denominator);
1476 denominator = py_exponent;
1477 py_exponent = NULL;
1478 }
1479
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001480 /* Returns ints instead of longs where possible */
1481 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1482 if (numerator == NULL) goto error;
1483 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1484 if (denominator == NULL) goto error;
1485
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001486 result_pair = PyTuple_Pack(2, numerator, denominator);
1487
1488#undef INPLACE_UPDATE
1489error:
1490 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001491 Py_XDECREF(denominator);
1492 Py_XDECREF(numerator);
1493 return result_pair;
1494}
1495
1496PyDoc_STRVAR(float_as_integer_ratio_doc,
1497"float.as_integer_ratio() -> (int, int)\n"
1498"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001499"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1500"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001501"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001502"\n"
1503">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001504"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001505">>> (0.0).as_integer_ratio()\n"
1506"(0, 1)\n"
1507">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001508"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001509
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001510
Jeremy Hylton938ace62002-07-17 16:30:39 +00001511static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001512float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1513
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514static PyObject *
1515float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1516{
1517 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001518 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519
Guido van Rossumbef14172001-08-29 15:47:46 +00001520 if (type != &PyFloat_Type)
1521 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1523 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001524 /* If it's a string, but not a string subclass, use
1525 PyFloat_FromString. */
1526 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 return PyFloat_FromString(x, NULL);
1528 return PyNumber_Float(x);
1529}
1530
Guido van Rossumbef14172001-08-29 15:47:46 +00001531/* Wimpy, slow approach to tp_new calls for subtypes of float:
1532 first create a regular float from whatever arguments we got,
1533 then allocate a subtype instance and initialize its ob_fval
1534 from the regular float. The regular float is then thrown away.
1535*/
1536static PyObject *
1537float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1538{
Anthony Baxter377be112006-04-11 06:54:30 +00001539 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001540
1541 assert(PyType_IsSubtype(type, &PyFloat_Type));
1542 tmp = float_new(&PyFloat_Type, args, kwds);
1543 if (tmp == NULL)
1544 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001545 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001546 newobj = type->tp_alloc(type, 0);
1547 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001548 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001549 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001550 }
Anthony Baxter377be112006-04-11 06:54:30 +00001551 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001552 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001553 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001554}
1555
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001556static PyObject *
1557float_getnewargs(PyFloatObject *v)
1558{
1559 return Py_BuildValue("(d)", v->ob_fval);
1560}
1561
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001562/* this is for the benefit of the pack/unpack routines below */
1563
1564typedef enum {
1565 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1566} float_format_type;
1567
1568static float_format_type double_format, float_format;
1569static float_format_type detected_double_format, detected_float_format;
1570
1571static PyObject *
1572float_getformat(PyTypeObject *v, PyObject* arg)
1573{
1574 char* s;
1575 float_format_type r;
1576
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001577 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001578 PyErr_Format(PyExc_TypeError,
1579 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001580 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581 return NULL;
1582 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001583 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001584 if (strcmp(s, "double") == 0) {
1585 r = double_format;
1586 }
1587 else if (strcmp(s, "float") == 0) {
1588 r = float_format;
1589 }
1590 else {
1591 PyErr_SetString(PyExc_ValueError,
1592 "__getformat__() argument 1 must be "
1593 "'double' or 'float'");
1594 return NULL;
1595 }
1596
1597 switch (r) {
1598 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001599 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001600 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001601 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001602 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001603 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001604 default:
1605 Py_FatalError("insane float_format or double_format");
1606 return NULL;
1607 }
1608}
1609
1610PyDoc_STRVAR(float_getformat_doc,
1611"float.__getformat__(typestr) -> string\n"
1612"\n"
1613"You probably don't want to use this function. It exists mainly to be\n"
1614"used in Python's test suite.\n"
1615"\n"
1616"typestr must be 'double' or 'float'. This function returns whichever of\n"
1617"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1618"format of floating point numbers used by the C type named by typestr.");
1619
1620static PyObject *
1621float_setformat(PyTypeObject *v, PyObject* args)
1622{
1623 char* typestr;
1624 char* format;
1625 float_format_type f;
1626 float_format_type detected;
1627 float_format_type *p;
1628
1629 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1630 return NULL;
1631
1632 if (strcmp(typestr, "double") == 0) {
1633 p = &double_format;
1634 detected = detected_double_format;
1635 }
1636 else if (strcmp(typestr, "float") == 0) {
1637 p = &float_format;
1638 detected = detected_float_format;
1639 }
1640 else {
1641 PyErr_SetString(PyExc_ValueError,
1642 "__setformat__() argument 1 must "
1643 "be 'double' or 'float'");
1644 return NULL;
1645 }
1646
1647 if (strcmp(format, "unknown") == 0) {
1648 f = unknown_format;
1649 }
1650 else if (strcmp(format, "IEEE, little-endian") == 0) {
1651 f = ieee_little_endian_format;
1652 }
1653 else if (strcmp(format, "IEEE, big-endian") == 0) {
1654 f = ieee_big_endian_format;
1655 }
1656 else {
1657 PyErr_SetString(PyExc_ValueError,
1658 "__setformat__() argument 2 must be "
1659 "'unknown', 'IEEE, little-endian' or "
1660 "'IEEE, big-endian'");
1661 return NULL;
1662
1663 }
1664
1665 if (f != unknown_format && f != detected) {
1666 PyErr_Format(PyExc_ValueError,
1667 "can only set %s format to 'unknown' or the "
1668 "detected platform value", typestr);
1669 return NULL;
1670 }
1671
1672 *p = f;
1673 Py_RETURN_NONE;
1674}
1675
1676PyDoc_STRVAR(float_setformat_doc,
1677"float.__setformat__(typestr, fmt) -> None\n"
1678"\n"
1679"You probably don't want to use this function. It exists mainly to be\n"
1680"used in Python's test suite.\n"
1681"\n"
1682"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1683"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1684"one of the latter two if it appears to match the underlying C reality.\n"
1685"\n"
1686"Overrides the automatic determination of C-level floating point type.\n"
1687"This affects how floats are converted to and from binary strings.");
1688
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001689static PyObject *
1690float_getzero(PyObject *v, void *closure)
1691{
1692 return PyFloat_FromDouble(0.0);
1693}
1694
Eric Smitha9f7d622008-02-17 19:46:49 +00001695static PyObject *
1696float__format__(PyObject *self, PyObject *args)
1697{
1698 PyObject *format_spec;
1699
1700 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1701 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001702 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001703 return _PyFloat_FormatAdvanced(self,
1704 PyBytes_AS_STRING(format_spec),
1705 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001706 if (PyUnicode_Check(format_spec)) {
1707 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001708 PyObject *result;
1709 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001710
Eric Smithdc13b792008-05-30 18:10:04 +00001711 if (str_spec == NULL)
1712 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001713
Eric Smithdc13b792008-05-30 18:10:04 +00001714 result = _PyFloat_FormatAdvanced(self,
1715 PyBytes_AS_STRING(str_spec),
1716 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001717
Eric Smithdc13b792008-05-30 18:10:04 +00001718 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001719 return result;
1720 }
1721 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1722 return NULL;
1723}
1724
1725PyDoc_STRVAR(float__format__doc,
1726"float.__format__(format_spec) -> string\n"
1727"\n"
1728"Formats the float according to format_spec.");
1729
1730
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001731static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001732 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001733 "Returns self, the complex conjugate of any float."},
1734 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1735 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001736 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1737 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001738 {"fromhex", (PyCFunction)float_fromhex,
1739 METH_O|METH_CLASS, float_fromhex_doc},
1740 {"hex", (PyCFunction)float_hex,
1741 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001742 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1743 "Returns True if the float is an integer."},
1744#if 0
1745 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1746 "Returns True if the float is positive or negative infinite."},
1747 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1748 "Returns True if the float is finite, neither infinite nor NaN."},
1749 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1750 "Returns True if the float is not a number (NaN)."},
1751#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001752 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001753 {"__getformat__", (PyCFunction)float_getformat,
1754 METH_O|METH_CLASS, float_getformat_doc},
1755 {"__setformat__", (PyCFunction)float_setformat,
1756 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001757 {"__format__", (PyCFunction)float__format__,
1758 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001759 {NULL, NULL} /* sentinel */
1760};
1761
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001762static PyGetSetDef float_getset[] = {
1763 {"real",
1764 (getter)float_float, (setter)NULL,
1765 "the real part of a complex number",
1766 NULL},
1767 {"imag",
1768 (getter)float_getzero, (setter)NULL,
1769 "the imaginary part of a complex number",
1770 NULL},
1771 {NULL} /* Sentinel */
1772};
1773
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001774PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775"float(x) -> floating point number\n\
1776\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001777Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778
1779
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001780static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001781 float_add, /*nb_add*/
1782 float_sub, /*nb_subtract*/
1783 float_mul, /*nb_multiply*/
1784 float_classic_div, /*nb_divide*/
1785 float_rem, /*nb_remainder*/
1786 float_divmod, /*nb_divmod*/
1787 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001788 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001789 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001790 (unaryfunc)float_abs, /*nb_absolute*/
1791 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001792 0, /*nb_invert*/
1793 0, /*nb_lshift*/
1794 0, /*nb_rshift*/
1795 0, /*nb_and*/
1796 0, /*nb_xor*/
1797 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001798 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001799 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001800 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001801 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001802 0, /* nb_oct */
1803 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001804 0, /* nb_inplace_add */
1805 0, /* nb_inplace_subtract */
1806 0, /* nb_inplace_multiply */
1807 0, /* nb_inplace_divide */
1808 0, /* nb_inplace_remainder */
1809 0, /* nb_inplace_power */
1810 0, /* nb_inplace_lshift */
1811 0, /* nb_inplace_rshift */
1812 0, /* nb_inplace_and */
1813 0, /* nb_inplace_xor */
1814 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001815 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001816 float_div, /* nb_true_divide */
1817 0, /* nb_inplace_floor_divide */
1818 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819};
1820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001821PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001822 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001825 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 (destructor)float_dealloc, /* tp_dealloc */
1827 (printfunc)float_print, /* tp_print */
1828 0, /* tp_getattr */
1829 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001830 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 (reprfunc)float_repr, /* tp_repr */
1832 &float_as_number, /* tp_as_number */
1833 0, /* tp_as_sequence */
1834 0, /* tp_as_mapping */
1835 (hashfunc)float_hash, /* tp_hash */
1836 0, /* tp_call */
1837 (reprfunc)float_str, /* tp_str */
1838 PyObject_GenericGetAttr, /* tp_getattro */
1839 0, /* tp_setattro */
1840 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001841 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1842 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 float_doc, /* tp_doc */
1844 0, /* tp_traverse */
1845 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001846 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 0, /* tp_weaklistoffset */
1848 0, /* tp_iter */
1849 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001850 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001852 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 0, /* tp_base */
1854 0, /* tp_dict */
1855 0, /* tp_descr_get */
1856 0, /* tp_descr_set */
1857 0, /* tp_dictoffset */
1858 0, /* tp_init */
1859 0, /* tp_alloc */
1860 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001861};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001862
1863void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001864_PyFloat_Init(void)
1865{
1866 /* We attempt to determine if this machine is using IEEE
1867 floating point formats by peering at the bits of some
1868 carefully chosen values. If it looks like we are on an
1869 IEEE platform, the float packing/unpacking routines can
1870 just copy bits, if not they resort to arithmetic & shifts
1871 and masks. The shifts & masks approach works on all finite
1872 values, but what happens to infinities, NaNs and signed
1873 zeroes on packing is an accident, and attempting to unpack
1874 a NaN or an infinity will raise an exception.
1875
1876 Note that if we're on some whacked-out platform which uses
1877 IEEE formats but isn't strictly little-endian or big-
1878 endian, we will fall back to the portable shifts & masks
1879 method. */
1880
1881#if SIZEOF_DOUBLE == 8
1882 {
1883 double x = 9006104071832581.0;
1884 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1885 detected_double_format = ieee_big_endian_format;
1886 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1887 detected_double_format = ieee_little_endian_format;
1888 else
1889 detected_double_format = unknown_format;
1890 }
1891#else
1892 detected_double_format = unknown_format;
1893#endif
1894
1895#if SIZEOF_FLOAT == 4
1896 {
1897 float y = 16711938.0;
1898 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1899 detected_float_format = ieee_big_endian_format;
1900 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1901 detected_float_format = ieee_little_endian_format;
1902 else
1903 detected_float_format = unknown_format;
1904 }
1905#else
1906 detected_float_format = unknown_format;
1907#endif
1908
1909 double_format = detected_double_format;
1910 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001911
Christian Heimes796fc312008-01-30 18:58:29 +00001912 /* Init float info */
1913 if (FloatInfoType.tp_name == 0)
1914 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001915}
1916
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001917int
1918PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001919{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001920 PyFloatObject *p;
1921 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001922 int i;
1923 int u; /* remaining unfreed ints per block */
1924 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001925
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001926 list = block_list;
1927 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001928 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001929 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001930 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001931 for (i = 0, p = &list->objects[0];
1932 i < N_FLOATOBJECTS;
1933 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001934 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001935 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001936 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001937 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001938 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001939 list->next = block_list;
1940 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001941 for (i = 0, p = &list->objects[0];
1942 i < N_FLOATOBJECTS;
1943 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001944 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001945 Py_REFCNT(p) == 0) {
1946 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001947 free_list;
1948 free_list = p;
1949 }
1950 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001951 }
1952 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001953 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001954 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001955 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001956 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001957 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001958 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001959}
1960
1961void
1962PyFloat_Fini(void)
1963{
1964 PyFloatObject *p;
1965 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001966 int i;
1967 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001968
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001969 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00001970
Guido van Rossum3fce8831999-03-12 19:43:17 +00001971 if (!Py_VerboseFlag)
1972 return;
1973 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001974 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001975 fprintf(stderr, "\n");
1976 }
1977 else {
1978 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001979 ": %d unfreed float%s\n",
1980 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001981 }
1982 if (Py_VerboseFlag > 1) {
1983 list = block_list;
1984 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001985 for (i = 0, p = &list->objects[0];
1986 i < N_FLOATOBJECTS;
1987 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001988 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001989 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001990 char buf[100];
1991 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001992 /* XXX(twouters) cast refcount to
1993 long until %zd is universally
1994 available
1995 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001996 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001997 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001998 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001999 }
2000 }
2001 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002002 }
2003 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002004}
Tim Peters9905b942003-03-20 20:53:32 +00002005
2006/*----------------------------------------------------------------------------
2007 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002008 */
2009int
2010_PyFloat_Pack4(double x, unsigned char *p, int le)
2011{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012 if (float_format == unknown_format) {
2013 unsigned char sign;
2014 int e;
2015 double f;
2016 unsigned int fbits;
2017 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002018
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002019 if (le) {
2020 p += 3;
2021 incr = -1;
2022 }
Tim Peters9905b942003-03-20 20:53:32 +00002023
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024 if (x < 0) {
2025 sign = 1;
2026 x = -x;
2027 }
2028 else
2029 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002030
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002031 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002032
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002033 /* Normalize f to be in the range [1.0, 2.0) */
2034 if (0.5 <= f && f < 1.0) {
2035 f *= 2.0;
2036 e--;
2037 }
2038 else if (f == 0.0)
2039 e = 0;
2040 else {
2041 PyErr_SetString(PyExc_SystemError,
2042 "frexp() result out of range");
2043 return -1;
2044 }
2045
2046 if (e >= 128)
2047 goto Overflow;
2048 else if (e < -126) {
2049 /* Gradual underflow */
2050 f = ldexp(f, 126 + e);
2051 e = 0;
2052 }
2053 else if (!(e == 0 && f == 0.0)) {
2054 e += 127;
2055 f -= 1.0; /* Get rid of leading 1 */
2056 }
2057
2058 f *= 8388608.0; /* 2**23 */
2059 fbits = (unsigned int)(f + 0.5); /* Round */
2060 assert(fbits <= 8388608);
2061 if (fbits >> 23) {
2062 /* The carry propagated out of a string of 23 1 bits. */
2063 fbits = 0;
2064 ++e;
2065 if (e >= 255)
2066 goto Overflow;
2067 }
2068
2069 /* First byte */
2070 *p = (sign << 7) | (e >> 1);
2071 p += incr;
2072
2073 /* Second byte */
2074 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2075 p += incr;
2076
2077 /* Third byte */
2078 *p = (fbits >> 8) & 0xFF;
2079 p += incr;
2080
2081 /* Fourth byte */
2082 *p = fbits & 0xFF;
2083
2084 /* Done */
2085 return 0;
2086
Tim Peters9905b942003-03-20 20:53:32 +00002087 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002089 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002090 const char *s = (char*)&y;
2091 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002092
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002093 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2094 goto Overflow;
2095
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002096 if ((float_format == ieee_little_endian_format && !le)
2097 || (float_format == ieee_big_endian_format && le)) {
2098 p += 3;
2099 incr = -1;
2100 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002101
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102 for (i = 0; i < 4; i++) {
2103 *p = *s++;
2104 p += incr;
2105 }
2106 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002107 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002108 Overflow:
2109 PyErr_SetString(PyExc_OverflowError,
2110 "float too large to pack with f format");
2111 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002112}
2113
2114int
2115_PyFloat_Pack8(double x, unsigned char *p, int le)
2116{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117 if (double_format == unknown_format) {
2118 unsigned char sign;
2119 int e;
2120 double f;
2121 unsigned int fhi, flo;
2122 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002123
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124 if (le) {
2125 p += 7;
2126 incr = -1;
2127 }
Tim Peters9905b942003-03-20 20:53:32 +00002128
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129 if (x < 0) {
2130 sign = 1;
2131 x = -x;
2132 }
2133 else
2134 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002135
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002136 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002137
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138 /* Normalize f to be in the range [1.0, 2.0) */
2139 if (0.5 <= f && f < 1.0) {
2140 f *= 2.0;
2141 e--;
2142 }
2143 else if (f == 0.0)
2144 e = 0;
2145 else {
2146 PyErr_SetString(PyExc_SystemError,
2147 "frexp() result out of range");
2148 return -1;
2149 }
2150
2151 if (e >= 1024)
2152 goto Overflow;
2153 else if (e < -1022) {
2154 /* Gradual underflow */
2155 f = ldexp(f, 1022 + e);
2156 e = 0;
2157 }
2158 else if (!(e == 0 && f == 0.0)) {
2159 e += 1023;
2160 f -= 1.0; /* Get rid of leading 1 */
2161 }
2162
2163 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2164 f *= 268435456.0; /* 2**28 */
2165 fhi = (unsigned int)f; /* Truncate */
2166 assert(fhi < 268435456);
2167
2168 f -= (double)fhi;
2169 f *= 16777216.0; /* 2**24 */
2170 flo = (unsigned int)(f + 0.5); /* Round */
2171 assert(flo <= 16777216);
2172 if (flo >> 24) {
2173 /* The carry propagated out of a string of 24 1 bits. */
2174 flo = 0;
2175 ++fhi;
2176 if (fhi >> 28) {
2177 /* And it also progagated out of the next 28 bits. */
2178 fhi = 0;
2179 ++e;
2180 if (e >= 2047)
2181 goto Overflow;
2182 }
2183 }
2184
2185 /* First byte */
2186 *p = (sign << 7) | (e >> 4);
2187 p += incr;
2188
2189 /* Second byte */
2190 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2191 p += incr;
2192
2193 /* Third byte */
2194 *p = (fhi >> 16) & 0xFF;
2195 p += incr;
2196
2197 /* Fourth byte */
2198 *p = (fhi >> 8) & 0xFF;
2199 p += incr;
2200
2201 /* Fifth byte */
2202 *p = fhi & 0xFF;
2203 p += incr;
2204
2205 /* Sixth byte */
2206 *p = (flo >> 16) & 0xFF;
2207 p += incr;
2208
2209 /* Seventh byte */
2210 *p = (flo >> 8) & 0xFF;
2211 p += incr;
2212
2213 /* Eighth byte */
2214 *p = flo & 0xFF;
2215 p += incr;
2216
2217 /* Done */
2218 return 0;
2219
2220 Overflow:
2221 PyErr_SetString(PyExc_OverflowError,
2222 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002223 return -1;
2224 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225 else {
2226 const char *s = (char*)&x;
2227 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002228
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229 if ((double_format == ieee_little_endian_format && !le)
2230 || (double_format == ieee_big_endian_format && le)) {
2231 p += 7;
2232 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002233 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234
2235 for (i = 0; i < 8; i++) {
2236 *p = *s++;
2237 p += incr;
2238 }
2239 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002240 }
Tim Peters9905b942003-03-20 20:53:32 +00002241}
2242
2243double
2244_PyFloat_Unpack4(const unsigned char *p, int le)
2245{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246 if (float_format == unknown_format) {
2247 unsigned char sign;
2248 int e;
2249 unsigned int f;
2250 double x;
2251 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002252
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253 if (le) {
2254 p += 3;
2255 incr = -1;
2256 }
2257
2258 /* First byte */
2259 sign = (*p >> 7) & 1;
2260 e = (*p & 0x7F) << 1;
2261 p += incr;
2262
2263 /* Second byte */
2264 e |= (*p >> 7) & 1;
2265 f = (*p & 0x7F) << 16;
2266 p += incr;
2267
2268 if (e == 255) {
2269 PyErr_SetString(
2270 PyExc_ValueError,
2271 "can't unpack IEEE 754 special value "
2272 "on non-IEEE platform");
2273 return -1;
2274 }
2275
2276 /* Third byte */
2277 f |= *p << 8;
2278 p += incr;
2279
2280 /* Fourth byte */
2281 f |= *p;
2282
2283 x = (double)f / 8388608.0;
2284
2285 /* XXX This sadly ignores Inf/NaN issues */
2286 if (e == 0)
2287 e = -126;
2288 else {
2289 x += 1.0;
2290 e -= 127;
2291 }
2292 x = ldexp(x, e);
2293
2294 if (sign)
2295 x = -x;
2296
2297 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002298 }
Tim Peters9905b942003-03-20 20:53:32 +00002299 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002300 float x;
2301
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302 if ((float_format == ieee_little_endian_format && !le)
2303 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002304 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305 char *d = &buf[3];
2306 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002307
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308 for (i = 0; i < 4; i++) {
2309 *d-- = *p++;
2310 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002311 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312 }
2313 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002314 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002316
2317 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318 }
Tim Peters9905b942003-03-20 20:53:32 +00002319}
2320
2321double
2322_PyFloat_Unpack8(const unsigned char *p, int le)
2323{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324 if (double_format == unknown_format) {
2325 unsigned char sign;
2326 int e;
2327 unsigned int fhi, flo;
2328 double x;
2329 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002330
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331 if (le) {
2332 p += 7;
2333 incr = -1;
2334 }
2335
2336 /* First byte */
2337 sign = (*p >> 7) & 1;
2338 e = (*p & 0x7F) << 4;
2339
2340 p += incr;
2341
2342 /* Second byte */
2343 e |= (*p >> 4) & 0xF;
2344 fhi = (*p & 0xF) << 24;
2345 p += incr;
2346
2347 if (e == 2047) {
2348 PyErr_SetString(
2349 PyExc_ValueError,
2350 "can't unpack IEEE 754 special value "
2351 "on non-IEEE platform");
2352 return -1.0;
2353 }
2354
2355 /* Third byte */
2356 fhi |= *p << 16;
2357 p += incr;
2358
2359 /* Fourth byte */
2360 fhi |= *p << 8;
2361 p += incr;
2362
2363 /* Fifth byte */
2364 fhi |= *p;
2365 p += incr;
2366
2367 /* Sixth byte */
2368 flo = *p << 16;
2369 p += incr;
2370
2371 /* Seventh byte */
2372 flo |= *p << 8;
2373 p += incr;
2374
2375 /* Eighth byte */
2376 flo |= *p;
2377
2378 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2379 x /= 268435456.0; /* 2**28 */
2380
2381 if (e == 0)
2382 e = -1022;
2383 else {
2384 x += 1.0;
2385 e -= 1023;
2386 }
2387 x = ldexp(x, e);
2388
2389 if (sign)
2390 x = -x;
2391
2392 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002393 }
Tim Peters9905b942003-03-20 20:53:32 +00002394 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002395 double x;
2396
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002397 if ((double_format == ieee_little_endian_format && !le)
2398 || (double_format == ieee_big_endian_format && le)) {
2399 char buf[8];
2400 char *d = &buf[7];
2401 int i;
2402
2403 for (i = 0; i < 8; i++) {
2404 *d-- = *p++;
2405 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002406 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002407 }
2408 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002409 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002410 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002411
2412 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002413 }
Tim Peters9905b942003-03-20 20:53:32 +00002414}