blob: 28b2004bce2ee6c4867b06193e7c44705a86e407 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson7103aa42008-07-15 19:08:33 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Neal Norwitz5f95a792008-01-25 08:04:16 +000022#ifdef _OSF_SOURCE
23/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24extern int finite(double);
25#endif
26
Guido van Rossum93ad0df1997-05-13 21:00:42 +000027/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000029#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000030#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000031
Guido van Rossum3fce8831999-03-12 19:43:17 +000032struct _floatblock {
33 struct _floatblock *next;
34 PyFloatObject objects[N_FLOATOBJECTS];
35};
36
37typedef struct _floatblock PyFloatBlock;
38
39static PyFloatBlock *block_list = NULL;
40static PyFloatObject *free_list = NULL;
41
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000043fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044{
45 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000049 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000050 ((PyFloatBlock *)p)->next = block_list;
51 block_list = (PyFloatBlock *)p;
52 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053 q = p + N_FLOATOBJECTS;
54 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000055 Py_TYPE(q) = (struct _typeobject *)(q-1);
56 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000057 return p + N_FLOATOBJECTS - 1;
58}
59
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060double
61PyFloat_GetMax(void)
62{
63 return DBL_MAX;
64}
65
66double
67PyFloat_GetMin(void)
68{
69 return DBL_MIN;
70}
71
Christian Heimes796fc312008-01-30 18:58:29 +000072static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000073
74PyDoc_STRVAR(floatinfo__doc__,
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +000075"sys.float_info\n\
Christian Heimesc94e2b52008-01-14 04:13:37 +000076\n\
77A structseq holding information about the float type. It contains low level\n\
78information about the precision and internal representation. Please study\n\
79your system's :file:`float.h` for more information.");
80
81static PyStructSequence_Field floatinfo_fields[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
84 "is representable"},
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
86 "is representable"},
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
91 "a normalized"},
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
98 {0}
99};
100
101static PyStructSequence_Desc floatinfo_desc = {
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +0000102 "sys.float_info", /* name */
Christian Heimesc94e2b52008-01-14 04:13:37 +0000103 floatinfo__doc__, /* doc */
104 floatinfo_fields, /* fields */
105 11
106};
107
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108PyObject *
109PyFloat_GetInfo(void)
110{
Christian Heimes796fc312008-01-30 18:58:29 +0000111 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000112 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114 floatinfo = PyStructSequence_New(&FloatInfoType);
115 if (floatinfo == NULL) {
116 return NULL;
117 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Christian Heimesc94e2b52008-01-14 04:13:37 +0000119#define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121#define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000123
Christian Heimesc94e2b52008-01-14 04:13:37 +0000124 SetDblFlag(DBL_MAX);
125 SetIntFlag(DBL_MAX_EXP);
126 SetIntFlag(DBL_MAX_10_EXP);
127 SetDblFlag(DBL_MIN);
128 SetIntFlag(DBL_MIN_EXP);
129 SetIntFlag(DBL_MIN_10_EXP);
130 SetIntFlag(DBL_DIG);
131 SetIntFlag(DBL_MANT_DIG);
132 SetDblFlag(DBL_EPSILON);
133 SetIntFlag(FLT_RADIX);
134 SetIntFlag(FLT_ROUNDS);
135#undef SetIntFlag
136#undef SetDblFlag
137
138 if (PyErr_Occurred()) {
139 Py_CLEAR(floatinfo);
140 return NULL;
141 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000142 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
152 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000153 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000155 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Tim Petersef14d732000-09-23 03:39:17 +0000161/**************************************************************************
162RED_FLAG 22-Sep-2000 tim
163PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
164
1651. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
168
1692. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
172
173Since we can't change the interface of a public API function, pend is
174still supported but now *officially* useless: if pend is not NULL,
175*pend is set to NULL.
176**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000178PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179{
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000180 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000182 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#ifdef Py_USING_UNICODE
Mark Dickinson8568b192009-10-26 21:11:20 +0000184 char *s_buffer = NULL;
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;
Mark Dickinson8568b192009-10-26 21:11:20 +0000187 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188
Tim Petersef14d732000-09-23 03:39:17 +0000189 if (pend)
190 *pend = NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000191 if (PyString_Check(v)) {
192 s = PyString_AS_STRING(v);
193 len = PyString_GET_SIZE(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000194 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000195#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000196 else if (PyUnicode_Check(v)) {
Mark Dickinson8568b192009-10-26 21:11:20 +0000197 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
198 if (s_buffer == NULL)
199 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000200 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000201 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000202 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000203 NULL))
Mark Dickinson8568b192009-10-26 21:11:20 +0000204 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000205 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000206 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000207 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000208#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000209 else if (PyObject_AsCharBuffer(v, &s, &len)) {
210 PyErr_SetString(PyExc_TypeError,
Mark Dickinson8568b192009-10-26 21:11:20 +0000211 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000212 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000213 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000215
Mark Dickinson777e4ff2009-05-03 20:59:48 +0000216 while (Py_ISSPACE(*s))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 s++;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000218 /* We don't care about overflow or underflow. If the platform
219 * supports them, infinities and signed zeroes (on underflow) are
220 * fine. */
Mark Dickinson8568b192009-10-26 21:11:20 +0000221 x = PyOS_string_to_double(s, (char **)&end, NULL);
222 if (x == -1.0 && PyErr_Occurred())
223 goto error;
Mark Dickinson777e4ff2009-05-03 20:59:48 +0000224 while (Py_ISSPACE(*end))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000225 end++;
Mark Dickinson8568b192009-10-26 21:11:20 +0000226 if (end == last)
227 result = PyFloat_FromDouble(x);
228 else {
229 PyOS_snprintf(buffer, sizeof(buffer),
230 "invalid literal for float(): %.200s", s);
231 PyErr_SetString(PyExc_ValueError, buffer);
232 result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000233 }
Mark Dickinson8568b192009-10-26 21:11:20 +0000234
235 error:
236#ifdef Py_USING_UNICODE
237 if (s_buffer)
238 PyMem_FREE(s_buffer);
239#endif
240 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000241}
242
Guido van Rossum234f9421993-06-17 12:35:49 +0000243static void
Fred Drakefd99de62000-07-09 05:02:18 +0000244float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000245{
Guido van Rossum9475a232001-10-05 20:51:39 +0000246 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000247 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000248 free_list = op;
249 }
250 else
Christian Heimese93237d2007-12-19 02:37:44 +0000251 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000252}
253
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254double
Fred Drakefd99de62000-07-09 05:02:18 +0000255PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257 PyNumberMethods *nb;
258 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000259 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000260
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000261 if (op && PyFloat_Check(op))
262 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000263
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000264 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266 return -1;
267 }
Tim Petersd2364e82001-11-01 20:09:42 +0000268
Christian Heimese93237d2007-12-19 02:37:44 +0000269 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000270 PyErr_SetString(PyExc_TypeError, "a float is required");
271 return -1;
272 }
273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000275 if (fo == NULL)
276 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 if (!PyFloat_Check(fo)) {
278 PyErr_SetString(PyExc_TypeError,
279 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000280 return -1;
281 }
Tim Petersd2364e82001-11-01 20:09:42 +0000282
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283 val = PyFloat_AS_DOUBLE(fo);
284 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287}
288
289/* Methods */
290
Neil Schemenauer32117e52001-01-04 01:44:34 +0000291/* Macro and helper that convert PyObject obj to a C double and store
292 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000293 slot function. If conversion to double raises an exception, obj is
294 set to NULL, and the function invoking this macro returns NULL. If
295 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
296 stored in obj, and returned from the function invoking this macro.
297*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000298#define CONVERT_TO_DOUBLE(obj, dbl) \
299 if (PyFloat_Check(obj)) \
300 dbl = PyFloat_AS_DOUBLE(obj); \
301 else if (convert_to_double(&(obj), &(dbl)) < 0) \
302 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000303
304static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000305convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000306{
307 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000308
Neil Schemenauer32117e52001-01-04 01:44:34 +0000309 if (PyInt_Check(obj)) {
310 *dbl = (double)PyInt_AS_LONG(obj);
311 }
312 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000313 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000314 if (*dbl == -1.0 && PyErr_Occurred()) {
315 *v = NULL;
316 return -1;
317 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000318 }
319 else {
320 Py_INCREF(Py_NotImplemented);
321 *v = Py_NotImplemented;
322 return -1;
323 }
324 return 0;
325}
326
Eric Smithcfaf79c2009-10-26 14:48:55 +0000327/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
Tim Peters97019e42001-11-28 22:43:45 +0000328 XXX they pass a char buffer without passing a length.
329*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000330void
Fred Drakefd99de62000-07-09 05:02:18 +0000331PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000332{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000333 char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
334 PyFloat_STR_PRECISION,
335 Py_DTSF_ADD_DOT_0, NULL);
336 strcpy(buf, tmp);
337 PyMem_Free(tmp);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000338}
339
Tim Peters72f98e92001-05-08 15:19:57 +0000340void
341PyFloat_AsReprString(char *buf, PyFloatObject *v)
342{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000343 char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
344 Py_DTSF_ADD_DOT_0, NULL);
345 strcpy(buf, tmp);
346 PyMem_Free(tmp);
Tim Peters72f98e92001-05-08 15:19:57 +0000347}
348
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000349/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000350static int
Fred Drakefd99de62000-07-09 05:02:18 +0000351float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000353 char *buf;
354 if (flags & Py_PRINT_RAW)
355 buf = PyOS_double_to_string(v->ob_fval,
356 'g', PyFloat_STR_PRECISION,
357 Py_DTSF_ADD_DOT_0, NULL);
358 else
359 buf = PyOS_double_to_string(v->ob_fval,
360 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
Brett Cannon01531592007-09-17 03:28:34 +0000361 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000363 Py_END_ALLOW_THREADS
Eric Smithcfaf79c2009-10-26 14:48:55 +0000364 PyMem_Free(buf);
Guido van Rossum90933611991-06-07 16:10:43 +0000365 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366}
367
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368static PyObject *
Eric Smithcfaf79c2009-10-26 14:48:55 +0000369float_str_or_repr(PyFloatObject *v, int precision, char format_code)
370{
371 PyObject *result;
372 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
373 format_code, precision,
374 Py_DTSF_ADD_DOT_0,
375 NULL);
376 if (!buf)
377 return PyErr_NoMemory();
378 result = PyString_FromString(buf);
379 PyMem_Free(buf);
380 return result;
381}
382
383static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000384float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000386 return float_str_or_repr(v, 0, 'r');
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{
Eric Smithcfaf79c2009-10-26 14:48:55 +0000392 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393}
394
Tim Peters307fa782004-09-23 08:06:40 +0000395/* Comparison is pretty much a nightmare. When comparing float to float,
396 * we do it as straightforwardly (and long-windedly) as conceivable, so
397 * that, e.g., Python x == y delivers the same result as the platform
398 * C x == y when x and/or y is a NaN.
399 * When mixing float with an integer type, there's no good *uniform* approach.
400 * Converting the double to an integer obviously doesn't work, since we
401 * may lose info from fractional bits. Converting the integer to a double
402 * also has two failure modes: (1) a long int may trigger overflow (too
403 * large to fit in the dynamic range of a C double); (2) even a C long may have
404 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
405 * 63 bits of precision, but a C double probably has only 53), and then
406 * we can falsely claim equality when low-order integer bits are lost by
407 * coercion to double. So this part is painful too.
408 */
409
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000410static PyObject*
411float_richcompare(PyObject *v, PyObject *w, int op)
412{
413 double i, j;
414 int r = 0;
415
Tim Peters307fa782004-09-23 08:06:40 +0000416 assert(PyFloat_Check(v));
417 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000418
Tim Peters307fa782004-09-23 08:06:40 +0000419 /* Switch on the type of w. Set i and j to doubles to be compared,
420 * and op to the richcomp to use.
421 */
422 if (PyFloat_Check(w))
423 j = PyFloat_AS_DOUBLE(w);
424
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000425 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000426 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000427 /* If i is an infinity, its magnitude exceeds any
428 * finite integer, so it doesn't matter which int we
429 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000430 */
431 j = 0.0;
432 else
433 goto Unimplemented;
434 }
435
436 else if (PyInt_Check(w)) {
437 long jj = PyInt_AS_LONG(w);
438 /* In the worst realistic case I can imagine, C double is a
439 * Cray single with 48 bits of precision, and long has 64
440 * bits.
441 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000442#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000443 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
444 if (abs >> 48) {
445 /* Needs more than 48 bits. Make it take the
446 * PyLong path.
447 */
448 PyObject *result;
449 PyObject *ww = PyLong_FromLong(jj);
450
451 if (ww == NULL)
452 return NULL;
453 result = float_richcompare(v, ww, op);
454 Py_DECREF(ww);
455 return result;
456 }
457#endif
458 j = (double)jj;
459 assert((long)j == jj);
460 }
461
462 else if (PyLong_Check(w)) {
463 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
464 int wsign = _PyLong_Sign(w);
465 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000466 int exponent;
467
468 if (vsign != wsign) {
469 /* Magnitudes are irrelevant -- the signs alone
470 * determine the outcome.
471 */
472 i = (double)vsign;
473 j = (double)wsign;
474 goto Compare;
475 }
476 /* The signs are the same. */
477 /* Convert w to a double if it fits. In particular, 0 fits. */
478 nbits = _PyLong_NumBits(w);
479 if (nbits == (size_t)-1 && PyErr_Occurred()) {
480 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000481 * to hold the # of bits. Replace with little doubles
482 * that give the same outcome -- w is so large that
483 * its magnitude must exceed the magnitude of any
484 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000485 */
486 PyErr_Clear();
487 i = (double)vsign;
488 assert(wsign != 0);
489 j = wsign * 2.0;
490 goto Compare;
491 }
492 if (nbits <= 48) {
493 j = PyLong_AsDouble(w);
494 /* It's impossible that <= 48 bits overflowed. */
495 assert(j != -1.0 || ! PyErr_Occurred());
496 goto Compare;
497 }
498 assert(wsign != 0); /* else nbits was 0 */
499 assert(vsign != 0); /* if vsign were 0, then since wsign is
500 * not 0, we would have taken the
501 * vsign != wsign branch at the start */
502 /* We want to work with non-negative numbers. */
503 if (vsign < 0) {
504 /* "Multiply both sides" by -1; this also swaps the
505 * comparator.
506 */
507 i = -i;
508 op = _Py_SwappedOp[op];
509 }
510 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000511 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000512 /* exponent is the # of bits in v before the radix point;
513 * we know that nbits (the # of bits in w) > 48 at this point
514 */
515 if (exponent < 0 || (size_t)exponent < nbits) {
516 i = 1.0;
517 j = 2.0;
518 goto Compare;
519 }
520 if ((size_t)exponent > nbits) {
521 i = 2.0;
522 j = 1.0;
523 goto Compare;
524 }
525 /* v and w have the same number of bits before the radix
526 * point. Construct two longs that have the same comparison
527 * outcome.
528 */
529 {
530 double fracpart;
531 double intpart;
532 PyObject *result = NULL;
533 PyObject *one = NULL;
534 PyObject *vv = NULL;
535 PyObject *ww = w;
536
537 if (wsign < 0) {
538 ww = PyNumber_Negative(w);
539 if (ww == NULL)
540 goto Error;
541 }
542 else
543 Py_INCREF(ww);
544
545 fracpart = modf(i, &intpart);
546 vv = PyLong_FromDouble(intpart);
547 if (vv == NULL)
548 goto Error;
549
550 if (fracpart != 0.0) {
551 /* Shift left, and or a 1 bit into vv
552 * to represent the lost fraction.
553 */
554 PyObject *temp;
555
556 one = PyInt_FromLong(1);
557 if (one == NULL)
558 goto Error;
559
560 temp = PyNumber_Lshift(ww, one);
561 if (temp == NULL)
562 goto Error;
563 Py_DECREF(ww);
564 ww = temp;
565
566 temp = PyNumber_Lshift(vv, one);
567 if (temp == NULL)
568 goto Error;
569 Py_DECREF(vv);
570 vv = temp;
571
572 temp = PyNumber_Or(vv, one);
573 if (temp == NULL)
574 goto Error;
575 Py_DECREF(vv);
576 vv = temp;
577 }
578
579 r = PyObject_RichCompareBool(vv, ww, op);
580 if (r < 0)
581 goto Error;
582 result = PyBool_FromLong(r);
583 Error:
584 Py_XDECREF(vv);
585 Py_XDECREF(ww);
586 Py_XDECREF(one);
587 return result;
588 }
589 } /* else if (PyLong_Check(w)) */
590
591 else /* w isn't float, int, or long */
592 goto Unimplemented;
593
594 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000595 PyFPE_START_PROTECT("richcompare", return NULL)
596 switch (op) {
597 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000598 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000599 break;
600 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000601 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000602 break;
603 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000604 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000605 break;
606 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000607 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000608 break;
609 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000610 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000611 break;
612 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000613 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000614 break;
615 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000616 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000617 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000618
619 Unimplemented:
620 Py_INCREF(Py_NotImplemented);
621 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000622}
623
Guido van Rossum9bfef441993-03-29 10:43:31 +0000624static long
Fred Drakefd99de62000-07-09 05:02:18 +0000625float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000626{
Tim Peters39dce292000-08-15 03:34:48 +0000627 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000628}
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000631float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000633 double a,b;
634 CONVERT_TO_DOUBLE(v, a);
635 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000636 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000637 a = a + b;
638 PyFPE_END_PROTECT(a)
639 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640}
641
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000642static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000643float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000644{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000645 double a,b;
646 CONVERT_TO_DOUBLE(v, a);
647 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000648 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000649 a = a - b;
650 PyFPE_END_PROTECT(a)
651 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000652}
653
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000654static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000655float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000656{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000657 double a,b;
658 CONVERT_TO_DOUBLE(v, a);
659 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000660 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000661 a = a * b;
662 PyFPE_END_PROTECT(a)
663 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000667float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000668{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000669 double a,b;
670 CONVERT_TO_DOUBLE(v, a);
671 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000672#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000673 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000674 PyErr_SetString(PyExc_ZeroDivisionError,
675 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676 return NULL;
677 }
Christian Heimes6f341092008-04-18 23:13:07 +0000678#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000679 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000680 a = a / b;
681 PyFPE_END_PROTECT(a)
682 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000683}
684
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000686float_classic_div(PyObject *v, PyObject *w)
687{
688 double a,b;
689 CONVERT_TO_DOUBLE(v, a);
690 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000691 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000692 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
693 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000694#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000695 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000696 PyErr_SetString(PyExc_ZeroDivisionError,
697 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000698 return NULL;
699 }
Christian Heimes6f341092008-04-18 23:13:07 +0000700#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000701 PyFPE_START_PROTECT("divide", return 0)
702 a = a / b;
703 PyFPE_END_PROTECT(a)
704 return PyFloat_FromDouble(a);
705}
706
707static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000708float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000709{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000710 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000711 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000712 CONVERT_TO_DOUBLE(v, vx);
713 CONVERT_TO_DOUBLE(w, wx);
714#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000716 PyErr_SetString(PyExc_ZeroDivisionError,
717 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718 return NULL;
719 }
Christian Heimes6f341092008-04-18 23:13:07 +0000720#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000721 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000722 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000723 /* note: checking mod*wx < 0 is incorrect -- underflows to
724 0 if wx < sqrt(smallest nonzero double) */
725 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000726 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000727 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000728 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730}
731
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000733float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000734{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000735 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000736 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000737 CONVERT_TO_DOUBLE(v, vx);
738 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000739 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000741 return NULL;
742 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000743 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000744 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000745 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000746 exact multiple of wx. But this is fp arithmetic, and fp
747 vx - mod is an approximation; the result is that div may
748 not be an exact integral value after the division, although
749 it will always be very close to one.
750 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000751 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000752 if (mod) {
753 /* ensure the remainder has the same sign as the denominator */
754 if ((wx < 0) != (mod < 0)) {
755 mod += wx;
756 div -= 1.0;
757 }
758 }
759 else {
760 /* the remainder is zero, and in the presence of signed zeroes
761 fmod returns different results across platforms; ensure
762 it has the same sign as the denominator; we'd like to do
763 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000764 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000765 if (wx < 0.0)
766 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000767 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000768 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000769 if (div) {
770 floordiv = floor(div);
771 if (div - floordiv > 0.5)
772 floordiv += 1.0;
773 }
774 else {
775 /* div is zero - get the same sign as the true quotient */
776 div *= div; /* hide "div = +0" from optimizers */
777 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
778 }
779 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000780 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000781}
782
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000784float_floor_div(PyObject *v, PyObject *w)
785{
786 PyObject *t, *r;
787
788 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000789 if (t == NULL || t == Py_NotImplemented)
790 return t;
791 assert(PyTuple_CheckExact(t));
792 r = PyTuple_GET_ITEM(t, 0);
793 Py_INCREF(r);
794 Py_DECREF(t);
795 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000796}
797
798static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000799float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800{
801 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000802
803 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000804 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000805 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000806 return NULL;
807 }
808
Neil Schemenauer32117e52001-01-04 01:44:34 +0000809 CONVERT_TO_DOUBLE(v, iv);
810 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000811
812 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000813 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000814 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000815 }
Tim Peters96685bf2001-08-23 22:31:37 +0000816 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000817 if (iw < 0.0) {
818 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000819 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000820 return NULL;
821 }
822 return PyFloat_FromDouble(0.0);
823 }
Christian Heimes6f341092008-04-18 23:13:07 +0000824 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
825 return PyFloat_FromDouble(1.0);
826 }
Tim Peterse87568d2003-05-24 20:18:24 +0000827 if (iv < 0.0) {
828 /* Whether this is an error is a mess, and bumps into libm
829 * bugs so we have to figure it out ourselves.
830 */
831 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000832 PyErr_SetString(PyExc_ValueError, "negative number "
833 "cannot be raised to a fractional power");
834 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000835 }
836 /* iw is an exact integer, albeit perhaps a very large one.
837 * -1 raised to an exact integer should never be exceptional.
838 * Alas, some libms (chiefly glibc as of early 2003) return
839 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
840 * happen to be representable in a *C* integer. That's a
841 * bug; we let that slide in math.pow() (which currently
842 * reflects all platform accidents), but not for Python's **.
843 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000844 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000845 /* Return 1 if iw is even, -1 if iw is odd; there's
846 * no guarantee that any C integral type is big
847 * enough to hold iw, so we have to check this
848 * indirectly.
849 */
850 ix = floor(iw * 0.5) * 2.0;
851 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
852 }
853 /* Else iv != -1.0, and overflow or underflow are possible.
854 * Unless we're to write pow() ourselves, we have to trust
855 * the platform to do this correctly.
856 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000857 }
Tim Peters96685bf2001-08-23 22:31:37 +0000858 errno = 0;
859 PyFPE_START_PROTECT("pow", return NULL)
860 ix = pow(iv, iw);
861 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000862 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000863 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000864 /* We don't expect any errno value other than ERANGE, but
865 * the range of libm bugs appears unbounded.
866 */
Alex Martelli348dc882006-08-23 22:17:59 +0000867 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
868 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000870 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000871 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872}
873
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000874static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000875float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000876{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000878}
879
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000880static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000881float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000882{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000883 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884}
885
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000886static int
Fred Drakefd99de62000-07-09 05:02:18 +0000887float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000888{
889 return v->ob_fval != 0.0;
890}
891
Guido van Rossum234f9421993-06-17 12:35:49 +0000892static int
Fred Drakefd99de62000-07-09 05:02:18 +0000893float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000894{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000895 if (PyInt_Check(*pw)) {
896 long x = PyInt_AsLong(*pw);
897 *pw = PyFloat_FromDouble((double)x);
898 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000899 return 0;
900 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000901 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000902 double x = PyLong_AsDouble(*pw);
903 if (x == -1.0 && PyErr_Occurred())
904 return -1;
905 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000906 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000907 return 0;
908 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000909 else if (PyFloat_Check(*pw)) {
910 Py_INCREF(*pv);
911 Py_INCREF(*pw);
912 return 0;
913 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000914 return 1; /* Can't do it */
915}
916
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000917static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000918float_is_integer(PyObject *v)
919{
920 double x = PyFloat_AsDouble(v);
921 PyObject *o;
922
923 if (x == -1.0 && PyErr_Occurred())
924 return NULL;
925 if (!Py_IS_FINITE(x))
926 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +0000927 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000928 PyFPE_START_PROTECT("is_integer", return NULL)
929 o = (floor(x) == x) ? Py_True : Py_False;
930 PyFPE_END_PROTECT(x)
931 if (errno != 0) {
932 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
933 PyExc_ValueError);
934 return NULL;
935 }
936 Py_INCREF(o);
937 return o;
938}
939
940#if 0
941static PyObject *
942float_is_inf(PyObject *v)
943{
944 double x = PyFloat_AsDouble(v);
945 if (x == -1.0 && PyErr_Occurred())
946 return NULL;
947 return PyBool_FromLong((long)Py_IS_INFINITY(x));
948}
949
950static PyObject *
951float_is_nan(PyObject *v)
952{
953 double x = PyFloat_AsDouble(v);
954 if (x == -1.0 && PyErr_Occurred())
955 return NULL;
956 return PyBool_FromLong((long)Py_IS_NAN(x));
957}
958
959static PyObject *
960float_is_finite(PyObject *v)
961{
962 double x = PyFloat_AsDouble(v);
963 if (x == -1.0 && PyErr_Occurred())
964 return NULL;
965 return PyBool_FromLong((long)Py_IS_FINITE(x));
966}
967#endif
968
969static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000970float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000971{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000972 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000973 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000974
975 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000976 /* Try to get out cheap if this fits in a Python int. The attempt
977 * to cast to long must be protected, as C doesn't define what
978 * happens if the double is too big to fit in a long. Some rare
979 * systems raise an exception then (RISCOS was mentioned as one,
980 * and someone using a non-default option on Sun also bumped into
981 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
982 * still be vulnerable: if a long has more bits of precision than
983 * a double, casting MIN/MAX to double may yield an approximation,
984 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
985 * yield true from the C expression wholepart<=LONG_MAX, despite
986 * that wholepart is actually greater than LONG_MAX.
987 */
988 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
989 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000990 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000991 }
992 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000993}
994
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000995static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +0000996float_long(PyObject *v)
997{
998 double x = PyFloat_AsDouble(v);
999 return PyLong_FromDouble(x);
1000}
1001
1002static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001003float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001004{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001005 if (PyFloat_CheckExact(v))
1006 Py_INCREF(v);
1007 else
1008 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001009 return v;
1010}
1011
Mark Dickinson7103aa42008-07-15 19:08:33 +00001012/* turn ASCII hex characters into integer values and vice versa */
1013
1014static char
1015char_from_hex(int x)
1016{
1017 assert(0 <= x && x < 16);
1018 return "0123456789abcdef"[x];
1019}
1020
1021static int
1022hex_from_char(char c) {
1023 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001024 switch(c) {
1025 case '0':
1026 x = 0;
1027 break;
1028 case '1':
1029 x = 1;
1030 break;
1031 case '2':
1032 x = 2;
1033 break;
1034 case '3':
1035 x = 3;
1036 break;
1037 case '4':
1038 x = 4;
1039 break;
1040 case '5':
1041 x = 5;
1042 break;
1043 case '6':
1044 x = 6;
1045 break;
1046 case '7':
1047 x = 7;
1048 break;
1049 case '8':
1050 x = 8;
1051 break;
1052 case '9':
1053 x = 9;
1054 break;
1055 case 'a':
1056 case 'A':
1057 x = 10;
1058 break;
1059 case 'b':
1060 case 'B':
1061 x = 11;
1062 break;
1063 case 'c':
1064 case 'C':
1065 x = 12;
1066 break;
1067 case 'd':
1068 case 'D':
1069 x = 13;
1070 break;
1071 case 'e':
1072 case 'E':
1073 x = 14;
1074 break;
1075 case 'f':
1076 case 'F':
1077 x = 15;
1078 break;
1079 default:
1080 x = -1;
1081 break;
1082 }
1083 return x;
1084}
1085
1086/* convert a float to a hexadecimal string */
1087
1088/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1089 of the form 4k+1. */
1090#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1091
1092static PyObject *
1093float_hex(PyObject *v)
1094{
1095 double x, m;
1096 int e, shift, i, si, esign;
1097 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1098 trailing NUL byte. */
1099 char s[(TOHEX_NBITS-1)/4+3];
1100
1101 CONVERT_TO_DOUBLE(v, x);
1102
1103 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1104 return float_str((PyFloatObject *)v);
1105
1106 if (x == 0.0) {
1107 if(copysign(1.0, x) == -1.0)
1108 return PyString_FromString("-0x0.0p+0");
1109 else
1110 return PyString_FromString("0x0.0p+0");
1111 }
1112
1113 m = frexp(fabs(x), &e);
1114 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1115 m = ldexp(m, shift);
1116 e -= shift;
1117
1118 si = 0;
1119 s[si] = char_from_hex((int)m);
1120 si++;
1121 m -= (int)m;
1122 s[si] = '.';
1123 si++;
1124 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1125 m *= 16.0;
1126 s[si] = char_from_hex((int)m);
1127 si++;
1128 m -= (int)m;
1129 }
1130 s[si] = '\0';
1131
1132 if (e < 0) {
1133 esign = (int)'-';
1134 e = -e;
1135 }
1136 else
1137 esign = (int)'+';
1138
1139 if (x < 0.0)
1140 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1141 else
1142 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1143}
1144
1145PyDoc_STRVAR(float_hex_doc,
1146"float.hex() -> string\n\
1147\n\
1148Return a hexadecimal representation of a floating-point number.\n\
1149>>> (-0.1).hex()\n\
1150'-0x1.999999999999ap-4'\n\
1151>>> 3.14159.hex()\n\
1152'0x1.921f9f01b866ep+1'");
1153
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001154/* Case-insensitive locale-independent string match used for nan and inf
1155 detection. t should be lower-case and null-terminated. Return a nonzero
1156 result if the first strlen(t) characters of s match t and 0 otherwise. */
1157
1158static int
1159case_insensitive_match(const char *s, const char *t)
1160{
1161 while(*t && Py_TOLOWER(*s) == *t) {
1162 s++;
1163 t++;
1164 }
1165 return *t ? 0 : 1;
1166}
1167
Mark Dickinson7103aa42008-07-15 19:08:33 +00001168/* Convert a hexadecimal string to a float. */
1169
1170static PyObject *
1171float_fromhex(PyObject *cls, PyObject *arg)
1172{
1173 PyObject *result_as_float, *result;
1174 double x;
1175 long exp, top_exp, lsb, key_digit;
1176 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1177 int half_eps, digit, round_up, sign=1;
1178 Py_ssize_t length, ndigits, fdigits, i;
1179
1180 /*
1181 * For the sake of simplicity and correctness, we impose an artificial
1182 * limit on ndigits, the total number of hex digits in the coefficient
1183 * The limit is chosen to ensure that, writing exp for the exponent,
1184 *
1185 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1186 * guaranteed to overflow (provided it's nonzero)
1187 *
1188 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1189 * guaranteed to underflow to 0.
1190 *
1191 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1192 * overflow in the calculation of exp and top_exp below.
1193 *
1194 * More specifically, ndigits is assumed to satisfy the following
1195 * inequalities:
1196 *
1197 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1198 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1199 *
1200 * If either of these inequalities is not satisfied, a ValueError is
1201 * raised. Otherwise, write x for the value of the hex string, and
1202 * assume x is nonzero. Then
1203 *
1204 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1205 *
1206 * Now if exp > LONG_MAX/2 then:
1207 *
1208 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1209 * = DBL_MAX_EXP
1210 *
1211 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1212 * double, so overflows. If exp < LONG_MIN/2, then
1213 *
1214 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1215 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1216 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1217 *
1218 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1219 * when converted to a C double.
1220 *
1221 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1222 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1223 */
1224
1225 if (PyString_AsStringAndSize(arg, &s, &length))
1226 return NULL;
1227 s_end = s + length;
1228
1229 /********************
1230 * Parse the string *
1231 ********************/
1232
1233 /* leading whitespace and optional sign */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001234 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001235 s++;
1236 if (*s == '-') {
1237 s++;
1238 sign = -1;
1239 }
1240 else if (*s == '+')
1241 s++;
1242
1243 /* infinities and nans */
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001244 if (*s == 'i' || *s == 'I') {
1245 if (!case_insensitive_match(s+1, "nf"))
1246 goto parse_error;
1247 s += 3;
1248 x = Py_HUGE_VAL;
1249 if (case_insensitive_match(s, "inity"))
1250 s += 5;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001251 goto finished;
1252 }
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001253 if (*s == 'n' || *s == 'N') {
1254 if (!case_insensitive_match(s+1, "an"))
1255 goto parse_error;
1256 s += 3;
1257 x = Py_NAN;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001258 goto finished;
1259 }
1260
1261 /* [0x] */
1262 s_store = s;
1263 if (*s == '0') {
1264 s++;
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001265 if (*s == 'x' || *s == 'X')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001266 s++;
1267 else
1268 s = s_store;
1269 }
1270
1271 /* coefficient: <integer> [. <fraction>] */
1272 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001273 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001274 s++;
1275 s_store = s;
1276 if (*s == '.') {
1277 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001278 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001279 s++;
1280 coeff_end = s-1;
1281 }
1282 else
1283 coeff_end = s;
1284
1285 /* ndigits = total # of hex digits; fdigits = # after point */
1286 ndigits = coeff_end - coeff_start;
1287 fdigits = coeff_end - s_store;
1288 if (ndigits == 0)
1289 goto parse_error;
1290 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1291 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1292 goto insane_length_error;
1293
1294 /* [p <exponent>] */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001295 if (*s == 'p' || *s == 'P') {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001296 s++;
1297 exp_start = s;
1298 if (*s == '-' || *s == '+')
1299 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001300 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001301 goto parse_error;
1302 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001303 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001304 s++;
1305 exp = strtol(exp_start, NULL, 10);
1306 }
1307 else
1308 exp = 0;
1309
Mark Dickinson7103aa42008-07-15 19:08:33 +00001310/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1311#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1312 coeff_end-(j) : \
1313 coeff_end-1-(j)))
1314
1315 /*******************************************
1316 * Compute rounded value of the hex string *
1317 *******************************************/
1318
1319 /* Discard leading zeros, and catch extreme overflow and underflow */
1320 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1321 ndigits--;
1322 if (ndigits == 0 || exp < LONG_MIN/2) {
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001323 x = 0.0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001324 goto finished;
1325 }
1326 if (exp > LONG_MAX/2)
1327 goto overflow_error;
1328
1329 /* Adjust exponent for fractional part. */
1330 exp = exp - 4*((long)fdigits);
1331
1332 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1333 top_exp = exp + 4*((long)ndigits - 1);
1334 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1335 top_exp++;
1336
1337 /* catch almost all nonextreme cases of overflow and underflow here */
1338 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001339 x = 0.0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001340 goto finished;
1341 }
1342 if (top_exp > DBL_MAX_EXP)
1343 goto overflow_error;
1344
1345 /* lsb = exponent of least significant bit of the *rounded* value.
1346 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1347 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1348
1349 x = 0.0;
1350 if (exp >= lsb) {
1351 /* no rounding required */
1352 for (i = ndigits-1; i >= 0; i--)
1353 x = 16.0*x + HEX_DIGIT(i);
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001354 x = ldexp(x, (int)(exp));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001355 goto finished;
1356 }
1357 /* rounding required. key_digit is the index of the hex digit
1358 containing the first bit to be rounded away. */
1359 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1360 key_digit = (lsb - exp - 1) / 4;
1361 for (i = ndigits-1; i > key_digit; i--)
1362 x = 16.0*x + HEX_DIGIT(i);
1363 digit = HEX_DIGIT(key_digit);
1364 x = 16.0*x + (double)(digit & (16-2*half_eps));
1365
1366 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1367 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1368 if ((digit & half_eps) != 0) {
1369 round_up = 0;
1370 if ((digit & (3*half_eps-1)) != 0 ||
1371 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1372 round_up = 1;
1373 else
1374 for (i = key_digit-1; i >= 0; i--)
1375 if (HEX_DIGIT(i) != 0) {
1376 round_up = 1;
1377 break;
1378 }
1379 if (round_up == 1) {
1380 x += 2*half_eps;
1381 if (top_exp == DBL_MAX_EXP &&
1382 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1383 /* overflow corner case: pre-rounded value <
1384 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1385 goto overflow_error;
1386 }
1387 }
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001388 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001389
1390 finished:
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001391 /* optional trailing whitespace leading to the end of the string */
1392 while (Py_ISSPACE(*s))
1393 s++;
1394 if (s != s_end)
1395 goto parse_error;
1396 result_as_float = Py_BuildValue("(d)", sign * x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001397 if (result_as_float == NULL)
1398 return NULL;
1399 result = PyObject_CallObject(cls, result_as_float);
1400 Py_DECREF(result_as_float);
1401 return result;
1402
1403 overflow_error:
1404 PyErr_SetString(PyExc_OverflowError,
1405 "hexadecimal value too large to represent as a float");
1406 return NULL;
1407
1408 parse_error:
1409 PyErr_SetString(PyExc_ValueError,
1410 "invalid hexadecimal floating-point string");
1411 return NULL;
1412
1413 insane_length_error:
1414 PyErr_SetString(PyExc_ValueError,
1415 "hexadecimal string too long to convert");
1416 return NULL;
1417}
1418
1419PyDoc_STRVAR(float_fromhex_doc,
1420"float.fromhex(string) -> float\n\
1421\n\
1422Create a floating-point number from a hexadecimal string.\n\
1423>>> float.fromhex('0x1.ffffp10')\n\
14242047.984375\n\
1425>>> float.fromhex('-0x1p-1074')\n\
1426-4.9406564584124654e-324");
1427
1428
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001429static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001430float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001431{
1432 double self;
1433 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001434 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001435 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001436
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001437 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001438 PyObject *py_exponent = NULL;
1439 PyObject *numerator = NULL;
1440 PyObject *denominator = NULL;
1441 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001442 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001443
1444#define INPLACE_UPDATE(obj, call) \
1445 prev = obj; \
1446 obj = call; \
1447 Py_DECREF(prev); \
1448
1449 CONVERT_TO_DOUBLE(v, self);
1450
1451 if (Py_IS_INFINITY(self)) {
1452 PyErr_SetString(PyExc_OverflowError,
1453 "Cannot pass infinity to float.as_integer_ratio.");
1454 return NULL;
1455 }
1456#ifdef Py_NAN
1457 if (Py_IS_NAN(self)) {
1458 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001459 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001460 return NULL;
1461 }
1462#endif
1463
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001464 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001465 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001466 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001467
Raymond Hettingerf9859032008-02-01 23:45:44 +00001468 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001469 float_part *= 2.0;
1470 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001471 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001472 /* self == float_part * 2**exponent exactly and float_part is integral.
1473 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1474 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001475
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001476 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001477 if (numerator == NULL) goto error;
1478
Raymond Hettingerf9859032008-02-01 23:45:44 +00001479 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001480 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001481 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001482 if (py_exponent == NULL) goto error;
1483 INPLACE_UPDATE(py_exponent,
1484 long_methods->nb_lshift(denominator, py_exponent));
1485 if (py_exponent == NULL) goto error;
1486 if (exponent > 0) {
1487 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001488 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001489 if (numerator == NULL) goto error;
1490 }
1491 else {
1492 Py_DECREF(denominator);
1493 denominator = py_exponent;
1494 py_exponent = NULL;
1495 }
1496
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001497 /* Returns ints instead of longs where possible */
1498 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1499 if (numerator == NULL) goto error;
1500 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1501 if (denominator == NULL) goto error;
1502
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001503 result_pair = PyTuple_Pack(2, numerator, denominator);
1504
1505#undef INPLACE_UPDATE
1506error:
1507 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001508 Py_XDECREF(denominator);
1509 Py_XDECREF(numerator);
1510 return result_pair;
1511}
1512
1513PyDoc_STRVAR(float_as_integer_ratio_doc,
1514"float.as_integer_ratio() -> (int, int)\n"
1515"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001516"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1517"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001518"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001519"\n"
1520">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001521"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001522">>> (0.0).as_integer_ratio()\n"
1523"(0, 1)\n"
1524">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001525"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001526
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001527
Jeremy Hylton938ace62002-07-17 16:30:39 +00001528static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001529float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1530
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531static PyObject *
1532float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1533{
1534 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001535 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536
Guido van Rossumbef14172001-08-29 15:47:46 +00001537 if (type != &PyFloat_Type)
1538 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1540 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001541 /* If it's a string, but not a string subclass, use
1542 PyFloat_FromString. */
1543 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 return PyFloat_FromString(x, NULL);
1545 return PyNumber_Float(x);
1546}
1547
Guido van Rossumbef14172001-08-29 15:47:46 +00001548/* Wimpy, slow approach to tp_new calls for subtypes of float:
1549 first create a regular float from whatever arguments we got,
1550 then allocate a subtype instance and initialize its ob_fval
1551 from the regular float. The regular float is then thrown away.
1552*/
1553static PyObject *
1554float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1555{
Anthony Baxter377be112006-04-11 06:54:30 +00001556 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001557
1558 assert(PyType_IsSubtype(type, &PyFloat_Type));
1559 tmp = float_new(&PyFloat_Type, args, kwds);
1560 if (tmp == NULL)
1561 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001562 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001563 newobj = type->tp_alloc(type, 0);
1564 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001565 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001566 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001567 }
Anthony Baxter377be112006-04-11 06:54:30 +00001568 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001569 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001570 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001571}
1572
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001573static PyObject *
1574float_getnewargs(PyFloatObject *v)
1575{
1576 return Py_BuildValue("(d)", v->ob_fval);
1577}
1578
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001579/* this is for the benefit of the pack/unpack routines below */
1580
1581typedef enum {
1582 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1583} float_format_type;
1584
1585static float_format_type double_format, float_format;
1586static float_format_type detected_double_format, detected_float_format;
1587
1588static PyObject *
1589float_getformat(PyTypeObject *v, PyObject* arg)
1590{
1591 char* s;
1592 float_format_type r;
1593
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001594 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001595 PyErr_Format(PyExc_TypeError,
1596 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001597 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001598 return NULL;
1599 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001600 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001601 if (strcmp(s, "double") == 0) {
1602 r = double_format;
1603 }
1604 else if (strcmp(s, "float") == 0) {
1605 r = float_format;
1606 }
1607 else {
1608 PyErr_SetString(PyExc_ValueError,
1609 "__getformat__() argument 1 must be "
1610 "'double' or 'float'");
1611 return NULL;
1612 }
1613
1614 switch (r) {
1615 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001616 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001618 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001619 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001620 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621 default:
1622 Py_FatalError("insane float_format or double_format");
1623 return NULL;
1624 }
1625}
1626
1627PyDoc_STRVAR(float_getformat_doc,
1628"float.__getformat__(typestr) -> string\n"
1629"\n"
1630"You probably don't want to use this function. It exists mainly to be\n"
1631"used in Python's test suite.\n"
1632"\n"
1633"typestr must be 'double' or 'float'. This function returns whichever of\n"
1634"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1635"format of floating point numbers used by the C type named by typestr.");
1636
1637static PyObject *
1638float_setformat(PyTypeObject *v, PyObject* args)
1639{
1640 char* typestr;
1641 char* format;
1642 float_format_type f;
1643 float_format_type detected;
1644 float_format_type *p;
1645
1646 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1647 return NULL;
1648
1649 if (strcmp(typestr, "double") == 0) {
1650 p = &double_format;
1651 detected = detected_double_format;
1652 }
1653 else if (strcmp(typestr, "float") == 0) {
1654 p = &float_format;
1655 detected = detected_float_format;
1656 }
1657 else {
1658 PyErr_SetString(PyExc_ValueError,
1659 "__setformat__() argument 1 must "
1660 "be 'double' or 'float'");
1661 return NULL;
1662 }
1663
1664 if (strcmp(format, "unknown") == 0) {
1665 f = unknown_format;
1666 }
1667 else if (strcmp(format, "IEEE, little-endian") == 0) {
1668 f = ieee_little_endian_format;
1669 }
1670 else if (strcmp(format, "IEEE, big-endian") == 0) {
1671 f = ieee_big_endian_format;
1672 }
1673 else {
1674 PyErr_SetString(PyExc_ValueError,
1675 "__setformat__() argument 2 must be "
1676 "'unknown', 'IEEE, little-endian' or "
1677 "'IEEE, big-endian'");
1678 return NULL;
1679
1680 }
1681
1682 if (f != unknown_format && f != detected) {
1683 PyErr_Format(PyExc_ValueError,
1684 "can only set %s format to 'unknown' or the "
1685 "detected platform value", typestr);
1686 return NULL;
1687 }
1688
1689 *p = f;
1690 Py_RETURN_NONE;
1691}
1692
1693PyDoc_STRVAR(float_setformat_doc,
1694"float.__setformat__(typestr, fmt) -> None\n"
1695"\n"
1696"You probably don't want to use this function. It exists mainly to be\n"
1697"used in Python's test suite.\n"
1698"\n"
1699"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1700"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1701"one of the latter two if it appears to match the underlying C reality.\n"
1702"\n"
1703"Overrides the automatic determination of C-level floating point type.\n"
1704"This affects how floats are converted to and from binary strings.");
1705
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001706static PyObject *
1707float_getzero(PyObject *v, void *closure)
1708{
1709 return PyFloat_FromDouble(0.0);
1710}
1711
Eric Smitha9f7d622008-02-17 19:46:49 +00001712static PyObject *
1713float__format__(PyObject *self, PyObject *args)
1714{
1715 PyObject *format_spec;
1716
1717 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1718 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001719 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001720 return _PyFloat_FormatAdvanced(self,
1721 PyBytes_AS_STRING(format_spec),
1722 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001723 if (PyUnicode_Check(format_spec)) {
1724 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001725 PyObject *result;
1726 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001727
Eric Smithdc13b792008-05-30 18:10:04 +00001728 if (str_spec == NULL)
1729 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001730
Eric Smithdc13b792008-05-30 18:10:04 +00001731 result = _PyFloat_FormatAdvanced(self,
1732 PyBytes_AS_STRING(str_spec),
1733 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001734
Eric Smithdc13b792008-05-30 18:10:04 +00001735 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001736 return result;
1737 }
1738 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1739 return NULL;
1740}
1741
1742PyDoc_STRVAR(float__format__doc,
1743"float.__format__(format_spec) -> string\n"
1744"\n"
1745"Formats the float according to format_spec.");
1746
1747
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001748static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001749 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001750 "Returns self, the complex conjugate of any float."},
1751 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1752 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001753 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1754 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001755 {"fromhex", (PyCFunction)float_fromhex,
1756 METH_O|METH_CLASS, float_fromhex_doc},
1757 {"hex", (PyCFunction)float_hex,
1758 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001759 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1760 "Returns True if the float is an integer."},
1761#if 0
1762 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1763 "Returns True if the float is positive or negative infinite."},
1764 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1765 "Returns True if the float is finite, neither infinite nor NaN."},
1766 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1767 "Returns True if the float is not a number (NaN)."},
1768#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001769 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001770 {"__getformat__", (PyCFunction)float_getformat,
1771 METH_O|METH_CLASS, float_getformat_doc},
1772 {"__setformat__", (PyCFunction)float_setformat,
1773 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001774 {"__format__", (PyCFunction)float__format__,
1775 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001776 {NULL, NULL} /* sentinel */
1777};
1778
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001779static PyGetSetDef float_getset[] = {
1780 {"real",
1781 (getter)float_float, (setter)NULL,
1782 "the real part of a complex number",
1783 NULL},
1784 {"imag",
1785 (getter)float_getzero, (setter)NULL,
1786 "the imaginary part of a complex number",
1787 NULL},
1788 {NULL} /* Sentinel */
1789};
1790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001791PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792"float(x) -> floating point number\n\
1793\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795
1796
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001797static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001798 float_add, /*nb_add*/
1799 float_sub, /*nb_subtract*/
1800 float_mul, /*nb_multiply*/
1801 float_classic_div, /*nb_divide*/
1802 float_rem, /*nb_remainder*/
1803 float_divmod, /*nb_divmod*/
1804 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001805 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001806 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001807 (unaryfunc)float_abs, /*nb_absolute*/
1808 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001809 0, /*nb_invert*/
1810 0, /*nb_lshift*/
1811 0, /*nb_rshift*/
1812 0, /*nb_and*/
1813 0, /*nb_xor*/
1814 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001815 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001816 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001817 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001818 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001819 0, /* nb_oct */
1820 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001821 0, /* nb_inplace_add */
1822 0, /* nb_inplace_subtract */
1823 0, /* nb_inplace_multiply */
1824 0, /* nb_inplace_divide */
1825 0, /* nb_inplace_remainder */
1826 0, /* nb_inplace_power */
1827 0, /* nb_inplace_lshift */
1828 0, /* nb_inplace_rshift */
1829 0, /* nb_inplace_and */
1830 0, /* nb_inplace_xor */
1831 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001832 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001833 float_div, /* nb_true_divide */
1834 0, /* nb_inplace_floor_divide */
1835 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001836};
1837
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001838PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001839 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001841 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 (destructor)float_dealloc, /* tp_dealloc */
1844 (printfunc)float_print, /* tp_print */
1845 0, /* tp_getattr */
1846 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001847 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 (reprfunc)float_repr, /* tp_repr */
1849 &float_as_number, /* tp_as_number */
1850 0, /* tp_as_sequence */
1851 0, /* tp_as_mapping */
1852 (hashfunc)float_hash, /* tp_hash */
1853 0, /* tp_call */
1854 (reprfunc)float_str, /* tp_str */
1855 PyObject_GenericGetAttr, /* tp_getattro */
1856 0, /* tp_setattro */
1857 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001858 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1859 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 float_doc, /* tp_doc */
1861 0, /* tp_traverse */
1862 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001863 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001864 0, /* tp_weaklistoffset */
1865 0, /* tp_iter */
1866 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001867 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001869 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870 0, /* tp_base */
1871 0, /* tp_dict */
1872 0, /* tp_descr_get */
1873 0, /* tp_descr_set */
1874 0, /* tp_dictoffset */
1875 0, /* tp_init */
1876 0, /* tp_alloc */
1877 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001879
1880void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001881_PyFloat_Init(void)
1882{
1883 /* We attempt to determine if this machine is using IEEE
1884 floating point formats by peering at the bits of some
1885 carefully chosen values. If it looks like we are on an
1886 IEEE platform, the float packing/unpacking routines can
1887 just copy bits, if not they resort to arithmetic & shifts
1888 and masks. The shifts & masks approach works on all finite
1889 values, but what happens to infinities, NaNs and signed
1890 zeroes on packing is an accident, and attempting to unpack
1891 a NaN or an infinity will raise an exception.
1892
1893 Note that if we're on some whacked-out platform which uses
1894 IEEE formats but isn't strictly little-endian or big-
1895 endian, we will fall back to the portable shifts & masks
1896 method. */
1897
1898#if SIZEOF_DOUBLE == 8
1899 {
1900 double x = 9006104071832581.0;
1901 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1902 detected_double_format = ieee_big_endian_format;
1903 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1904 detected_double_format = ieee_little_endian_format;
1905 else
1906 detected_double_format = unknown_format;
1907 }
1908#else
1909 detected_double_format = unknown_format;
1910#endif
1911
1912#if SIZEOF_FLOAT == 4
1913 {
1914 float y = 16711938.0;
1915 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1916 detected_float_format = ieee_big_endian_format;
1917 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1918 detected_float_format = ieee_little_endian_format;
1919 else
1920 detected_float_format = unknown_format;
1921 }
1922#else
1923 detected_float_format = unknown_format;
1924#endif
1925
1926 double_format = detected_double_format;
1927 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001928
Christian Heimes796fc312008-01-30 18:58:29 +00001929 /* Init float info */
1930 if (FloatInfoType.tp_name == 0)
1931 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001932}
1933
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001934int
1935PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001936{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001937 PyFloatObject *p;
1938 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001939 int i;
1940 int u; /* remaining unfreed ints per block */
1941 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001942
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001943 list = block_list;
1944 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001945 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001946 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001947 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001948 for (i = 0, p = &list->objects[0];
1949 i < N_FLOATOBJECTS;
1950 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001951 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001952 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001953 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001954 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001955 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001956 list->next = block_list;
1957 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001958 for (i = 0, p = &list->objects[0];
1959 i < N_FLOATOBJECTS;
1960 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001961 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001962 Py_REFCNT(p) == 0) {
1963 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001964 free_list;
1965 free_list = p;
1966 }
1967 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001968 }
1969 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001970 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001971 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001972 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001973 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001974 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001975 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001976}
1977
1978void
1979PyFloat_Fini(void)
1980{
1981 PyFloatObject *p;
1982 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001983 int i;
1984 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001985
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001986 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00001987
Guido van Rossum3fce8831999-03-12 19:43:17 +00001988 if (!Py_VerboseFlag)
1989 return;
1990 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001991 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001992 fprintf(stderr, "\n");
1993 }
1994 else {
1995 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001996 ": %d unfreed float%s\n",
1997 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001998 }
1999 if (Py_VerboseFlag > 1) {
2000 list = block_list;
2001 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002002 for (i = 0, p = &list->objects[0];
2003 i < N_FLOATOBJECTS;
2004 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002005 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00002006 Py_REFCNT(p) != 0) {
Eric Smithb3272582009-10-16 14:26:36 +00002007 char *buf = PyOS_double_to_string(
2008 PyFloat_AS_DOUBLE(p), 'r',
2009 0, 0, NULL);
2010 if (buf) {
2011 /* XXX(twouters) cast
2012 refcount to long
2013 until %zd is
2014 universally
2015 available
2016 */
2017 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002018 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002019 p, (long)Py_REFCNT(p), buf);
Eric Smithb3272582009-10-16 14:26:36 +00002020 PyMem_Free(buf);
2021 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002022 }
2023 }
2024 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002025 }
2026 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002027}
Tim Peters9905b942003-03-20 20:53:32 +00002028
2029/*----------------------------------------------------------------------------
2030 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002031 */
2032int
2033_PyFloat_Pack4(double x, unsigned char *p, int le)
2034{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002035 if (float_format == unknown_format) {
2036 unsigned char sign;
2037 int e;
2038 double f;
2039 unsigned int fbits;
2040 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002041
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002042 if (le) {
2043 p += 3;
2044 incr = -1;
2045 }
Tim Peters9905b942003-03-20 20:53:32 +00002046
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002047 if (x < 0) {
2048 sign = 1;
2049 x = -x;
2050 }
2051 else
2052 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002053
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002054 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002055
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002056 /* Normalize f to be in the range [1.0, 2.0) */
2057 if (0.5 <= f && f < 1.0) {
2058 f *= 2.0;
2059 e--;
2060 }
2061 else if (f == 0.0)
2062 e = 0;
2063 else {
2064 PyErr_SetString(PyExc_SystemError,
2065 "frexp() result out of range");
2066 return -1;
2067 }
2068
2069 if (e >= 128)
2070 goto Overflow;
2071 else if (e < -126) {
2072 /* Gradual underflow */
2073 f = ldexp(f, 126 + e);
2074 e = 0;
2075 }
2076 else if (!(e == 0 && f == 0.0)) {
2077 e += 127;
2078 f -= 1.0; /* Get rid of leading 1 */
2079 }
2080
2081 f *= 8388608.0; /* 2**23 */
2082 fbits = (unsigned int)(f + 0.5); /* Round */
2083 assert(fbits <= 8388608);
2084 if (fbits >> 23) {
2085 /* The carry propagated out of a string of 23 1 bits. */
2086 fbits = 0;
2087 ++e;
2088 if (e >= 255)
2089 goto Overflow;
2090 }
2091
2092 /* First byte */
2093 *p = (sign << 7) | (e >> 1);
2094 p += incr;
2095
2096 /* Second byte */
2097 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2098 p += incr;
2099
2100 /* Third byte */
2101 *p = (fbits >> 8) & 0xFF;
2102 p += incr;
2103
2104 /* Fourth byte */
2105 *p = fbits & 0xFF;
2106
2107 /* Done */
2108 return 0;
2109
Tim Peters9905b942003-03-20 20:53:32 +00002110 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002111 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002112 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113 const char *s = (char*)&y;
2114 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002115
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002116 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2117 goto Overflow;
2118
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002119 if ((float_format == ieee_little_endian_format && !le)
2120 || (float_format == ieee_big_endian_format && le)) {
2121 p += 3;
2122 incr = -1;
2123 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002124
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002125 for (i = 0; i < 4; i++) {
2126 *p = *s++;
2127 p += incr;
2128 }
2129 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002130 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002131 Overflow:
2132 PyErr_SetString(PyExc_OverflowError,
2133 "float too large to pack with f format");
2134 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002135}
2136
2137int
2138_PyFloat_Pack8(double x, unsigned char *p, int le)
2139{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002140 if (double_format == unknown_format) {
2141 unsigned char sign;
2142 int e;
2143 double f;
2144 unsigned int fhi, flo;
2145 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002146
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002147 if (le) {
2148 p += 7;
2149 incr = -1;
2150 }
Tim Peters9905b942003-03-20 20:53:32 +00002151
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002152 if (x < 0) {
2153 sign = 1;
2154 x = -x;
2155 }
2156 else
2157 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002158
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002160
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002161 /* Normalize f to be in the range [1.0, 2.0) */
2162 if (0.5 <= f && f < 1.0) {
2163 f *= 2.0;
2164 e--;
2165 }
2166 else if (f == 0.0)
2167 e = 0;
2168 else {
2169 PyErr_SetString(PyExc_SystemError,
2170 "frexp() result out of range");
2171 return -1;
2172 }
2173
2174 if (e >= 1024)
2175 goto Overflow;
2176 else if (e < -1022) {
2177 /* Gradual underflow */
2178 f = ldexp(f, 1022 + e);
2179 e = 0;
2180 }
2181 else if (!(e == 0 && f == 0.0)) {
2182 e += 1023;
2183 f -= 1.0; /* Get rid of leading 1 */
2184 }
2185
2186 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2187 f *= 268435456.0; /* 2**28 */
2188 fhi = (unsigned int)f; /* Truncate */
2189 assert(fhi < 268435456);
2190
2191 f -= (double)fhi;
2192 f *= 16777216.0; /* 2**24 */
2193 flo = (unsigned int)(f + 0.5); /* Round */
2194 assert(flo <= 16777216);
2195 if (flo >> 24) {
2196 /* The carry propagated out of a string of 24 1 bits. */
2197 flo = 0;
2198 ++fhi;
2199 if (fhi >> 28) {
2200 /* And it also progagated out of the next 28 bits. */
2201 fhi = 0;
2202 ++e;
2203 if (e >= 2047)
2204 goto Overflow;
2205 }
2206 }
2207
2208 /* First byte */
2209 *p = (sign << 7) | (e >> 4);
2210 p += incr;
2211
2212 /* Second byte */
2213 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2214 p += incr;
2215
2216 /* Third byte */
2217 *p = (fhi >> 16) & 0xFF;
2218 p += incr;
2219
2220 /* Fourth byte */
2221 *p = (fhi >> 8) & 0xFF;
2222 p += incr;
2223
2224 /* Fifth byte */
2225 *p = fhi & 0xFF;
2226 p += incr;
2227
2228 /* Sixth byte */
2229 *p = (flo >> 16) & 0xFF;
2230 p += incr;
2231
2232 /* Seventh byte */
2233 *p = (flo >> 8) & 0xFF;
2234 p += incr;
2235
2236 /* Eighth byte */
2237 *p = flo & 0xFF;
2238 p += incr;
2239
2240 /* Done */
2241 return 0;
2242
2243 Overflow:
2244 PyErr_SetString(PyExc_OverflowError,
2245 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002246 return -1;
2247 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002248 else {
2249 const char *s = (char*)&x;
2250 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002251
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252 if ((double_format == ieee_little_endian_format && !le)
2253 || (double_format == ieee_big_endian_format && le)) {
2254 p += 7;
2255 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002256 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002257
2258 for (i = 0; i < 8; i++) {
2259 *p = *s++;
2260 p += incr;
2261 }
2262 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002263 }
Tim Peters9905b942003-03-20 20:53:32 +00002264}
2265
2266double
2267_PyFloat_Unpack4(const unsigned char *p, int le)
2268{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002269 if (float_format == unknown_format) {
2270 unsigned char sign;
2271 int e;
2272 unsigned int f;
2273 double x;
2274 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002275
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002276 if (le) {
2277 p += 3;
2278 incr = -1;
2279 }
2280
2281 /* First byte */
2282 sign = (*p >> 7) & 1;
2283 e = (*p & 0x7F) << 1;
2284 p += incr;
2285
2286 /* Second byte */
2287 e |= (*p >> 7) & 1;
2288 f = (*p & 0x7F) << 16;
2289 p += incr;
2290
2291 if (e == 255) {
2292 PyErr_SetString(
2293 PyExc_ValueError,
2294 "can't unpack IEEE 754 special value "
2295 "on non-IEEE platform");
2296 return -1;
2297 }
2298
2299 /* Third byte */
2300 f |= *p << 8;
2301 p += incr;
2302
2303 /* Fourth byte */
2304 f |= *p;
2305
2306 x = (double)f / 8388608.0;
2307
2308 /* XXX This sadly ignores Inf/NaN issues */
2309 if (e == 0)
2310 e = -126;
2311 else {
2312 x += 1.0;
2313 e -= 127;
2314 }
2315 x = ldexp(x, e);
2316
2317 if (sign)
2318 x = -x;
2319
2320 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002321 }
Tim Peters9905b942003-03-20 20:53:32 +00002322 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002323 float x;
2324
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325 if ((float_format == ieee_little_endian_format && !le)
2326 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002327 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328 char *d = &buf[3];
2329 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002330
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331 for (i = 0; i < 4; i++) {
2332 *d-- = *p++;
2333 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002334 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002335 }
2336 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002337 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002339
2340 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341 }
Tim Peters9905b942003-03-20 20:53:32 +00002342}
2343
2344double
2345_PyFloat_Unpack8(const unsigned char *p, int le)
2346{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002347 if (double_format == unknown_format) {
2348 unsigned char sign;
2349 int e;
2350 unsigned int fhi, flo;
2351 double x;
2352 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002353
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354 if (le) {
2355 p += 7;
2356 incr = -1;
2357 }
2358
2359 /* First byte */
2360 sign = (*p >> 7) & 1;
2361 e = (*p & 0x7F) << 4;
2362
2363 p += incr;
2364
2365 /* Second byte */
2366 e |= (*p >> 4) & 0xF;
2367 fhi = (*p & 0xF) << 24;
2368 p += incr;
2369
2370 if (e == 2047) {
2371 PyErr_SetString(
2372 PyExc_ValueError,
2373 "can't unpack IEEE 754 special value "
2374 "on non-IEEE platform");
2375 return -1.0;
2376 }
2377
2378 /* Third byte */
2379 fhi |= *p << 16;
2380 p += incr;
2381
2382 /* Fourth byte */
2383 fhi |= *p << 8;
2384 p += incr;
2385
2386 /* Fifth byte */
2387 fhi |= *p;
2388 p += incr;
2389
2390 /* Sixth byte */
2391 flo = *p << 16;
2392 p += incr;
2393
2394 /* Seventh byte */
2395 flo |= *p << 8;
2396 p += incr;
2397
2398 /* Eighth byte */
2399 flo |= *p;
2400
2401 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2402 x /= 268435456.0; /* 2**28 */
2403
2404 if (e == 0)
2405 e = -1022;
2406 else {
2407 x += 1.0;
2408 e -= 1023;
2409 }
2410 x = ldexp(x, e);
2411
2412 if (sign)
2413 x = -x;
2414
2415 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002416 }
Tim Peters9905b942003-03-20 20:53:32 +00002417 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002418 double x;
2419
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002420 if ((double_format == ieee_little_endian_format && !le)
2421 || (double_format == ieee_big_endian_format && le)) {
2422 char buf[8];
2423 char *d = &buf[7];
2424 int i;
2425
2426 for (i = 0; i < 8; i++) {
2427 *d-- = *p++;
2428 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002429 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002430 }
2431 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002432 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002433 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002434
2435 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002436 }
Tim Peters9905b942003-03-20 20:53:32 +00002437}