blob: 6b9a310dd337e388511f94fe246161cf0e918f14 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson7103aa42008-07-15 19:08:33 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Neal Norwitz5f95a792008-01-25 08:04:16 +000022#ifdef _OSF_SOURCE
23/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24extern int finite(double);
25#endif
26
Guido van Rossum93ad0df1997-05-13 21:00:42 +000027/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000029#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000030#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000031
Guido van Rossum3fce8831999-03-12 19:43:17 +000032struct _floatblock {
33 struct _floatblock *next;
34 PyFloatObject objects[N_FLOATOBJECTS];
35};
36
37typedef struct _floatblock PyFloatBlock;
38
39static PyFloatBlock *block_list = NULL;
40static PyFloatObject *free_list = NULL;
41
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000043fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044{
45 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000049 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000050 ((PyFloatBlock *)p)->next = block_list;
51 block_list = (PyFloatBlock *)p;
52 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053 q = p + N_FLOATOBJECTS;
54 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000055 Py_TYPE(q) = (struct _typeobject *)(q-1);
56 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000057 return p + N_FLOATOBJECTS - 1;
58}
59
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060double
61PyFloat_GetMax(void)
62{
63 return DBL_MAX;
64}
65
66double
67PyFloat_GetMin(void)
68{
69 return DBL_MIN;
70}
71
Christian Heimes796fc312008-01-30 18:58:29 +000072static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000073
74PyDoc_STRVAR(floatinfo__doc__,
75"sys.floatinfo\n\
76\n\
77A structseq holding information about the float type. It contains low level\n\
78information about the precision and internal representation. Please study\n\
79your system's :file:`float.h` for more information.");
80
81static PyStructSequence_Field floatinfo_fields[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
84 "is representable"},
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
86 "is representable"},
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
91 "a normalized"},
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
98 {0}
99};
100
101static PyStructSequence_Desc floatinfo_desc = {
102 "sys.floatinfo", /* name */
103 floatinfo__doc__, /* doc */
104 floatinfo_fields, /* fields */
105 11
106};
107
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108PyObject *
109PyFloat_GetInfo(void)
110{
Christian Heimes796fc312008-01-30 18:58:29 +0000111 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000112 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114 floatinfo = PyStructSequence_New(&FloatInfoType);
115 if (floatinfo == NULL) {
116 return NULL;
117 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Christian Heimesc94e2b52008-01-14 04:13:37 +0000119#define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121#define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000123
Christian Heimesc94e2b52008-01-14 04:13:37 +0000124 SetDblFlag(DBL_MAX);
125 SetIntFlag(DBL_MAX_EXP);
126 SetIntFlag(DBL_MAX_10_EXP);
127 SetDblFlag(DBL_MIN);
128 SetIntFlag(DBL_MIN_EXP);
129 SetIntFlag(DBL_MIN_10_EXP);
130 SetIntFlag(DBL_DIG);
131 SetIntFlag(DBL_MANT_DIG);
132 SetDblFlag(DBL_EPSILON);
133 SetIntFlag(FLT_RADIX);
134 SetIntFlag(FLT_ROUNDS);
135#undef SetIntFlag
136#undef SetDblFlag
137
138 if (PyErr_Occurred()) {
139 Py_CLEAR(floatinfo);
140 return NULL;
141 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000142 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
152 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000153 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000155 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Tim Petersef14d732000-09-23 03:39:17 +0000161/**************************************************************************
162RED_FLAG 22-Sep-2000 tim
163PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
164
1651. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
168
1692. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
172
173Since we can't change the interface of a public API function, pend is
174still supported but now *officially* useless: if pend is not NULL,
175*pend is set to NULL.
176**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000178PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179{
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000180 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000182 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000184 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000185#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187
Tim Petersef14d732000-09-23 03:39:17 +0000188 if (pend)
189 *pend = NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000190 if (PyString_Check(v)) {
191 s = PyString_AS_STRING(v);
192 len = PyString_GET_SIZE(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000194#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000195 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000196 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000198 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 return NULL;
200 }
Tim Petersef14d732000-09-23 03:39:17 +0000201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000203 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 NULL))
205 return NULL;
206 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000207 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000208 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000210 else if (PyObject_AsCharBuffer(v, &s, &len)) {
211 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000212 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000215 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000216
Mark Dickinson777e4ff2009-05-03 20:59:48 +0000217 while (Py_ISSPACE(*s))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 s++;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000219 /* We don't care about overflow or underflow. If the platform
220 * supports them, infinities and signed zeroes (on underflow) are
221 * fine. */
222 errno = 0;
Tim Peters858346e2000-09-25 21:01:28 +0000223 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000224 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000225 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000226 if (end == s) {
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000227 if (errno == ENOMEM)
228 PyErr_NoMemory();
229 else {
230 PyOS_snprintf(buffer, sizeof(buffer),
231 "invalid literal for float(): %.200s", s);
232 PyErr_SetString(PyExc_ValueError, buffer);
Christian Heimes0a8143f2007-12-18 23:22:54 +0000233 }
Tim Petersef14d732000-09-23 03:39:17 +0000234 return NULL;
235 }
236 /* Since end != s, the platform made *some* kind of sense out
237 of the input. Trust it. */
Mark Dickinson777e4ff2009-05-03 20:59:48 +0000238 while (Py_ISSPACE(*end))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000239 end++;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000240 if (end != last) {
241 if (*end == '\0')
242 PyErr_SetString(PyExc_ValueError,
243 "null byte in argument for float()");
244 else {
245 PyOS_snprintf(buffer, sizeof(buffer),
246 "invalid literal for float(): %.200s", s);
247 PyErr_SetString(PyExc_ValueError, buffer);
248 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 return NULL;
250 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000251 return PyFloat_FromDouble(x);
252}
253
Guido van Rossum234f9421993-06-17 12:35:49 +0000254static void
Fred Drakefd99de62000-07-09 05:02:18 +0000255float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000256{
Guido van Rossum9475a232001-10-05 20:51:39 +0000257 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000258 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000259 free_list = op;
260 }
261 else
Christian Heimese93237d2007-12-19 02:37:44 +0000262 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000263}
264
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000265double
Fred Drakefd99de62000-07-09 05:02:18 +0000266PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268 PyNumberMethods *nb;
269 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000271
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 if (op && PyFloat_Check(op))
273 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000274
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000275 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277 return -1;
278 }
Tim Petersd2364e82001-11-01 20:09:42 +0000279
Christian Heimese93237d2007-12-19 02:37:44 +0000280 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000281 PyErr_SetString(PyExc_TypeError, "a float is required");
282 return -1;
283 }
284
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286 if (fo == NULL)
287 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000288 if (!PyFloat_Check(fo)) {
289 PyErr_SetString(PyExc_TypeError,
290 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000291 return -1;
292 }
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 val = PyFloat_AS_DOUBLE(fo);
295 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000296
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298}
299
300/* Methods */
301
Tim Peters97019e42001-11-28 22:43:45 +0000302/* XXX PyFloat_AsStringEx should not be a public API function (for one
303 XXX thing, its signature passes a buffer without a length; for another,
304 XXX it isn't useful outside this file).
305*/
306void
307PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
308{
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000309 _PyOS_double_to_string(buf, 100, v->ob_fval, 'g', precision,
310 Py_DTSF_ADD_DOT_0, NULL);
Tim Peters97019e42001-11-28 22:43:45 +0000311}
312
Neil Schemenauer32117e52001-01-04 01:44:34 +0000313/* Macro and helper that convert PyObject obj to a C double and store
314 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000315 slot function. If conversion to double raises an exception, obj is
316 set to NULL, and the function invoking this macro returns NULL. If
317 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
318 stored in obj, and returned from the function invoking this macro.
319*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000320#define CONVERT_TO_DOUBLE(obj, dbl) \
321 if (PyFloat_Check(obj)) \
322 dbl = PyFloat_AS_DOUBLE(obj); \
323 else if (convert_to_double(&(obj), &(dbl)) < 0) \
324 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000325
326static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000327convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000328{
329 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000330
Neil Schemenauer32117e52001-01-04 01:44:34 +0000331 if (PyInt_Check(obj)) {
332 *dbl = (double)PyInt_AS_LONG(obj);
333 }
334 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000335 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000336 if (*dbl == -1.0 && PyErr_Occurred()) {
337 *v = NULL;
338 return -1;
339 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000340 }
341 else {
342 Py_INCREF(Py_NotImplemented);
343 *v = Py_NotImplemented;
344 return -1;
345 }
346 return 0;
347}
348
Tim Peters97019e42001-11-28 22:43:45 +0000349/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
350 XXX they pass a char buffer without passing a length.
351*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000352void
Fred Drakefd99de62000-07-09 05:02:18 +0000353PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000354{
Eric Smitha985a3a2009-05-05 18:26:08 +0000355 _PyOS_double_to_string(buf, 100, v->ob_fval, 'g', PyFloat_STR_PRECISION,
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000356 Py_DTSF_ADD_DOT_0, NULL);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000357}
358
Tim Peters72f98e92001-05-08 15:19:57 +0000359void
360PyFloat_AsReprString(char *buf, PyFloatObject *v)
361{
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000362 _PyOS_double_to_string(buf, 100, v->ob_fval, 'r', 0,
363 Py_DTSF_ADD_DOT_0, NULL);
Tim Peters72f98e92001-05-08 15:19:57 +0000364}
365
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000366/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000367static int
Fred Drakefd99de62000-07-09 05:02:18 +0000368float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
370 char buf[100];
Eric Smitha985a3a2009-05-05 18:26:08 +0000371 if (flags & Py_PRINT_RAW)
372 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval,
373 'g', PyFloat_STR_PRECISION,
374 Py_DTSF_ADD_DOT_0, NULL);
375 else
376 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval,
377 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
Brett Cannon01531592007-09-17 03:28:34 +0000378 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000380 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000381 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382}
383
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000384static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000385float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000386{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000387 char buf[100];
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000388 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval, 'r', 0,
389 Py_DTSF_ADD_DOT_0, NULL);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000390 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000391}
392
393static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000394float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000395{
396 char buf[100];
Eric Smitha985a3a2009-05-05 18:26:08 +0000397 _PyOS_double_to_string(buf, sizeof(buf), v->ob_fval, 'g',
398 PyFloat_STR_PRECISION,
Mark Dickinsondf108ca2009-04-29 21:56:53 +0000399 Py_DTSF_ADD_DOT_0, NULL);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000400 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401}
402
Tim Peters307fa782004-09-23 08:06:40 +0000403/* Comparison is pretty much a nightmare. When comparing float to float,
404 * we do it as straightforwardly (and long-windedly) as conceivable, so
405 * that, e.g., Python x == y delivers the same result as the platform
406 * C x == y when x and/or y is a NaN.
407 * When mixing float with an integer type, there's no good *uniform* approach.
408 * Converting the double to an integer obviously doesn't work, since we
409 * may lose info from fractional bits. Converting the integer to a double
410 * also has two failure modes: (1) a long int may trigger overflow (too
411 * large to fit in the dynamic range of a C double); (2) even a C long may have
412 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
413 * 63 bits of precision, but a C double probably has only 53), and then
414 * we can falsely claim equality when low-order integer bits are lost by
415 * coercion to double. So this part is painful too.
416 */
417
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000418static PyObject*
419float_richcompare(PyObject *v, PyObject *w, int op)
420{
421 double i, j;
422 int r = 0;
423
Tim Peters307fa782004-09-23 08:06:40 +0000424 assert(PyFloat_Check(v));
425 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000426
Tim Peters307fa782004-09-23 08:06:40 +0000427 /* Switch on the type of w. Set i and j to doubles to be compared,
428 * and op to the richcomp to use.
429 */
430 if (PyFloat_Check(w))
431 j = PyFloat_AS_DOUBLE(w);
432
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000433 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000434 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000435 /* If i is an infinity, its magnitude exceeds any
436 * finite integer, so it doesn't matter which int we
437 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000438 */
439 j = 0.0;
440 else
441 goto Unimplemented;
442 }
443
444 else if (PyInt_Check(w)) {
445 long jj = PyInt_AS_LONG(w);
446 /* In the worst realistic case I can imagine, C double is a
447 * Cray single with 48 bits of precision, and long has 64
448 * bits.
449 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000450#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000451 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
452 if (abs >> 48) {
453 /* Needs more than 48 bits. Make it take the
454 * PyLong path.
455 */
456 PyObject *result;
457 PyObject *ww = PyLong_FromLong(jj);
458
459 if (ww == NULL)
460 return NULL;
461 result = float_richcompare(v, ww, op);
462 Py_DECREF(ww);
463 return result;
464 }
465#endif
466 j = (double)jj;
467 assert((long)j == jj);
468 }
469
470 else if (PyLong_Check(w)) {
471 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
472 int wsign = _PyLong_Sign(w);
473 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000474 int exponent;
475
476 if (vsign != wsign) {
477 /* Magnitudes are irrelevant -- the signs alone
478 * determine the outcome.
479 */
480 i = (double)vsign;
481 j = (double)wsign;
482 goto Compare;
483 }
484 /* The signs are the same. */
485 /* Convert w to a double if it fits. In particular, 0 fits. */
486 nbits = _PyLong_NumBits(w);
487 if (nbits == (size_t)-1 && PyErr_Occurred()) {
488 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000489 * to hold the # of bits. Replace with little doubles
490 * that give the same outcome -- w is so large that
491 * its magnitude must exceed the magnitude of any
492 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000493 */
494 PyErr_Clear();
495 i = (double)vsign;
496 assert(wsign != 0);
497 j = wsign * 2.0;
498 goto Compare;
499 }
500 if (nbits <= 48) {
501 j = PyLong_AsDouble(w);
502 /* It's impossible that <= 48 bits overflowed. */
503 assert(j != -1.0 || ! PyErr_Occurred());
504 goto Compare;
505 }
506 assert(wsign != 0); /* else nbits was 0 */
507 assert(vsign != 0); /* if vsign were 0, then since wsign is
508 * not 0, we would have taken the
509 * vsign != wsign branch at the start */
510 /* We want to work with non-negative numbers. */
511 if (vsign < 0) {
512 /* "Multiply both sides" by -1; this also swaps the
513 * comparator.
514 */
515 i = -i;
516 op = _Py_SwappedOp[op];
517 }
518 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000519 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000520 /* exponent is the # of bits in v before the radix point;
521 * we know that nbits (the # of bits in w) > 48 at this point
522 */
523 if (exponent < 0 || (size_t)exponent < nbits) {
524 i = 1.0;
525 j = 2.0;
526 goto Compare;
527 }
528 if ((size_t)exponent > nbits) {
529 i = 2.0;
530 j = 1.0;
531 goto Compare;
532 }
533 /* v and w have the same number of bits before the radix
534 * point. Construct two longs that have the same comparison
535 * outcome.
536 */
537 {
538 double fracpart;
539 double intpart;
540 PyObject *result = NULL;
541 PyObject *one = NULL;
542 PyObject *vv = NULL;
543 PyObject *ww = w;
544
545 if (wsign < 0) {
546 ww = PyNumber_Negative(w);
547 if (ww == NULL)
548 goto Error;
549 }
550 else
551 Py_INCREF(ww);
552
553 fracpart = modf(i, &intpart);
554 vv = PyLong_FromDouble(intpart);
555 if (vv == NULL)
556 goto Error;
557
558 if (fracpart != 0.0) {
559 /* Shift left, and or a 1 bit into vv
560 * to represent the lost fraction.
561 */
562 PyObject *temp;
563
564 one = PyInt_FromLong(1);
565 if (one == NULL)
566 goto Error;
567
568 temp = PyNumber_Lshift(ww, one);
569 if (temp == NULL)
570 goto Error;
571 Py_DECREF(ww);
572 ww = temp;
573
574 temp = PyNumber_Lshift(vv, one);
575 if (temp == NULL)
576 goto Error;
577 Py_DECREF(vv);
578 vv = temp;
579
580 temp = PyNumber_Or(vv, one);
581 if (temp == NULL)
582 goto Error;
583 Py_DECREF(vv);
584 vv = temp;
585 }
586
587 r = PyObject_RichCompareBool(vv, ww, op);
588 if (r < 0)
589 goto Error;
590 result = PyBool_FromLong(r);
591 Error:
592 Py_XDECREF(vv);
593 Py_XDECREF(ww);
594 Py_XDECREF(one);
595 return result;
596 }
597 } /* else if (PyLong_Check(w)) */
598
599 else /* w isn't float, int, or long */
600 goto Unimplemented;
601
602 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000603 PyFPE_START_PROTECT("richcompare", return NULL)
604 switch (op) {
605 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000606 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000607 break;
608 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000609 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000610 break;
611 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000612 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000613 break;
614 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000615 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000616 break;
617 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000618 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000619 break;
620 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000621 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000622 break;
623 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000624 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000625 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000626
627 Unimplemented:
628 Py_INCREF(Py_NotImplemented);
629 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000630}
631
Guido van Rossum9bfef441993-03-29 10:43:31 +0000632static long
Fred Drakefd99de62000-07-09 05:02:18 +0000633float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000634{
Tim Peters39dce292000-08-15 03:34:48 +0000635 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000636}
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000639float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000641 double a,b;
642 CONVERT_TO_DOUBLE(v, a);
643 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000644 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000645 a = a + b;
646 PyFPE_END_PROTECT(a)
647 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000648}
649
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000651float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000652{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000653 double a,b;
654 CONVERT_TO_DOUBLE(v, a);
655 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000656 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000657 a = a - b;
658 PyFPE_END_PROTECT(a)
659 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660}
661
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000663float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000665 double a,b;
666 CONVERT_TO_DOUBLE(v, a);
667 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000668 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000669 a = a * b;
670 PyFPE_END_PROTECT(a)
671 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672}
673
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000675float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677 double a,b;
678 CONVERT_TO_DOUBLE(v, a);
679 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000680#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000681 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000682 PyErr_SetString(PyExc_ZeroDivisionError,
683 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000684 return NULL;
685 }
Christian Heimes6f341092008-04-18 23:13:07 +0000686#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000687 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000688 a = a / b;
689 PyFPE_END_PROTECT(a)
690 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000691}
692
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000693static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000694float_classic_div(PyObject *v, PyObject *w)
695{
696 double a,b;
697 CONVERT_TO_DOUBLE(v, a);
698 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000699 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000700 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
701 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000702#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000703 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000704 PyErr_SetString(PyExc_ZeroDivisionError,
705 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000706 return NULL;
707 }
Christian Heimes6f341092008-04-18 23:13:07 +0000708#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000709 PyFPE_START_PROTECT("divide", return 0)
710 a = a / b;
711 PyFPE_END_PROTECT(a)
712 return PyFloat_FromDouble(a);
713}
714
715static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000716float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000717{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000718 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000719 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000720 CONVERT_TO_DOUBLE(v, vx);
721 CONVERT_TO_DOUBLE(w, wx);
722#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000724 PyErr_SetString(PyExc_ZeroDivisionError,
725 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726 return NULL;
727 }
Christian Heimes6f341092008-04-18 23:13:07 +0000728#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000729 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000730 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000731 /* note: checking mod*wx < 0 is incorrect -- underflows to
732 0 if wx < sqrt(smallest nonzero double) */
733 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000734 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000735 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000736 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000738}
739
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000741float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000742{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000743 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000744 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000745 CONVERT_TO_DOUBLE(v, vx);
746 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000747 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000749 return NULL;
750 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000751 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000752 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000753 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000754 exact multiple of wx. But this is fp arithmetic, and fp
755 vx - mod is an approximation; the result is that div may
756 not be an exact integral value after the division, although
757 it will always be very close to one.
758 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000759 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000760 if (mod) {
761 /* ensure the remainder has the same sign as the denominator */
762 if ((wx < 0) != (mod < 0)) {
763 mod += wx;
764 div -= 1.0;
765 }
766 }
767 else {
768 /* the remainder is zero, and in the presence of signed zeroes
769 fmod returns different results across platforms; ensure
770 it has the same sign as the denominator; we'd like to do
771 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000772 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000773 if (wx < 0.0)
774 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000775 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000776 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000777 if (div) {
778 floordiv = floor(div);
779 if (div - floordiv > 0.5)
780 floordiv += 1.0;
781 }
782 else {
783 /* div is zero - get the same sign as the true quotient */
784 div *= div; /* hide "div = +0" from optimizers */
785 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
786 }
787 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000788 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000789}
790
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000791static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000792float_floor_div(PyObject *v, PyObject *w)
793{
794 PyObject *t, *r;
795
796 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000797 if (t == NULL || t == Py_NotImplemented)
798 return t;
799 assert(PyTuple_CheckExact(t));
800 r = PyTuple_GET_ITEM(t, 0);
801 Py_INCREF(r);
802 Py_DECREF(t);
803 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000804}
805
806static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000807float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808{
809 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000810
811 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000812 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000813 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000814 return NULL;
815 }
816
Neil Schemenauer32117e52001-01-04 01:44:34 +0000817 CONVERT_TO_DOUBLE(v, iv);
818 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000819
820 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000821 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000822 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000823 }
Tim Peters96685bf2001-08-23 22:31:37 +0000824 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000825 if (iw < 0.0) {
826 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000827 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000828 return NULL;
829 }
830 return PyFloat_FromDouble(0.0);
831 }
Christian Heimes6f341092008-04-18 23:13:07 +0000832 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
833 return PyFloat_FromDouble(1.0);
834 }
Tim Peterse87568d2003-05-24 20:18:24 +0000835 if (iv < 0.0) {
836 /* Whether this is an error is a mess, and bumps into libm
837 * bugs so we have to figure it out ourselves.
838 */
839 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000840 PyErr_SetString(PyExc_ValueError, "negative number "
841 "cannot be raised to a fractional power");
842 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000843 }
844 /* iw is an exact integer, albeit perhaps a very large one.
845 * -1 raised to an exact integer should never be exceptional.
846 * Alas, some libms (chiefly glibc as of early 2003) return
847 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
848 * happen to be representable in a *C* integer. That's a
849 * bug; we let that slide in math.pow() (which currently
850 * reflects all platform accidents), but not for Python's **.
851 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000852 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000853 /* Return 1 if iw is even, -1 if iw is odd; there's
854 * no guarantee that any C integral type is big
855 * enough to hold iw, so we have to check this
856 * indirectly.
857 */
858 ix = floor(iw * 0.5) * 2.0;
859 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
860 }
861 /* Else iv != -1.0, and overflow or underflow are possible.
862 * Unless we're to write pow() ourselves, we have to trust
863 * the platform to do this correctly.
864 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000865 }
Tim Peters96685bf2001-08-23 22:31:37 +0000866 errno = 0;
867 PyFPE_START_PROTECT("pow", return NULL)
868 ix = pow(iv, iw);
869 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000870 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000871 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000872 /* We don't expect any errno value other than ERANGE, but
873 * the range of libm bugs appears unbounded.
874 */
Alex Martelli348dc882006-08-23 22:17:59 +0000875 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
876 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000878 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880}
881
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000882static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000883float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000886}
887
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000888static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000889float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000890{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000891 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000892}
893
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000894static int
Fred Drakefd99de62000-07-09 05:02:18 +0000895float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000896{
897 return v->ob_fval != 0.0;
898}
899
Guido van Rossum234f9421993-06-17 12:35:49 +0000900static int
Fred Drakefd99de62000-07-09 05:02:18 +0000901float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000902{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000903 if (PyInt_Check(*pw)) {
904 long x = PyInt_AsLong(*pw);
905 *pw = PyFloat_FromDouble((double)x);
906 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000907 return 0;
908 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000909 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000910 double x = PyLong_AsDouble(*pw);
911 if (x == -1.0 && PyErr_Occurred())
912 return -1;
913 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000914 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000915 return 0;
916 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000917 else if (PyFloat_Check(*pw)) {
918 Py_INCREF(*pv);
919 Py_INCREF(*pw);
920 return 0;
921 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000922 return 1; /* Can't do it */
923}
924
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000926float_is_integer(PyObject *v)
927{
928 double x = PyFloat_AsDouble(v);
929 PyObject *o;
930
931 if (x == -1.0 && PyErr_Occurred())
932 return NULL;
933 if (!Py_IS_FINITE(x))
934 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +0000935 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000936 PyFPE_START_PROTECT("is_integer", return NULL)
937 o = (floor(x) == x) ? Py_True : Py_False;
938 PyFPE_END_PROTECT(x)
939 if (errno != 0) {
940 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
941 PyExc_ValueError);
942 return NULL;
943 }
944 Py_INCREF(o);
945 return o;
946}
947
948#if 0
949static PyObject *
950float_is_inf(PyObject *v)
951{
952 double x = PyFloat_AsDouble(v);
953 if (x == -1.0 && PyErr_Occurred())
954 return NULL;
955 return PyBool_FromLong((long)Py_IS_INFINITY(x));
956}
957
958static PyObject *
959float_is_nan(PyObject *v)
960{
961 double x = PyFloat_AsDouble(v);
962 if (x == -1.0 && PyErr_Occurred())
963 return NULL;
964 return PyBool_FromLong((long)Py_IS_NAN(x));
965}
966
967static PyObject *
968float_is_finite(PyObject *v)
969{
970 double x = PyFloat_AsDouble(v);
971 if (x == -1.0 && PyErr_Occurred())
972 return NULL;
973 return PyBool_FromLong((long)Py_IS_FINITE(x));
974}
975#endif
976
977static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000978float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000979{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000980 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000981 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000982
983 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000984 /* Try to get out cheap if this fits in a Python int. The attempt
985 * to cast to long must be protected, as C doesn't define what
986 * happens if the double is too big to fit in a long. Some rare
987 * systems raise an exception then (RISCOS was mentioned as one,
988 * and someone using a non-default option on Sun also bumped into
989 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
990 * still be vulnerable: if a long has more bits of precision than
991 * a double, casting MIN/MAX to double may yield an approximation,
992 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
993 * yield true from the C expression wholepart<=LONG_MAX, despite
994 * that wholepart is actually greater than LONG_MAX.
995 */
996 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
997 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000998 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000999 }
1000 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001001}
1002
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001003static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001004float_long(PyObject *v)
1005{
1006 double x = PyFloat_AsDouble(v);
1007 return PyLong_FromDouble(x);
1008}
1009
1010static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001011float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001012{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001013 if (PyFloat_CheckExact(v))
1014 Py_INCREF(v);
1015 else
1016 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001017 return v;
1018}
1019
Mark Dickinson7103aa42008-07-15 19:08:33 +00001020/* turn ASCII hex characters into integer values and vice versa */
1021
1022static char
1023char_from_hex(int x)
1024{
1025 assert(0 <= x && x < 16);
1026 return "0123456789abcdef"[x];
1027}
1028
1029static int
1030hex_from_char(char c) {
1031 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001032 switch(c) {
1033 case '0':
1034 x = 0;
1035 break;
1036 case '1':
1037 x = 1;
1038 break;
1039 case '2':
1040 x = 2;
1041 break;
1042 case '3':
1043 x = 3;
1044 break;
1045 case '4':
1046 x = 4;
1047 break;
1048 case '5':
1049 x = 5;
1050 break;
1051 case '6':
1052 x = 6;
1053 break;
1054 case '7':
1055 x = 7;
1056 break;
1057 case '8':
1058 x = 8;
1059 break;
1060 case '9':
1061 x = 9;
1062 break;
1063 case 'a':
1064 case 'A':
1065 x = 10;
1066 break;
1067 case 'b':
1068 case 'B':
1069 x = 11;
1070 break;
1071 case 'c':
1072 case 'C':
1073 x = 12;
1074 break;
1075 case 'd':
1076 case 'D':
1077 x = 13;
1078 break;
1079 case 'e':
1080 case 'E':
1081 x = 14;
1082 break;
1083 case 'f':
1084 case 'F':
1085 x = 15;
1086 break;
1087 default:
1088 x = -1;
1089 break;
1090 }
1091 return x;
1092}
1093
1094/* convert a float to a hexadecimal string */
1095
1096/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1097 of the form 4k+1. */
1098#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1099
1100static PyObject *
1101float_hex(PyObject *v)
1102{
1103 double x, m;
1104 int e, shift, i, si, esign;
1105 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1106 trailing NUL byte. */
1107 char s[(TOHEX_NBITS-1)/4+3];
1108
1109 CONVERT_TO_DOUBLE(v, x);
1110
1111 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1112 return float_str((PyFloatObject *)v);
1113
1114 if (x == 0.0) {
1115 if(copysign(1.0, x) == -1.0)
1116 return PyString_FromString("-0x0.0p+0");
1117 else
1118 return PyString_FromString("0x0.0p+0");
1119 }
1120
1121 m = frexp(fabs(x), &e);
1122 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1123 m = ldexp(m, shift);
1124 e -= shift;
1125
1126 si = 0;
1127 s[si] = char_from_hex((int)m);
1128 si++;
1129 m -= (int)m;
1130 s[si] = '.';
1131 si++;
1132 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1133 m *= 16.0;
1134 s[si] = char_from_hex((int)m);
1135 si++;
1136 m -= (int)m;
1137 }
1138 s[si] = '\0';
1139
1140 if (e < 0) {
1141 esign = (int)'-';
1142 e = -e;
1143 }
1144 else
1145 esign = (int)'+';
1146
1147 if (x < 0.0)
1148 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1149 else
1150 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1151}
1152
1153PyDoc_STRVAR(float_hex_doc,
1154"float.hex() -> string\n\
1155\n\
1156Return a hexadecimal representation of a floating-point number.\n\
1157>>> (-0.1).hex()\n\
1158'-0x1.999999999999ap-4'\n\
1159>>> 3.14159.hex()\n\
1160'0x1.921f9f01b866ep+1'");
1161
1162/* Convert a hexadecimal string to a float. */
1163
1164static PyObject *
1165float_fromhex(PyObject *cls, PyObject *arg)
1166{
1167 PyObject *result_as_float, *result;
1168 double x;
1169 long exp, top_exp, lsb, key_digit;
1170 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1171 int half_eps, digit, round_up, sign=1;
1172 Py_ssize_t length, ndigits, fdigits, i;
1173
1174 /*
1175 * For the sake of simplicity and correctness, we impose an artificial
1176 * limit on ndigits, the total number of hex digits in the coefficient
1177 * The limit is chosen to ensure that, writing exp for the exponent,
1178 *
1179 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1180 * guaranteed to overflow (provided it's nonzero)
1181 *
1182 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1183 * guaranteed to underflow to 0.
1184 *
1185 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1186 * overflow in the calculation of exp and top_exp below.
1187 *
1188 * More specifically, ndigits is assumed to satisfy the following
1189 * inequalities:
1190 *
1191 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1192 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1193 *
1194 * If either of these inequalities is not satisfied, a ValueError is
1195 * raised. Otherwise, write x for the value of the hex string, and
1196 * assume x is nonzero. Then
1197 *
1198 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1199 *
1200 * Now if exp > LONG_MAX/2 then:
1201 *
1202 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1203 * = DBL_MAX_EXP
1204 *
1205 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1206 * double, so overflows. If exp < LONG_MIN/2, then
1207 *
1208 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1209 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1210 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1211 *
1212 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1213 * when converted to a C double.
1214 *
1215 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1216 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1217 */
1218
1219 if (PyString_AsStringAndSize(arg, &s, &length))
1220 return NULL;
1221 s_end = s + length;
1222
1223 /********************
1224 * Parse the string *
1225 ********************/
1226
1227 /* leading whitespace and optional sign */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001228 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001229 s++;
1230 if (*s == '-') {
1231 s++;
1232 sign = -1;
1233 }
1234 else if (*s == '+')
1235 s++;
1236
1237 /* infinities and nans */
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001238 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001239 x = Py_NAN;
1240 goto finished;
1241 }
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001242 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1243 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001244 x = sign*Py_HUGE_VAL;
1245 goto finished;
1246 }
1247
1248 /* [0x] */
1249 s_store = s;
1250 if (*s == '0') {
1251 s++;
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001252 if (*s == 'x' || *s == 'X')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001253 s++;
1254 else
1255 s = s_store;
1256 }
1257
1258 /* coefficient: <integer> [. <fraction>] */
1259 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001260 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001261 s++;
1262 s_store = s;
1263 if (*s == '.') {
1264 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001265 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001266 s++;
1267 coeff_end = s-1;
1268 }
1269 else
1270 coeff_end = s;
1271
1272 /* ndigits = total # of hex digits; fdigits = # after point */
1273 ndigits = coeff_end - coeff_start;
1274 fdigits = coeff_end - s_store;
1275 if (ndigits == 0)
1276 goto parse_error;
1277 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1278 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1279 goto insane_length_error;
1280
1281 /* [p <exponent>] */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001282 if (*s == 'p' || *s == 'P') {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001283 s++;
1284 exp_start = s;
1285 if (*s == '-' || *s == '+')
1286 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001287 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001288 goto parse_error;
1289 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001290 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001291 s++;
1292 exp = strtol(exp_start, NULL, 10);
1293 }
1294 else
1295 exp = 0;
1296
1297 /* optional trailing whitespace leading to the end of the string */
Mark Dickinson777e4ff2009-05-03 20:59:48 +00001298 while (Py_ISSPACE(*s))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001299 s++;
1300 if (s != s_end)
1301 goto parse_error;
1302
1303/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1304#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1305 coeff_end-(j) : \
1306 coeff_end-1-(j)))
1307
1308 /*******************************************
1309 * Compute rounded value of the hex string *
1310 *******************************************/
1311
1312 /* Discard leading zeros, and catch extreme overflow and underflow */
1313 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1314 ndigits--;
1315 if (ndigits == 0 || exp < LONG_MIN/2) {
1316 x = sign * 0.0;
1317 goto finished;
1318 }
1319 if (exp > LONG_MAX/2)
1320 goto overflow_error;
1321
1322 /* Adjust exponent for fractional part. */
1323 exp = exp - 4*((long)fdigits);
1324
1325 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1326 top_exp = exp + 4*((long)ndigits - 1);
1327 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1328 top_exp++;
1329
1330 /* catch almost all nonextreme cases of overflow and underflow here */
1331 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1332 x = sign * 0.0;
1333 goto finished;
1334 }
1335 if (top_exp > DBL_MAX_EXP)
1336 goto overflow_error;
1337
1338 /* lsb = exponent of least significant bit of the *rounded* value.
1339 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1340 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1341
1342 x = 0.0;
1343 if (exp >= lsb) {
1344 /* no rounding required */
1345 for (i = ndigits-1; i >= 0; i--)
1346 x = 16.0*x + HEX_DIGIT(i);
1347 x = sign * ldexp(x, (int)(exp));
1348 goto finished;
1349 }
1350 /* rounding required. key_digit is the index of the hex digit
1351 containing the first bit to be rounded away. */
1352 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1353 key_digit = (lsb - exp - 1) / 4;
1354 for (i = ndigits-1; i > key_digit; i--)
1355 x = 16.0*x + HEX_DIGIT(i);
1356 digit = HEX_DIGIT(key_digit);
1357 x = 16.0*x + (double)(digit & (16-2*half_eps));
1358
1359 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1360 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1361 if ((digit & half_eps) != 0) {
1362 round_up = 0;
1363 if ((digit & (3*half_eps-1)) != 0 ||
1364 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1365 round_up = 1;
1366 else
1367 for (i = key_digit-1; i >= 0; i--)
1368 if (HEX_DIGIT(i) != 0) {
1369 round_up = 1;
1370 break;
1371 }
1372 if (round_up == 1) {
1373 x += 2*half_eps;
1374 if (top_exp == DBL_MAX_EXP &&
1375 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1376 /* overflow corner case: pre-rounded value <
1377 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1378 goto overflow_error;
1379 }
1380 }
1381 x = sign * ldexp(x, (int)(exp+4*key_digit));
1382
1383 finished:
1384 result_as_float = Py_BuildValue("(d)", x);
1385 if (result_as_float == NULL)
1386 return NULL;
1387 result = PyObject_CallObject(cls, result_as_float);
1388 Py_DECREF(result_as_float);
1389 return result;
1390
1391 overflow_error:
1392 PyErr_SetString(PyExc_OverflowError,
1393 "hexadecimal value too large to represent as a float");
1394 return NULL;
1395
1396 parse_error:
1397 PyErr_SetString(PyExc_ValueError,
1398 "invalid hexadecimal floating-point string");
1399 return NULL;
1400
1401 insane_length_error:
1402 PyErr_SetString(PyExc_ValueError,
1403 "hexadecimal string too long to convert");
1404 return NULL;
1405}
1406
1407PyDoc_STRVAR(float_fromhex_doc,
1408"float.fromhex(string) -> float\n\
1409\n\
1410Create a floating-point number from a hexadecimal string.\n\
1411>>> float.fromhex('0x1.ffffp10')\n\
14122047.984375\n\
1413>>> float.fromhex('-0x1p-1074')\n\
1414-4.9406564584124654e-324");
1415
1416
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001417static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001418float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001419{
1420 double self;
1421 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001422 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001423 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001424
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001425 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001426 PyObject *py_exponent = NULL;
1427 PyObject *numerator = NULL;
1428 PyObject *denominator = NULL;
1429 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001430 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001431
1432#define INPLACE_UPDATE(obj, call) \
1433 prev = obj; \
1434 obj = call; \
1435 Py_DECREF(prev); \
1436
1437 CONVERT_TO_DOUBLE(v, self);
1438
1439 if (Py_IS_INFINITY(self)) {
1440 PyErr_SetString(PyExc_OverflowError,
1441 "Cannot pass infinity to float.as_integer_ratio.");
1442 return NULL;
1443 }
1444#ifdef Py_NAN
1445 if (Py_IS_NAN(self)) {
1446 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001447 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001448 return NULL;
1449 }
1450#endif
1451
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001452 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001453 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001454 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001455
Raymond Hettingerf9859032008-02-01 23:45:44 +00001456 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001457 float_part *= 2.0;
1458 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001459 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001460 /* self == float_part * 2**exponent exactly and float_part is integral.
1461 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1462 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001463
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001464 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001465 if (numerator == NULL) goto error;
1466
Raymond Hettingerf9859032008-02-01 23:45:44 +00001467 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001468 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001469 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001470 if (py_exponent == NULL) goto error;
1471 INPLACE_UPDATE(py_exponent,
1472 long_methods->nb_lshift(denominator, py_exponent));
1473 if (py_exponent == NULL) goto error;
1474 if (exponent > 0) {
1475 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001476 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001477 if (numerator == NULL) goto error;
1478 }
1479 else {
1480 Py_DECREF(denominator);
1481 denominator = py_exponent;
1482 py_exponent = NULL;
1483 }
1484
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001485 /* Returns ints instead of longs where possible */
1486 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1487 if (numerator == NULL) goto error;
1488 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1489 if (denominator == NULL) goto error;
1490
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001491 result_pair = PyTuple_Pack(2, numerator, denominator);
1492
1493#undef INPLACE_UPDATE
1494error:
1495 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001496 Py_XDECREF(denominator);
1497 Py_XDECREF(numerator);
1498 return result_pair;
1499}
1500
1501PyDoc_STRVAR(float_as_integer_ratio_doc,
1502"float.as_integer_ratio() -> (int, int)\n"
1503"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001504"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1505"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001506"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001507"\n"
1508">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001509"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001510">>> (0.0).as_integer_ratio()\n"
1511"(0, 1)\n"
1512">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001513"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001514
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001515
Jeremy Hylton938ace62002-07-17 16:30:39 +00001516static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001517float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1518
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519static PyObject *
1520float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1521{
1522 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001523 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524
Guido van Rossumbef14172001-08-29 15:47:46 +00001525 if (type != &PyFloat_Type)
1526 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1528 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001529 /* If it's a string, but not a string subclass, use
1530 PyFloat_FromString. */
1531 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532 return PyFloat_FromString(x, NULL);
1533 return PyNumber_Float(x);
1534}
1535
Guido van Rossumbef14172001-08-29 15:47:46 +00001536/* Wimpy, slow approach to tp_new calls for subtypes of float:
1537 first create a regular float from whatever arguments we got,
1538 then allocate a subtype instance and initialize its ob_fval
1539 from the regular float. The regular float is then thrown away.
1540*/
1541static PyObject *
1542float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1543{
Anthony Baxter377be112006-04-11 06:54:30 +00001544 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001545
1546 assert(PyType_IsSubtype(type, &PyFloat_Type));
1547 tmp = float_new(&PyFloat_Type, args, kwds);
1548 if (tmp == NULL)
1549 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001550 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001551 newobj = type->tp_alloc(type, 0);
1552 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001553 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001554 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001555 }
Anthony Baxter377be112006-04-11 06:54:30 +00001556 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001557 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001558 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001559}
1560
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001561static PyObject *
1562float_getnewargs(PyFloatObject *v)
1563{
1564 return Py_BuildValue("(d)", v->ob_fval);
1565}
1566
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001567/* this is for the benefit of the pack/unpack routines below */
1568
1569typedef enum {
1570 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1571} float_format_type;
1572
1573static float_format_type double_format, float_format;
1574static float_format_type detected_double_format, detected_float_format;
1575
1576static PyObject *
1577float_getformat(PyTypeObject *v, PyObject* arg)
1578{
1579 char* s;
1580 float_format_type r;
1581
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001582 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001583 PyErr_Format(PyExc_TypeError,
1584 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001585 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001586 return NULL;
1587 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001588 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001589 if (strcmp(s, "double") == 0) {
1590 r = double_format;
1591 }
1592 else if (strcmp(s, "float") == 0) {
1593 r = float_format;
1594 }
1595 else {
1596 PyErr_SetString(PyExc_ValueError,
1597 "__getformat__() argument 1 must be "
1598 "'double' or 'float'");
1599 return NULL;
1600 }
1601
1602 switch (r) {
1603 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001604 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001605 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001606 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001607 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001608 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001609 default:
1610 Py_FatalError("insane float_format or double_format");
1611 return NULL;
1612 }
1613}
1614
1615PyDoc_STRVAR(float_getformat_doc,
1616"float.__getformat__(typestr) -> string\n"
1617"\n"
1618"You probably don't want to use this function. It exists mainly to be\n"
1619"used in Python's test suite.\n"
1620"\n"
1621"typestr must be 'double' or 'float'. This function returns whichever of\n"
1622"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1623"format of floating point numbers used by the C type named by typestr.");
1624
1625static PyObject *
1626float_setformat(PyTypeObject *v, PyObject* args)
1627{
1628 char* typestr;
1629 char* format;
1630 float_format_type f;
1631 float_format_type detected;
1632 float_format_type *p;
1633
1634 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1635 return NULL;
1636
1637 if (strcmp(typestr, "double") == 0) {
1638 p = &double_format;
1639 detected = detected_double_format;
1640 }
1641 else if (strcmp(typestr, "float") == 0) {
1642 p = &float_format;
1643 detected = detected_float_format;
1644 }
1645 else {
1646 PyErr_SetString(PyExc_ValueError,
1647 "__setformat__() argument 1 must "
1648 "be 'double' or 'float'");
1649 return NULL;
1650 }
1651
1652 if (strcmp(format, "unknown") == 0) {
1653 f = unknown_format;
1654 }
1655 else if (strcmp(format, "IEEE, little-endian") == 0) {
1656 f = ieee_little_endian_format;
1657 }
1658 else if (strcmp(format, "IEEE, big-endian") == 0) {
1659 f = ieee_big_endian_format;
1660 }
1661 else {
1662 PyErr_SetString(PyExc_ValueError,
1663 "__setformat__() argument 2 must be "
1664 "'unknown', 'IEEE, little-endian' or "
1665 "'IEEE, big-endian'");
1666 return NULL;
1667
1668 }
1669
1670 if (f != unknown_format && f != detected) {
1671 PyErr_Format(PyExc_ValueError,
1672 "can only set %s format to 'unknown' or the "
1673 "detected platform value", typestr);
1674 return NULL;
1675 }
1676
1677 *p = f;
1678 Py_RETURN_NONE;
1679}
1680
1681PyDoc_STRVAR(float_setformat_doc,
1682"float.__setformat__(typestr, fmt) -> None\n"
1683"\n"
1684"You probably don't want to use this function. It exists mainly to be\n"
1685"used in Python's test suite.\n"
1686"\n"
1687"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1688"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1689"one of the latter two if it appears to match the underlying C reality.\n"
1690"\n"
1691"Overrides the automatic determination of C-level floating point type.\n"
1692"This affects how floats are converted to and from binary strings.");
1693
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001694static PyObject *
1695float_getzero(PyObject *v, void *closure)
1696{
1697 return PyFloat_FromDouble(0.0);
1698}
1699
Eric Smitha9f7d622008-02-17 19:46:49 +00001700static PyObject *
1701float__format__(PyObject *self, PyObject *args)
1702{
1703 PyObject *format_spec;
1704
1705 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1706 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001707 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001708 return _PyFloat_FormatAdvanced(self,
1709 PyBytes_AS_STRING(format_spec),
1710 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001711 if (PyUnicode_Check(format_spec)) {
1712 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001713 PyObject *result;
1714 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001715
Eric Smithdc13b792008-05-30 18:10:04 +00001716 if (str_spec == NULL)
1717 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001718
Eric Smithdc13b792008-05-30 18:10:04 +00001719 result = _PyFloat_FormatAdvanced(self,
1720 PyBytes_AS_STRING(str_spec),
1721 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001722
Eric Smithdc13b792008-05-30 18:10:04 +00001723 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001724 return result;
1725 }
1726 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1727 return NULL;
1728}
1729
1730PyDoc_STRVAR(float__format__doc,
1731"float.__format__(format_spec) -> string\n"
1732"\n"
1733"Formats the float according to format_spec.");
1734
1735
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001736static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001737 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001738 "Returns self, the complex conjugate of any float."},
1739 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1740 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001741 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1742 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001743 {"fromhex", (PyCFunction)float_fromhex,
1744 METH_O|METH_CLASS, float_fromhex_doc},
1745 {"hex", (PyCFunction)float_hex,
1746 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001747 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1748 "Returns True if the float is an integer."},
1749#if 0
1750 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1751 "Returns True if the float is positive or negative infinite."},
1752 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1753 "Returns True if the float is finite, neither infinite nor NaN."},
1754 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1755 "Returns True if the float is not a number (NaN)."},
1756#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001757 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001758 {"__getformat__", (PyCFunction)float_getformat,
1759 METH_O|METH_CLASS, float_getformat_doc},
1760 {"__setformat__", (PyCFunction)float_setformat,
1761 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001762 {"__format__", (PyCFunction)float__format__,
1763 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001764 {NULL, NULL} /* sentinel */
1765};
1766
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001767static PyGetSetDef float_getset[] = {
1768 {"real",
1769 (getter)float_float, (setter)NULL,
1770 "the real part of a complex number",
1771 NULL},
1772 {"imag",
1773 (getter)float_getzero, (setter)NULL,
1774 "the imaginary part of a complex number",
1775 NULL},
1776 {NULL} /* Sentinel */
1777};
1778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001779PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780"float(x) -> floating point number\n\
1781\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001782Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783
1784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001785static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001786 float_add, /*nb_add*/
1787 float_sub, /*nb_subtract*/
1788 float_mul, /*nb_multiply*/
1789 float_classic_div, /*nb_divide*/
1790 float_rem, /*nb_remainder*/
1791 float_divmod, /*nb_divmod*/
1792 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001793 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001794 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001795 (unaryfunc)float_abs, /*nb_absolute*/
1796 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001797 0, /*nb_invert*/
1798 0, /*nb_lshift*/
1799 0, /*nb_rshift*/
1800 0, /*nb_and*/
1801 0, /*nb_xor*/
1802 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001803 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001804 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001805 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001806 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001807 0, /* nb_oct */
1808 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001809 0, /* nb_inplace_add */
1810 0, /* nb_inplace_subtract */
1811 0, /* nb_inplace_multiply */
1812 0, /* nb_inplace_divide */
1813 0, /* nb_inplace_remainder */
1814 0, /* nb_inplace_power */
1815 0, /* nb_inplace_lshift */
1816 0, /* nb_inplace_rshift */
1817 0, /* nb_inplace_and */
1818 0, /* nb_inplace_xor */
1819 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001820 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001821 float_div, /* nb_true_divide */
1822 0, /* nb_inplace_floor_divide */
1823 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001824};
1825
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001826PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001827 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001828 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001829 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001830 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 (destructor)float_dealloc, /* tp_dealloc */
1832 (printfunc)float_print, /* tp_print */
1833 0, /* tp_getattr */
1834 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001835 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 (reprfunc)float_repr, /* tp_repr */
1837 &float_as_number, /* tp_as_number */
1838 0, /* tp_as_sequence */
1839 0, /* tp_as_mapping */
1840 (hashfunc)float_hash, /* tp_hash */
1841 0, /* tp_call */
1842 (reprfunc)float_str, /* tp_str */
1843 PyObject_GenericGetAttr, /* tp_getattro */
1844 0, /* tp_setattro */
1845 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001846 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1847 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 float_doc, /* tp_doc */
1849 0, /* tp_traverse */
1850 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001851 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 0, /* tp_weaklistoffset */
1853 0, /* tp_iter */
1854 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001855 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001857 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 0, /* tp_base */
1859 0, /* tp_dict */
1860 0, /* tp_descr_get */
1861 0, /* tp_descr_set */
1862 0, /* tp_dictoffset */
1863 0, /* tp_init */
1864 0, /* tp_alloc */
1865 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001867
1868void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001869_PyFloat_Init(void)
1870{
1871 /* We attempt to determine if this machine is using IEEE
1872 floating point formats by peering at the bits of some
1873 carefully chosen values. If it looks like we are on an
1874 IEEE platform, the float packing/unpacking routines can
1875 just copy bits, if not they resort to arithmetic & shifts
1876 and masks. The shifts & masks approach works on all finite
1877 values, but what happens to infinities, NaNs and signed
1878 zeroes on packing is an accident, and attempting to unpack
1879 a NaN or an infinity will raise an exception.
1880
1881 Note that if we're on some whacked-out platform which uses
1882 IEEE formats but isn't strictly little-endian or big-
1883 endian, we will fall back to the portable shifts & masks
1884 method. */
1885
1886#if SIZEOF_DOUBLE == 8
1887 {
1888 double x = 9006104071832581.0;
1889 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1890 detected_double_format = ieee_big_endian_format;
1891 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1892 detected_double_format = ieee_little_endian_format;
1893 else
1894 detected_double_format = unknown_format;
1895 }
1896#else
1897 detected_double_format = unknown_format;
1898#endif
1899
1900#if SIZEOF_FLOAT == 4
1901 {
1902 float y = 16711938.0;
1903 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1904 detected_float_format = ieee_big_endian_format;
1905 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1906 detected_float_format = ieee_little_endian_format;
1907 else
1908 detected_float_format = unknown_format;
1909 }
1910#else
1911 detected_float_format = unknown_format;
1912#endif
1913
1914 double_format = detected_double_format;
1915 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001916
Christian Heimes796fc312008-01-30 18:58:29 +00001917 /* Init float info */
1918 if (FloatInfoType.tp_name == 0)
1919 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001920}
1921
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001922int
1923PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001924{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001925 PyFloatObject *p;
1926 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001927 int i;
1928 int u; /* remaining unfreed ints per block */
1929 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001930
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001931 list = block_list;
1932 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001933 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001934 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001935 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001936 for (i = 0, p = &list->objects[0];
1937 i < N_FLOATOBJECTS;
1938 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001939 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001940 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001941 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001942 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001943 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001944 list->next = block_list;
1945 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001946 for (i = 0, p = &list->objects[0];
1947 i < N_FLOATOBJECTS;
1948 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001949 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001950 Py_REFCNT(p) == 0) {
1951 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001952 free_list;
1953 free_list = p;
1954 }
1955 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001956 }
1957 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001958 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001959 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001960 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001961 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001962 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001963 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001964}
1965
1966void
1967PyFloat_Fini(void)
1968{
1969 PyFloatObject *p;
1970 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001971 int i;
1972 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001973
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001974 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00001975
Guido van Rossum3fce8831999-03-12 19:43:17 +00001976 if (!Py_VerboseFlag)
1977 return;
1978 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001979 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001980 fprintf(stderr, "\n");
1981 }
1982 else {
1983 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001984 ": %d unfreed float%s\n",
1985 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001986 }
1987 if (Py_VerboseFlag > 1) {
1988 list = block_list;
1989 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001990 for (i = 0, p = &list->objects[0];
1991 i < N_FLOATOBJECTS;
1992 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001993 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001994 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001995 char buf[100];
1996 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001997 /* XXX(twouters) cast refcount to
1998 long until %zd is universally
1999 available
2000 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00002001 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002002 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002003 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00002004 }
2005 }
2006 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002007 }
2008 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002009}
Tim Peters9905b942003-03-20 20:53:32 +00002010
2011/*----------------------------------------------------------------------------
2012 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002013 */
2014int
2015_PyFloat_Pack4(double x, unsigned char *p, int le)
2016{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002017 if (float_format == unknown_format) {
2018 unsigned char sign;
2019 int e;
2020 double f;
2021 unsigned int fbits;
2022 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002023
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024 if (le) {
2025 p += 3;
2026 incr = -1;
2027 }
Tim Peters9905b942003-03-20 20:53:32 +00002028
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002029 if (x < 0) {
2030 sign = 1;
2031 x = -x;
2032 }
2033 else
2034 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002035
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002036 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002037
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002038 /* Normalize f to be in the range [1.0, 2.0) */
2039 if (0.5 <= f && f < 1.0) {
2040 f *= 2.0;
2041 e--;
2042 }
2043 else if (f == 0.0)
2044 e = 0;
2045 else {
2046 PyErr_SetString(PyExc_SystemError,
2047 "frexp() result out of range");
2048 return -1;
2049 }
2050
2051 if (e >= 128)
2052 goto Overflow;
2053 else if (e < -126) {
2054 /* Gradual underflow */
2055 f = ldexp(f, 126 + e);
2056 e = 0;
2057 }
2058 else if (!(e == 0 && f == 0.0)) {
2059 e += 127;
2060 f -= 1.0; /* Get rid of leading 1 */
2061 }
2062
2063 f *= 8388608.0; /* 2**23 */
2064 fbits = (unsigned int)(f + 0.5); /* Round */
2065 assert(fbits <= 8388608);
2066 if (fbits >> 23) {
2067 /* The carry propagated out of a string of 23 1 bits. */
2068 fbits = 0;
2069 ++e;
2070 if (e >= 255)
2071 goto Overflow;
2072 }
2073
2074 /* First byte */
2075 *p = (sign << 7) | (e >> 1);
2076 p += incr;
2077
2078 /* Second byte */
2079 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2080 p += incr;
2081
2082 /* Third byte */
2083 *p = (fbits >> 8) & 0xFF;
2084 p += incr;
2085
2086 /* Fourth byte */
2087 *p = fbits & 0xFF;
2088
2089 /* Done */
2090 return 0;
2091
Tim Peters9905b942003-03-20 20:53:32 +00002092 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002093 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002094 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002095 const char *s = (char*)&y;
2096 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002097
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002098 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2099 goto Overflow;
2100
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101 if ((float_format == ieee_little_endian_format && !le)
2102 || (float_format == ieee_big_endian_format && le)) {
2103 p += 3;
2104 incr = -1;
2105 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002106
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107 for (i = 0; i < 4; i++) {
2108 *p = *s++;
2109 p += incr;
2110 }
2111 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002112 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002113 Overflow:
2114 PyErr_SetString(PyExc_OverflowError,
2115 "float too large to pack with f format");
2116 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002117}
2118
2119int
2120_PyFloat_Pack8(double x, unsigned char *p, int le)
2121{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 if (double_format == unknown_format) {
2123 unsigned char sign;
2124 int e;
2125 double f;
2126 unsigned int fhi, flo;
2127 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002128
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129 if (le) {
2130 p += 7;
2131 incr = -1;
2132 }
Tim Peters9905b942003-03-20 20:53:32 +00002133
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002134 if (x < 0) {
2135 sign = 1;
2136 x = -x;
2137 }
2138 else
2139 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002140
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002141 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002142
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002143 /* Normalize f to be in the range [1.0, 2.0) */
2144 if (0.5 <= f && f < 1.0) {
2145 f *= 2.0;
2146 e--;
2147 }
2148 else if (f == 0.0)
2149 e = 0;
2150 else {
2151 PyErr_SetString(PyExc_SystemError,
2152 "frexp() result out of range");
2153 return -1;
2154 }
2155
2156 if (e >= 1024)
2157 goto Overflow;
2158 else if (e < -1022) {
2159 /* Gradual underflow */
2160 f = ldexp(f, 1022 + e);
2161 e = 0;
2162 }
2163 else if (!(e == 0 && f == 0.0)) {
2164 e += 1023;
2165 f -= 1.0; /* Get rid of leading 1 */
2166 }
2167
2168 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2169 f *= 268435456.0; /* 2**28 */
2170 fhi = (unsigned int)f; /* Truncate */
2171 assert(fhi < 268435456);
2172
2173 f -= (double)fhi;
2174 f *= 16777216.0; /* 2**24 */
2175 flo = (unsigned int)(f + 0.5); /* Round */
2176 assert(flo <= 16777216);
2177 if (flo >> 24) {
2178 /* The carry propagated out of a string of 24 1 bits. */
2179 flo = 0;
2180 ++fhi;
2181 if (fhi >> 28) {
2182 /* And it also progagated out of the next 28 bits. */
2183 fhi = 0;
2184 ++e;
2185 if (e >= 2047)
2186 goto Overflow;
2187 }
2188 }
2189
2190 /* First byte */
2191 *p = (sign << 7) | (e >> 4);
2192 p += incr;
2193
2194 /* Second byte */
2195 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2196 p += incr;
2197
2198 /* Third byte */
2199 *p = (fhi >> 16) & 0xFF;
2200 p += incr;
2201
2202 /* Fourth byte */
2203 *p = (fhi >> 8) & 0xFF;
2204 p += incr;
2205
2206 /* Fifth byte */
2207 *p = fhi & 0xFF;
2208 p += incr;
2209
2210 /* Sixth byte */
2211 *p = (flo >> 16) & 0xFF;
2212 p += incr;
2213
2214 /* Seventh byte */
2215 *p = (flo >> 8) & 0xFF;
2216 p += incr;
2217
2218 /* Eighth byte */
2219 *p = flo & 0xFF;
2220 p += incr;
2221
2222 /* Done */
2223 return 0;
2224
2225 Overflow:
2226 PyErr_SetString(PyExc_OverflowError,
2227 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002228 return -1;
2229 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230 else {
2231 const char *s = (char*)&x;
2232 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002233
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234 if ((double_format == ieee_little_endian_format && !le)
2235 || (double_format == ieee_big_endian_format && le)) {
2236 p += 7;
2237 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002238 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002239
2240 for (i = 0; i < 8; i++) {
2241 *p = *s++;
2242 p += incr;
2243 }
2244 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002245 }
Tim Peters9905b942003-03-20 20:53:32 +00002246}
2247
2248double
2249_PyFloat_Unpack4(const unsigned char *p, int le)
2250{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002251 if (float_format == unknown_format) {
2252 unsigned char sign;
2253 int e;
2254 unsigned int f;
2255 double x;
2256 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002257
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258 if (le) {
2259 p += 3;
2260 incr = -1;
2261 }
2262
2263 /* First byte */
2264 sign = (*p >> 7) & 1;
2265 e = (*p & 0x7F) << 1;
2266 p += incr;
2267
2268 /* Second byte */
2269 e |= (*p >> 7) & 1;
2270 f = (*p & 0x7F) << 16;
2271 p += incr;
2272
2273 if (e == 255) {
2274 PyErr_SetString(
2275 PyExc_ValueError,
2276 "can't unpack IEEE 754 special value "
2277 "on non-IEEE platform");
2278 return -1;
2279 }
2280
2281 /* Third byte */
2282 f |= *p << 8;
2283 p += incr;
2284
2285 /* Fourth byte */
2286 f |= *p;
2287
2288 x = (double)f / 8388608.0;
2289
2290 /* XXX This sadly ignores Inf/NaN issues */
2291 if (e == 0)
2292 e = -126;
2293 else {
2294 x += 1.0;
2295 e -= 127;
2296 }
2297 x = ldexp(x, e);
2298
2299 if (sign)
2300 x = -x;
2301
2302 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002303 }
Tim Peters9905b942003-03-20 20:53:32 +00002304 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002305 float x;
2306
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307 if ((float_format == ieee_little_endian_format && !le)
2308 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002309 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310 char *d = &buf[3];
2311 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002312
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313 for (i = 0; i < 4; i++) {
2314 *d-- = *p++;
2315 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002316 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317 }
2318 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002319 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002321
2322 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323 }
Tim Peters9905b942003-03-20 20:53:32 +00002324}
2325
2326double
2327_PyFloat_Unpack8(const unsigned char *p, int le)
2328{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329 if (double_format == unknown_format) {
2330 unsigned char sign;
2331 int e;
2332 unsigned int fhi, flo;
2333 double x;
2334 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002335
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336 if (le) {
2337 p += 7;
2338 incr = -1;
2339 }
2340
2341 /* First byte */
2342 sign = (*p >> 7) & 1;
2343 e = (*p & 0x7F) << 4;
2344
2345 p += incr;
2346
2347 /* Second byte */
2348 e |= (*p >> 4) & 0xF;
2349 fhi = (*p & 0xF) << 24;
2350 p += incr;
2351
2352 if (e == 2047) {
2353 PyErr_SetString(
2354 PyExc_ValueError,
2355 "can't unpack IEEE 754 special value "
2356 "on non-IEEE platform");
2357 return -1.0;
2358 }
2359
2360 /* Third byte */
2361 fhi |= *p << 16;
2362 p += incr;
2363
2364 /* Fourth byte */
2365 fhi |= *p << 8;
2366 p += incr;
2367
2368 /* Fifth byte */
2369 fhi |= *p;
2370 p += incr;
2371
2372 /* Sixth byte */
2373 flo = *p << 16;
2374 p += incr;
2375
2376 /* Seventh byte */
2377 flo |= *p << 8;
2378 p += incr;
2379
2380 /* Eighth byte */
2381 flo |= *p;
2382
2383 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2384 x /= 268435456.0; /* 2**28 */
2385
2386 if (e == 0)
2387 e = -1022;
2388 else {
2389 x += 1.0;
2390 e -= 1023;
2391 }
2392 x = ldexp(x, e);
2393
2394 if (sign)
2395 x = -x;
2396
2397 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002398 }
Tim Peters9905b942003-03-20 20:53:32 +00002399 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002400 double x;
2401
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002402 if ((double_format == ieee_little_endian_format && !le)
2403 || (double_format == ieee_big_endian_format && le)) {
2404 char buf[8];
2405 char *d = &buf[7];
2406 int i;
2407
2408 for (i = 0; i < 8; i++) {
2409 *d-- = *p++;
2410 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002411 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002412 }
2413 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002414 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002415 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002416
2417 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002418 }
Tim Peters9905b942003-03-20 20:53:32 +00002419}