blob: b7b52207e36b67ee4a2523b4c88009d65c7572f7 [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 Heimesd32ed6f2008-01-14 18:49:24 +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 Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +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
Christian Heimesbbe741d2008-03-28 10:53:29 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Guido van Rossum6923e131990-11-02 17:50:43 +000022
Christian Heimes969fe572008-01-25 11:23:10 +000023#ifdef _OSF_SOURCE
24/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
25extern int finite(double);
26#endif
27
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000029#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000030#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000031#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000032
Guido van Rossum3fce8831999-03-12 19:43:17 +000033struct _floatblock {
34 struct _floatblock *next;
35 PyFloatObject objects[N_FLOATOBJECTS];
36};
37
38typedef struct _floatblock PyFloatBlock;
39
40static PyFloatBlock *block_list = NULL;
41static PyFloatObject *free_list = NULL;
42
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000044fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045{
46 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
48 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000050 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000051 ((PyFloatBlock *)p)->next = block_list;
52 block_list = (PyFloatBlock *)p;
53 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 q = p + N_FLOATOBJECTS;
55 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000056 Py_TYPE(q) = (struct _typeobject *)(q-1);
57 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 return p + N_FLOATOBJECTS - 1;
59}
60
Christian Heimes93852662007-12-01 12:22:32 +000061double
62PyFloat_GetMax(void)
63{
64 return DBL_MAX;
65}
66
67double
68PyFloat_GetMin(void)
69{
70 return DBL_MIN;
71}
72
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073static PyTypeObject FloatInfoType;
74
75PyDoc_STRVAR(floatinfo__doc__,
76"sys.floatinfo\n\
77\n\
78A structseq holding information about the float type. It contains low level\n\
79information about the precision and internal representation. Please study\n\
80your system's :file:`float.h` for more information.");
81
82static PyStructSequence_Field floatinfo_fields[] = {
83 {"max", "DBL_MAX -- maximum representable finite float"},
84 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
85 "is representable"},
86 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
87 "is representable"},
88 {"min", "DBL_MIN -- Minimum positive normalizer float"},
89 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
90 "is a normalized float"},
91 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
92 "a normalized"},
93 {"dig", "DBL_DIG -- digits"},
94 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
95 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
96 "representable float"},
97 {"radix", "FLT_RADIX -- radix of exponent"},
98 {"rounds", "FLT_ROUNDS -- addition rounds"},
99 {0}
100};
101
102static PyStructSequence_Desc floatinfo_desc = {
103 "sys.floatinfo", /* name */
104 floatinfo__doc__, /* doc */
105 floatinfo_fields, /* fields */
106 11
107};
108
Christian Heimes93852662007-12-01 12:22:32 +0000109PyObject *
110PyFloat_GetInfo(void)
111{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000112 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000113 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000114
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000115 floatinfo = PyStructSequence_New(&FloatInfoType);
116 if (floatinfo == NULL) {
117 return NULL;
118 }
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120#define SetIntFlag(flag) \
121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
122#define SetDblFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125 SetDblFlag(DBL_MAX);
126 SetIntFlag(DBL_MAX_EXP);
127 SetIntFlag(DBL_MAX_10_EXP);
128 SetDblFlag(DBL_MIN);
129 SetIntFlag(DBL_MIN_EXP);
130 SetIntFlag(DBL_MIN_10_EXP);
131 SetIntFlag(DBL_DIG);
132 SetIntFlag(DBL_MANT_DIG);
133 SetDblFlag(DBL_EPSILON);
134 SetIntFlag(FLT_RADIX);
135 SetIntFlag(FLT_ROUNDS);
136#undef SetIntFlag
137#undef SetDblFlag
138
139 if (PyErr_Occurred()) {
140 Py_CLEAR(floatinfo);
141 return NULL;
142 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000143 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000144}
145
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000154 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000155 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000163PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164{
Christian Heimes99170a52007-12-19 02:07:34 +0000165 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000167 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000172 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000178 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000180 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000181 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000183 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000186 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000189
Guido van Rossum4c08d552000-03-10 22:55:18 +0000190 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191 while (*s && isspace(Py_CHARMASK(*s)))
192 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000193 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000194 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000195 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 }
Christian Heimes99170a52007-12-19 02:07:34 +0000197 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000198 /* We don't care about overflow or underflow. If the platform supports
199 * them, infinities and signed zeroes (on underflow) are fine.
Eric Smith0923d1d2009-04-16 20:16:10 +0000200 * However, strtod can return 0 for denormalized numbers. Note that
Tim Petersef14d732000-09-23 03:39:17 +0000201 * whether strtod sets errno on underflow is not defined, so we can't
202 * key off errno.
203 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000204 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000205 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000206 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000207 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000209 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210 if (end > last)
211 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000212 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000213 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000214 char *p = (char*)sp;
215 int sign = 1;
216
217 if (*p == '-') {
218 sign = -1;
219 p++;
220 }
221 if (*p == '+') {
222 p++;
223 }
224 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000225 if (s_buffer != NULL)
226 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000227 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000228 }
Georg Brandl2ee470f2008-07-16 12:55:28 +0000229 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000230 if (s_buffer != NULL)
231 PyMem_FREE(s_buffer);
Georg Brandl2ee470f2008-07-16 12:55:28 +0000232 Py_RETURN_INF(sign);
233 }
Christian Heimes99170a52007-12-19 02:07:34 +0000234#ifdef Py_NAN
235 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000236 if (s_buffer != NULL)
237 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000238 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000239 }
240#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000241 PyOS_snprintf(buffer, sizeof(buffer),
242 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000243 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000244 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000245 }
246 /* Since end != s, the platform made *some* kind of sense out
247 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000248 while (*end && isspace(Py_CHARMASK(*end)))
249 end++;
250 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000251 PyOS_snprintf(buffer, sizeof(buffer),
252 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000253 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000254 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000255 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000256 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000257 PyErr_SetString(PyExc_ValueError,
258 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000259 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000261 result = PyFloat_FromDouble(x);
262 error:
263 if (s_buffer)
264 PyMem_FREE(s_buffer);
265 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266}
267
Guido van Rossum234f9421993-06-17 12:35:49 +0000268static void
Fred Drakefd99de62000-07-09 05:02:18 +0000269float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000270{
Guido van Rossum9475a232001-10-05 20:51:39 +0000271 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000272 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000273 free_list = op;
274 }
275 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000276 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000277}
278
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279double
Fred Drakefd99de62000-07-09 05:02:18 +0000280PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 PyNumberMethods *nb;
283 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000286 if (op && PyFloat_Check(op))
287 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000289 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 return -1;
292 }
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Christian Heimes90aa7642007-12-19 02:45:37 +0000294 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000295 PyErr_SetString(PyExc_TypeError, "a float is required");
296 return -1;
297 }
298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300 if (fo == NULL)
301 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 if (!PyFloat_Check(fo)) {
303 PyErr_SetString(PyExc_TypeError,
304 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 return -1;
306 }
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 val = PyFloat_AS_DOUBLE(fo);
309 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312}
313
Neil Schemenauer32117e52001-01-04 01:44:34 +0000314/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000315 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000316 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*/
Neil Schemenauer32117e52001-01-04 01:44:34 +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;
325
Eric Smith0923d1d2009-04-16 20:16:10 +0000326/* Methods */
327
Neil Schemenauer32117e52001-01-04 01:44:34 +0000328static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000329convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000330{
331 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000332
Guido van Rossumddefaf32007-01-14 03:31:43 +0000333 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000334 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000335 if (*dbl == -1.0 && PyErr_Occurred()) {
336 *v = NULL;
337 return -1;
338 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000339 }
340 else {
341 Py_INCREF(Py_NotImplemented);
342 *v = Py_NotImplemented;
343 return -1;
344 }
345 return 0;
346}
347
Eric Smith0923d1d2009-04-16 20:16:10 +0000348static PyObject *
349float_str_or_repr(PyFloatObject *v, char format_code)
350{
351 PyObject *result;
352 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
353 format_code, 0, Py_DTSF_ADD_DOT_0,
354 NULL);
355 if (!buf)
356 return PyErr_NoMemory();
357 result = PyUnicode_FromString(buf);
358 PyMem_Free(buf);
359 return result;
360}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000361
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000362static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000363float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364{
Eric Smith0923d1d2009-04-16 20:16:10 +0000365 return float_str_or_repr(v, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000366}
367
368static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000369float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000370{
Eric Smith0923d1d2009-04-16 20:16:10 +0000371 return float_str_or_repr(v, 's');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372}
373
Tim Peters307fa782004-09-23 08:06:40 +0000374/* Comparison is pretty much a nightmare. When comparing float to float,
375 * we do it as straightforwardly (and long-windedly) as conceivable, so
376 * that, e.g., Python x == y delivers the same result as the platform
377 * C x == y when x and/or y is a NaN.
378 * When mixing float with an integer type, there's no good *uniform* approach.
379 * Converting the double to an integer obviously doesn't work, since we
380 * may lose info from fractional bits. Converting the integer to a double
381 * also has two failure modes: (1) a long int may trigger overflow (too
382 * large to fit in the dynamic range of a C double); (2) even a C long may have
383 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
384 * 63 bits of precision, but a C double probably has only 53), and then
385 * we can falsely claim equality when low-order integer bits are lost by
386 * coercion to double. So this part is painful too.
387 */
388
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000389static PyObject*
390float_richcompare(PyObject *v, PyObject *w, int op)
391{
392 double i, j;
393 int r = 0;
394
Tim Peters307fa782004-09-23 08:06:40 +0000395 assert(PyFloat_Check(v));
396 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000397
Tim Peters307fa782004-09-23 08:06:40 +0000398 /* Switch on the type of w. Set i and j to doubles to be compared,
399 * and op to the richcomp to use.
400 */
401 if (PyFloat_Check(w))
402 j = PyFloat_AS_DOUBLE(w);
403
Thomas Wouters477c8d52006-05-27 19:21:47 +0000404 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000405 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000406 /* If i is an infinity, its magnitude exceeds any
407 * finite integer, so it doesn't matter which int we
408 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000409 */
410 j = 0.0;
411 else
412 goto Unimplemented;
413 }
414
Tim Peters307fa782004-09-23 08:06:40 +0000415 else if (PyLong_Check(w)) {
416 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
417 int wsign = _PyLong_Sign(w);
418 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000419 int exponent;
420
421 if (vsign != wsign) {
422 /* Magnitudes are irrelevant -- the signs alone
423 * determine the outcome.
424 */
425 i = (double)vsign;
426 j = (double)wsign;
427 goto Compare;
428 }
429 /* The signs are the same. */
430 /* Convert w to a double if it fits. In particular, 0 fits. */
431 nbits = _PyLong_NumBits(w);
432 if (nbits == (size_t)-1 && PyErr_Occurred()) {
433 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000434 * to hold the # of bits. Replace with little doubles
435 * that give the same outcome -- w is so large that
436 * its magnitude must exceed the magnitude of any
437 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000438 */
439 PyErr_Clear();
440 i = (double)vsign;
441 assert(wsign != 0);
442 j = wsign * 2.0;
443 goto Compare;
444 }
445 if (nbits <= 48) {
446 j = PyLong_AsDouble(w);
447 /* It's impossible that <= 48 bits overflowed. */
448 assert(j != -1.0 || ! PyErr_Occurred());
449 goto Compare;
450 }
451 assert(wsign != 0); /* else nbits was 0 */
452 assert(vsign != 0); /* if vsign were 0, then since wsign is
453 * not 0, we would have taken the
454 * vsign != wsign branch at the start */
455 /* We want to work with non-negative numbers. */
456 if (vsign < 0) {
457 /* "Multiply both sides" by -1; this also swaps the
458 * comparator.
459 */
460 i = -i;
461 op = _Py_SwappedOp[op];
462 }
463 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000464 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000465 /* exponent is the # of bits in v before the radix point;
466 * we know that nbits (the # of bits in w) > 48 at this point
467 */
468 if (exponent < 0 || (size_t)exponent < nbits) {
469 i = 1.0;
470 j = 2.0;
471 goto Compare;
472 }
473 if ((size_t)exponent > nbits) {
474 i = 2.0;
475 j = 1.0;
476 goto Compare;
477 }
478 /* v and w have the same number of bits before the radix
479 * point. Construct two longs that have the same comparison
480 * outcome.
481 */
482 {
483 double fracpart;
484 double intpart;
485 PyObject *result = NULL;
486 PyObject *one = NULL;
487 PyObject *vv = NULL;
488 PyObject *ww = w;
489
490 if (wsign < 0) {
491 ww = PyNumber_Negative(w);
492 if (ww == NULL)
493 goto Error;
494 }
495 else
496 Py_INCREF(ww);
497
498 fracpart = modf(i, &intpart);
499 vv = PyLong_FromDouble(intpart);
500 if (vv == NULL)
501 goto Error;
502
503 if (fracpart != 0.0) {
504 /* Shift left, and or a 1 bit into vv
505 * to represent the lost fraction.
506 */
507 PyObject *temp;
508
Christian Heimes217cfd12007-12-02 14:31:20 +0000509 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000510 if (one == NULL)
511 goto Error;
512
513 temp = PyNumber_Lshift(ww, one);
514 if (temp == NULL)
515 goto Error;
516 Py_DECREF(ww);
517 ww = temp;
518
519 temp = PyNumber_Lshift(vv, one);
520 if (temp == NULL)
521 goto Error;
522 Py_DECREF(vv);
523 vv = temp;
524
525 temp = PyNumber_Or(vv, one);
526 if (temp == NULL)
527 goto Error;
528 Py_DECREF(vv);
529 vv = temp;
530 }
531
532 r = PyObject_RichCompareBool(vv, ww, op);
533 if (r < 0)
534 goto Error;
535 result = PyBool_FromLong(r);
536 Error:
537 Py_XDECREF(vv);
538 Py_XDECREF(ww);
539 Py_XDECREF(one);
540 return result;
541 }
542 } /* else if (PyLong_Check(w)) */
543
544 else /* w isn't float, int, or long */
545 goto Unimplemented;
546
547 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000548 PyFPE_START_PROTECT("richcompare", return NULL)
549 switch (op) {
550 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000551 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000552 break;
553 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000554 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000555 break;
556 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000557 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000558 break;
559 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000560 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000561 break;
562 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000563 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000564 break;
565 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000566 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000567 break;
568 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000569 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000570 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000571
572 Unimplemented:
573 Py_INCREF(Py_NotImplemented);
574 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000575}
576
Guido van Rossum9bfef441993-03-29 10:43:31 +0000577static long
Fred Drakefd99de62000-07-09 05:02:18 +0000578float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000579{
Tim Peters39dce292000-08-15 03:34:48 +0000580 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000586 double a,b;
587 CONVERT_TO_DOUBLE(v, a);
588 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000589 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590 a = a + b;
591 PyFPE_END_PROTECT(a)
592 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593}
594
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000595static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000596float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000598 double a,b;
599 CONVERT_TO_DOUBLE(v, a);
600 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000601 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000602 a = a - b;
603 PyFPE_END_PROTECT(a)
604 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605}
606
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000608float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000610 double a,b;
611 CONVERT_TO_DOUBLE(v, a);
612 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000613 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000614 a = a * b;
615 PyFPE_END_PROTECT(a)
616 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000622 double a,b;
623 CONVERT_TO_DOUBLE(v, a);
624 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000625#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000626 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000627 PyErr_SetString(PyExc_ZeroDivisionError,
628 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629 return NULL;
630 }
Christian Heimes53876d92008-04-19 00:31:39 +0000631#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000632 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000633 a = a / b;
634 PyFPE_END_PROTECT(a)
635 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636}
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000639float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000641 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000642 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000643 CONVERT_TO_DOUBLE(v, vx);
644 CONVERT_TO_DOUBLE(w, wx);
645#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000647 PyErr_SetString(PyExc_ZeroDivisionError,
648 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649 return NULL;
650 }
Christian Heimes53876d92008-04-19 00:31:39 +0000651#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000652 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000653 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000654 /* note: checking mod*wx < 0 is incorrect -- underflows to
655 0 if wx < sqrt(smallest nonzero double) */
656 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000657 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000658 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000659 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661}
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000664float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000665{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000666 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000667 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000668 CONVERT_TO_DOUBLE(v, vx);
669 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000670 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000672 return NULL;
673 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000674 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000675 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000676 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000677 exact multiple of wx. But this is fp arithmetic, and fp
678 vx - mod is an approximation; the result is that div may
679 not be an exact integral value after the division, although
680 it will always be very close to one.
681 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000682 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000683 if (mod) {
684 /* ensure the remainder has the same sign as the denominator */
685 if ((wx < 0) != (mod < 0)) {
686 mod += wx;
687 div -= 1.0;
688 }
689 }
690 else {
691 /* the remainder is zero, and in the presence of signed zeroes
692 fmod returns different results across platforms; ensure
693 it has the same sign as the denominator; we'd like to do
694 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000695 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000696 if (wx < 0.0)
697 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000698 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000699 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000700 if (div) {
701 floordiv = floor(div);
702 if (div - floordiv > 0.5)
703 floordiv += 1.0;
704 }
705 else {
706 /* div is zero - get the same sign as the true quotient */
707 div *= div; /* hide "div = +0" from optimizers */
708 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
709 }
710 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000711 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000712}
713
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000715float_floor_div(PyObject *v, PyObject *w)
716{
717 PyObject *t, *r;
718
719 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000720 if (t == NULL || t == Py_NotImplemented)
721 return t;
722 assert(PyTuple_CheckExact(t));
723 r = PyTuple_GET_ITEM(t, 0);
724 Py_INCREF(r);
725 Py_DECREF(t);
726 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000727}
728
729static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000730float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731{
732 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000733
734 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000735 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000736 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000737 return NULL;
738 }
739
Neil Schemenauer32117e52001-01-04 01:44:34 +0000740 CONVERT_TO_DOUBLE(v, iv);
741 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000742
743 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000744 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000745 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000746 }
Tim Peters96685bf2001-08-23 22:31:37 +0000747 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000748 if (iw < 0.0) {
749 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000750 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000751 return NULL;
752 }
753 return PyFloat_FromDouble(0.0);
754 }
Christian Heimes53876d92008-04-19 00:31:39 +0000755 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
756 return PyFloat_FromDouble(1.0);
757 }
Tim Peterse87568d2003-05-24 20:18:24 +0000758 if (iv < 0.0) {
759 /* Whether this is an error is a mess, and bumps into libm
760 * bugs so we have to figure it out ourselves.
761 */
762 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000763 /* Negative numbers raised to fractional powers
764 * become complex.
765 */
766 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000767 }
768 /* iw is an exact integer, albeit perhaps a very large one.
769 * -1 raised to an exact integer should never be exceptional.
770 * Alas, some libms (chiefly glibc as of early 2003) return
771 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
772 * happen to be representable in a *C* integer. That's a
773 * bug; we let that slide in math.pow() (which currently
774 * reflects all platform accidents), but not for Python's **.
775 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000777 /* Return 1 if iw is even, -1 if iw is odd; there's
778 * no guarantee that any C integral type is big
779 * enough to hold iw, so we have to check this
780 * indirectly.
781 */
782 ix = floor(iw * 0.5) * 2.0;
783 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
784 }
785 /* Else iv != -1.0, and overflow or underflow are possible.
786 * Unless we're to write pow() ourselves, we have to trust
787 * the platform to do this correctly.
788 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000789 }
Tim Peters96685bf2001-08-23 22:31:37 +0000790 errno = 0;
791 PyFPE_START_PROTECT("pow", return NULL)
792 ix = pow(iv, iw);
793 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000794 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000795 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000796 /* We don't expect any errno value other than ERANGE, but
797 * the range of libm bugs appears unbounded.
798 */
799 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
800 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000802 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804}
805
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000807float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810}
811
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000813float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000814{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000815 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816}
817
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000818static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000819float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000820{
821 return v->ob_fval != 0.0;
822}
823
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000825float_is_integer(PyObject *v)
826{
827 double x = PyFloat_AsDouble(v);
828 PyObject *o;
829
830 if (x == -1.0 && PyErr_Occurred())
831 return NULL;
832 if (!Py_IS_FINITE(x))
833 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000834 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000835 PyFPE_START_PROTECT("is_integer", return NULL)
836 o = (floor(x) == x) ? Py_True : Py_False;
837 PyFPE_END_PROTECT(x)
838 if (errno != 0) {
839 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
840 PyExc_ValueError);
841 return NULL;
842 }
843 Py_INCREF(o);
844 return o;
845}
846
847#if 0
848static PyObject *
849float_is_inf(PyObject *v)
850{
851 double x = PyFloat_AsDouble(v);
852 if (x == -1.0 && PyErr_Occurred())
853 return NULL;
854 return PyBool_FromLong((long)Py_IS_INFINITY(x));
855}
856
857static PyObject *
858float_is_nan(PyObject *v)
859{
860 double x = PyFloat_AsDouble(v);
861 if (x == -1.0 && PyErr_Occurred())
862 return NULL;
863 return PyBool_FromLong((long)Py_IS_NAN(x));
864}
865
866static PyObject *
867float_is_finite(PyObject *v)
868{
869 double x = PyFloat_AsDouble(v);
870 if (x == -1.0 && PyErr_Occurred())
871 return NULL;
872 return PyBool_FromLong((long)Py_IS_FINITE(x));
873}
874#endif
875
876static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000877float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000878{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000880 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000881
882 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000883 /* Try to get out cheap if this fits in a Python int. The attempt
884 * to cast to long must be protected, as C doesn't define what
885 * happens if the double is too big to fit in a long. Some rare
886 * systems raise an exception then (RISCOS was mentioned as one,
887 * and someone using a non-default option on Sun also bumped into
888 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
889 * still be vulnerable: if a long has more bits of precision than
890 * a double, casting MIN/MAX to double may yield an approximation,
891 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
892 * yield true from the C expression wholepart<=LONG_MAX, despite
893 * that wholepart is actually greater than LONG_MAX.
894 */
895 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
896 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000897 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000898 }
899 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000900}
901
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000902/* double_round: rounds a finite double to the closest multiple of
903 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
904 ndigits <= 323). Returns a Python float, or sets a Python error and
905 returns NULL on failure (OverflowError and memory errors are possible). */
906
907#ifndef PY_NO_SHORT_FLOAT_REPR
908/* version of double_round that uses the correctly-rounded string<->double
909 conversions from Python/dtoa.c */
910
911static PyObject *
912double_round(double x, int ndigits) {
913
914 double rounded;
915 Py_ssize_t buflen, mybuflen=100;
916 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
917 int decpt, sign;
918 PyObject *result = NULL;
919
920 /* round to a decimal string */
921 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
922 if (buf == NULL) {
923 PyErr_NoMemory();
924 return NULL;
925 }
926
927 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
928 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
929 buflen = buf_end - buf;
930 if (buflen + 8 > mybuflen) {
931 mybuflen = buflen+8;
932 mybuf = (char *)PyMem_Malloc(mybuflen);
933 if (mybuf == NULL) {
934 PyErr_NoMemory();
935 goto exit;
936 }
937 }
938 /* copy buf to mybuf, adding exponent, sign and leading 0 */
939 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
940 buf, decpt - (int)buflen);
941
942 /* and convert the resulting string back to a double */
943 errno = 0;
944 rounded = _Py_dg_strtod(mybuf, NULL);
945 if (errno == ERANGE && fabs(rounded) >= 1.)
946 PyErr_SetString(PyExc_OverflowError,
947 "rounded value too large to represent");
948 else
949 result = PyFloat_FromDouble(rounded);
950
951 /* done computing value; now clean up */
952 if (mybuf != shortbuf)
953 PyMem_Free(mybuf);
954 exit:
955 _Py_dg_freedtoa(buf);
956 return result;
957}
958
959#else /* PY_NO_SHORT_FLOAT_REPR */
960
961/* fallback version, to be used when correctly rounded binary<->decimal
962 conversions aren't available */
963
964static PyObject *
965double_round(double x, int ndigits) {
966 double pow1, pow2, y, z;
967 if (ndigits >= 0) {
968 if (ndigits > 22) {
969 /* pow1 and pow2 are each safe from overflow, but
970 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
971 pow1 = pow(10.0, (double)(ndigits-22));
972 pow2 = 1e22;
973 }
974 else {
975 pow1 = pow(10.0, (double)ndigits);
976 pow2 = 1.0;
977 }
978 y = (x*pow1)*pow2;
979 /* if y overflows, then rounded value is exactly x */
980 if (!Py_IS_FINITE(y))
981 return PyFloat_FromDouble(x);
982 }
983 else {
984 pow1 = pow(10.0, (double)-ndigits);
985 pow2 = 1.0; /* unused; silences a gcc compiler warning */
986 y = x / pow1;
987 }
988
989 z = round(y);
990 if (fabs(y-z) == 0.5)
991 /* halfway between two integers; use round-half-even */
992 z = 2.0*round(y/2.0);
993
994 if (ndigits >= 0)
995 z = (z / pow2) / pow1;
996 else
997 z *= pow1;
998
999 /* if computation resulted in overflow, raise OverflowError */
1000 if (!Py_IS_FINITE(z)) {
1001 PyErr_SetString(PyExc_OverflowError,
1002 "overflow occurred during round");
1003 return NULL;
1004 }
1005
1006 return PyFloat_FromDouble(z);
1007}
1008
1009#endif /* PY_NO_SHORT_FLOAT_REPR */
1010
1011/* round a Python float v to the closest multiple of 10**-ndigits */
1012
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001014float_round(PyObject *v, PyObject *args)
1015{
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001016 double x, rounded;
1017 PyObject *o_ndigits = NULL;
1018 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001019
1020 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001021 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
1022 return NULL;
1023 if (o_ndigits == NULL) {
1024 /* single-argument round: round to nearest integer */
1025 rounded = round(x);
1026 if (fabs(x-rounded) == 0.5)
1027 /* halfway case: round to even */
1028 rounded = 2.0*round(x/2.0);
1029 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001030 }
1031
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001032 /* interpret second argument as a Py_ssize_t; clips on overflow */
1033 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
1034 if (ndigits == -1 && PyErr_Occurred())
1035 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001036
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001037 /* nans and infinities round to themselves */
1038 if (!Py_IS_FINITE(x))
1039 return PyFloat_FromDouble(x);
1040
1041 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1042 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1043 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
1044#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1045#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
1046 if (ndigits > NDIGITS_MAX)
1047 /* return x */
1048 return PyFloat_FromDouble(x);
1049 else if (ndigits < NDIGITS_MIN)
1050 /* return 0.0, but with sign of x */
1051 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001052 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001053 /* finite x, and ndigits is not unreasonably large */
1054 return double_round(x, (int)ndigits);
1055#undef NDIGITS_MAX
1056#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001057}
1058
1059static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001060float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001061{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001062 if (PyFloat_CheckExact(v))
1063 Py_INCREF(v);
1064 else
1065 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001066 return v;
1067}
1068
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001069/* turn ASCII hex characters into integer values and vice versa */
1070
1071static char
1072char_from_hex(int x)
1073{
1074 assert(0 <= x && x < 16);
1075 return "0123456789abcdef"[x];
1076}
1077
1078static int
1079hex_from_char(char c) {
1080 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001081 switch(c) {
1082 case '0':
1083 x = 0;
1084 break;
1085 case '1':
1086 x = 1;
1087 break;
1088 case '2':
1089 x = 2;
1090 break;
1091 case '3':
1092 x = 3;
1093 break;
1094 case '4':
1095 x = 4;
1096 break;
1097 case '5':
1098 x = 5;
1099 break;
1100 case '6':
1101 x = 6;
1102 break;
1103 case '7':
1104 x = 7;
1105 break;
1106 case '8':
1107 x = 8;
1108 break;
1109 case '9':
1110 x = 9;
1111 break;
1112 case 'a':
1113 case 'A':
1114 x = 10;
1115 break;
1116 case 'b':
1117 case 'B':
1118 x = 11;
1119 break;
1120 case 'c':
1121 case 'C':
1122 x = 12;
1123 break;
1124 case 'd':
1125 case 'D':
1126 x = 13;
1127 break;
1128 case 'e':
1129 case 'E':
1130 x = 14;
1131 break;
1132 case 'f':
1133 case 'F':
1134 x = 15;
1135 break;
1136 default:
1137 x = -1;
1138 break;
1139 }
1140 return x;
1141}
1142
1143/* convert a float to a hexadecimal string */
1144
1145/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1146 of the form 4k+1. */
1147#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1148
1149static PyObject *
1150float_hex(PyObject *v)
1151{
1152 double x, m;
1153 int e, shift, i, si, esign;
1154 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1155 trailing NUL byte. */
1156 char s[(TOHEX_NBITS-1)/4+3];
1157
1158 CONVERT_TO_DOUBLE(v, x);
1159
1160 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1161 return float_str((PyFloatObject *)v);
1162
1163 if (x == 0.0) {
1164 if(copysign(1.0, x) == -1.0)
1165 return PyUnicode_FromString("-0x0.0p+0");
1166 else
1167 return PyUnicode_FromString("0x0.0p+0");
1168 }
1169
1170 m = frexp(fabs(x), &e);
1171 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1172 m = ldexp(m, shift);
1173 e -= shift;
1174
1175 si = 0;
1176 s[si] = char_from_hex((int)m);
1177 si++;
1178 m -= (int)m;
1179 s[si] = '.';
1180 si++;
1181 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1182 m *= 16.0;
1183 s[si] = char_from_hex((int)m);
1184 si++;
1185 m -= (int)m;
1186 }
1187 s[si] = '\0';
1188
1189 if (e < 0) {
1190 esign = (int)'-';
1191 e = -e;
1192 }
1193 else
1194 esign = (int)'+';
1195
1196 if (x < 0.0)
1197 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1198 else
1199 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1200}
1201
1202PyDoc_STRVAR(float_hex_doc,
1203"float.hex() -> string\n\
1204\n\
1205Return a hexadecimal representation of a floating-point number.\n\
1206>>> (-0.1).hex()\n\
1207'-0x1.999999999999ap-4'\n\
1208>>> 3.14159.hex()\n\
1209'0x1.921f9f01b866ep+1'");
1210
1211/* Convert a hexadecimal string to a float. */
1212
1213static PyObject *
1214float_fromhex(PyObject *cls, PyObject *arg)
1215{
1216 PyObject *result_as_float, *result;
1217 double x;
1218 long exp, top_exp, lsb, key_digit;
1219 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1220 int half_eps, digit, round_up, sign=1;
1221 Py_ssize_t length, ndigits, fdigits, i;
1222
1223 /*
1224 * For the sake of simplicity and correctness, we impose an artificial
1225 * limit on ndigits, the total number of hex digits in the coefficient
1226 * The limit is chosen to ensure that, writing exp for the exponent,
1227 *
1228 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1229 * guaranteed to overflow (provided it's nonzero)
1230 *
1231 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1232 * guaranteed to underflow to 0.
1233 *
1234 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1235 * overflow in the calculation of exp and top_exp below.
1236 *
1237 * More specifically, ndigits is assumed to satisfy the following
1238 * inequalities:
1239 *
1240 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1241 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1242 *
1243 * If either of these inequalities is not satisfied, a ValueError is
1244 * raised. Otherwise, write x for the value of the hex string, and
1245 * assume x is nonzero. Then
1246 *
1247 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1248 *
1249 * Now if exp > LONG_MAX/2 then:
1250 *
1251 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1252 * = DBL_MAX_EXP
1253 *
1254 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1255 * double, so overflows. If exp < LONG_MIN/2, then
1256 *
1257 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1258 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1259 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1260 *
1261 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1262 * when converted to a C double.
1263 *
1264 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1265 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1266 */
1267
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001268 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001269 if (s == NULL)
1270 return NULL;
1271 s_end = s + length;
1272
1273 /********************
1274 * Parse the string *
1275 ********************/
1276
1277 /* leading whitespace and optional sign */
Kristján Valur Jónssonbaa45462008-12-18 17:08:57 +00001278 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001279 s++;
1280 if (*s == '-') {
1281 s++;
1282 sign = -1;
1283 }
1284 else if (*s == '+')
1285 s++;
1286
1287 /* infinities and nans */
Andrew MacIntyre45612572008-09-22 14:49:01 +00001288 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001289 x = Py_NAN;
1290 goto finished;
1291 }
Andrew MacIntyre45612572008-09-22 14:49:01 +00001292 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1293 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001294 x = sign*Py_HUGE_VAL;
1295 goto finished;
1296 }
1297
1298 /* [0x] */
1299 s_store = s;
1300 if (*s == '0') {
1301 s++;
1302 if (tolower(*s) == (int)'x')
1303 s++;
1304 else
1305 s = s_store;
1306 }
1307
1308 /* coefficient: <integer> [. <fraction>] */
1309 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001310 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001311 s++;
1312 s_store = s;
1313 if (*s == '.') {
1314 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001315 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001316 s++;
1317 coeff_end = s-1;
1318 }
1319 else
1320 coeff_end = s;
1321
1322 /* ndigits = total # of hex digits; fdigits = # after point */
1323 ndigits = coeff_end - coeff_start;
1324 fdigits = coeff_end - s_store;
1325 if (ndigits == 0)
1326 goto parse_error;
1327 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1328 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1329 goto insane_length_error;
1330
1331 /* [p <exponent>] */
1332 if (tolower(*s) == (int)'p') {
1333 s++;
1334 exp_start = s;
1335 if (*s == '-' || *s == '+')
1336 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001337 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338 goto parse_error;
1339 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001340 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341 s++;
1342 exp = strtol(exp_start, NULL, 10);
1343 }
1344 else
1345 exp = 0;
1346
1347 /* optional trailing whitespace leading to the end of the string */
Kristján Valur Jónssonbaa45462008-12-18 17:08:57 +00001348 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001349 s++;
1350 if (s != s_end)
1351 goto parse_error;
1352
1353/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1354#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1355 coeff_end-(j) : \
1356 coeff_end-1-(j)))
1357
1358 /*******************************************
1359 * Compute rounded value of the hex string *
1360 *******************************************/
1361
1362 /* Discard leading zeros, and catch extreme overflow and underflow */
1363 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1364 ndigits--;
1365 if (ndigits == 0 || exp < LONG_MIN/2) {
1366 x = sign * 0.0;
1367 goto finished;
1368 }
1369 if (exp > LONG_MAX/2)
1370 goto overflow_error;
1371
1372 /* Adjust exponent for fractional part. */
1373 exp = exp - 4*((long)fdigits);
1374
1375 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1376 top_exp = exp + 4*((long)ndigits - 1);
1377 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1378 top_exp++;
1379
1380 /* catch almost all nonextreme cases of overflow and underflow here */
1381 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1382 x = sign * 0.0;
1383 goto finished;
1384 }
1385 if (top_exp > DBL_MAX_EXP)
1386 goto overflow_error;
1387
1388 /* lsb = exponent of least significant bit of the *rounded* value.
1389 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1390 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1391
1392 x = 0.0;
1393 if (exp >= lsb) {
1394 /* no rounding required */
1395 for (i = ndigits-1; i >= 0; i--)
1396 x = 16.0*x + HEX_DIGIT(i);
1397 x = sign * ldexp(x, (int)(exp));
1398 goto finished;
1399 }
1400 /* rounding required. key_digit is the index of the hex digit
1401 containing the first bit to be rounded away. */
1402 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1403 key_digit = (lsb - exp - 1) / 4;
1404 for (i = ndigits-1; i > key_digit; i--)
1405 x = 16.0*x + HEX_DIGIT(i);
1406 digit = HEX_DIGIT(key_digit);
1407 x = 16.0*x + (double)(digit & (16-2*half_eps));
1408
1409 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1410 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1411 if ((digit & half_eps) != 0) {
1412 round_up = 0;
1413 if ((digit & (3*half_eps-1)) != 0 ||
1414 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1415 round_up = 1;
1416 else
1417 for (i = key_digit-1; i >= 0; i--)
1418 if (HEX_DIGIT(i) != 0) {
1419 round_up = 1;
1420 break;
1421 }
1422 if (round_up == 1) {
1423 x += 2*half_eps;
1424 if (top_exp == DBL_MAX_EXP &&
1425 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1426 /* overflow corner case: pre-rounded value <
1427 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1428 goto overflow_error;
1429 }
1430 }
1431 x = sign * ldexp(x, (int)(exp+4*key_digit));
1432
1433 finished:
1434 result_as_float = Py_BuildValue("(d)", x);
1435 if (result_as_float == NULL)
1436 return NULL;
1437 result = PyObject_CallObject(cls, result_as_float);
1438 Py_DECREF(result_as_float);
1439 return result;
1440
1441 overflow_error:
1442 PyErr_SetString(PyExc_OverflowError,
1443 "hexadecimal value too large to represent as a float");
1444 return NULL;
1445
1446 parse_error:
1447 PyErr_SetString(PyExc_ValueError,
1448 "invalid hexadecimal floating-point string");
1449 return NULL;
1450
1451 insane_length_error:
1452 PyErr_SetString(PyExc_ValueError,
1453 "hexadecimal string too long to convert");
1454 return NULL;
1455}
1456
1457PyDoc_STRVAR(float_fromhex_doc,
1458"float.fromhex(string) -> float\n\
1459\n\
1460Create a floating-point number from a hexadecimal string.\n\
1461>>> float.fromhex('0x1.ffffp10')\n\
14622047.984375\n\
1463>>> float.fromhex('-0x1p-1074')\n\
1464-4.9406564584124654e-324");
1465
1466
Christian Heimes26855632008-01-27 23:50:43 +00001467static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001468float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001469{
1470 double self;
1471 double float_part;
1472 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001473 int i;
1474
Christian Heimes26855632008-01-27 23:50:43 +00001475 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001476 PyObject *py_exponent = NULL;
1477 PyObject *numerator = NULL;
1478 PyObject *denominator = NULL;
1479 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001480 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001481
1482#define INPLACE_UPDATE(obj, call) \
1483 prev = obj; \
1484 obj = call; \
1485 Py_DECREF(prev); \
1486
1487 CONVERT_TO_DOUBLE(v, self);
1488
1489 if (Py_IS_INFINITY(self)) {
1490 PyErr_SetString(PyExc_OverflowError,
1491 "Cannot pass infinity to float.as_integer_ratio.");
1492 return NULL;
1493 }
1494#ifdef Py_NAN
1495 if (Py_IS_NAN(self)) {
1496 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001497 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001498 return NULL;
1499 }
1500#endif
1501
Christian Heimes26855632008-01-27 23:50:43 +00001502 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001503 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001504 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001505
1506 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1507 float_part *= 2.0;
1508 exponent--;
1509 }
1510 /* self == float_part * 2**exponent exactly and float_part is integral.
1511 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1512 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001513
Christian Heimes292d3512008-02-03 16:51:08 +00001514 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001515 if (numerator == NULL) goto error;
1516
Christian Heimes292d3512008-02-03 16:51:08 +00001517 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001518 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001519 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001520 if (py_exponent == NULL) goto error;
1521 INPLACE_UPDATE(py_exponent,
1522 long_methods->nb_lshift(denominator, py_exponent));
1523 if (py_exponent == NULL) goto error;
1524 if (exponent > 0) {
1525 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001526 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001527 if (numerator == NULL) goto error;
1528 }
1529 else {
1530 Py_DECREF(denominator);
1531 denominator = py_exponent;
1532 py_exponent = NULL;
1533 }
1534
1535 result_pair = PyTuple_Pack(2, numerator, denominator);
1536
1537#undef INPLACE_UPDATE
1538error:
1539 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001540 Py_XDECREF(denominator);
1541 Py_XDECREF(numerator);
1542 return result_pair;
1543}
1544
1545PyDoc_STRVAR(float_as_integer_ratio_doc,
1546"float.as_integer_ratio() -> (int, int)\n"
1547"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001548"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1549"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001550"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001551"\n"
1552">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001553"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001554">>> (0.0).as_integer_ratio()\n"
1555"(0, 1)\n"
1556">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001557"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001558
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001559
Jeremy Hylton938ace62002-07-17 16:30:39 +00001560static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001561float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1562
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563static PyObject *
1564float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1565{
1566 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001567 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568
Guido van Rossumbef14172001-08-29 15:47:46 +00001569 if (type != &PyFloat_Type)
1570 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1572 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001573 /* If it's a string, but not a string subclass, use
1574 PyFloat_FromString. */
1575 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001576 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 return PyNumber_Float(x);
1578}
1579
Guido van Rossumbef14172001-08-29 15:47:46 +00001580/* Wimpy, slow approach to tp_new calls for subtypes of float:
1581 first create a regular float from whatever arguments we got,
1582 then allocate a subtype instance and initialize its ob_fval
1583 from the regular float. The regular float is then thrown away.
1584*/
1585static PyObject *
1586float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1587{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001588 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001589
1590 assert(PyType_IsSubtype(type, &PyFloat_Type));
1591 tmp = float_new(&PyFloat_Type, args, kwds);
1592 if (tmp == NULL)
1593 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001594 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001595 newobj = type->tp_alloc(type, 0);
1596 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001597 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001598 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001599 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001600 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001601 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001602 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001603}
1604
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001605static PyObject *
1606float_getnewargs(PyFloatObject *v)
1607{
1608 return Py_BuildValue("(d)", v->ob_fval);
1609}
1610
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611/* this is for the benefit of the pack/unpack routines below */
1612
1613typedef enum {
1614 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1615} float_format_type;
1616
1617static float_format_type double_format, float_format;
1618static float_format_type detected_double_format, detected_float_format;
1619
1620static PyObject *
1621float_getformat(PyTypeObject *v, PyObject* arg)
1622{
1623 char* s;
1624 float_format_type r;
1625
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001626 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001627 PyErr_Format(PyExc_TypeError,
1628 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001629 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001630 return NULL;
1631 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001632 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001633 if (s == NULL)
1634 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001635 if (strcmp(s, "double") == 0) {
1636 r = double_format;
1637 }
1638 else if (strcmp(s, "float") == 0) {
1639 r = float_format;
1640 }
1641 else {
1642 PyErr_SetString(PyExc_ValueError,
1643 "__getformat__() argument 1 must be "
1644 "'double' or 'float'");
1645 return NULL;
1646 }
1647
1648 switch (r) {
1649 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001650 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001652 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001653 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001654 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655 default:
1656 Py_FatalError("insane float_format or double_format");
1657 return NULL;
1658 }
1659}
1660
1661PyDoc_STRVAR(float_getformat_doc,
1662"float.__getformat__(typestr) -> string\n"
1663"\n"
1664"You probably don't want to use this function. It exists mainly to be\n"
1665"used in Python's test suite.\n"
1666"\n"
1667"typestr must be 'double' or 'float'. This function returns whichever of\n"
1668"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1669"format of floating point numbers used by the C type named by typestr.");
1670
1671static PyObject *
1672float_setformat(PyTypeObject *v, PyObject* args)
1673{
1674 char* typestr;
1675 char* format;
1676 float_format_type f;
1677 float_format_type detected;
1678 float_format_type *p;
1679
1680 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1681 return NULL;
1682
1683 if (strcmp(typestr, "double") == 0) {
1684 p = &double_format;
1685 detected = detected_double_format;
1686 }
1687 else if (strcmp(typestr, "float") == 0) {
1688 p = &float_format;
1689 detected = detected_float_format;
1690 }
1691 else {
1692 PyErr_SetString(PyExc_ValueError,
1693 "__setformat__() argument 1 must "
1694 "be 'double' or 'float'");
1695 return NULL;
1696 }
1697
1698 if (strcmp(format, "unknown") == 0) {
1699 f = unknown_format;
1700 }
1701 else if (strcmp(format, "IEEE, little-endian") == 0) {
1702 f = ieee_little_endian_format;
1703 }
1704 else if (strcmp(format, "IEEE, big-endian") == 0) {
1705 f = ieee_big_endian_format;
1706 }
1707 else {
1708 PyErr_SetString(PyExc_ValueError,
1709 "__setformat__() argument 2 must be "
1710 "'unknown', 'IEEE, little-endian' or "
1711 "'IEEE, big-endian'");
1712 return NULL;
1713
1714 }
1715
1716 if (f != unknown_format && f != detected) {
1717 PyErr_Format(PyExc_ValueError,
1718 "can only set %s format to 'unknown' or the "
1719 "detected platform value", typestr);
1720 return NULL;
1721 }
1722
1723 *p = f;
1724 Py_RETURN_NONE;
1725}
1726
1727PyDoc_STRVAR(float_setformat_doc,
1728"float.__setformat__(typestr, fmt) -> None\n"
1729"\n"
1730"You probably don't want to use this function. It exists mainly to be\n"
1731"used in Python's test suite.\n"
1732"\n"
1733"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1734"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1735"one of the latter two if it appears to match the underlying C reality.\n"
1736"\n"
1737"Overrides the automatic determination of C-level floating point type.\n"
1738"This affects how floats are converted to and from binary strings.");
1739
Guido van Rossumb43daf72007-08-01 18:08:08 +00001740static PyObject *
1741float_getzero(PyObject *v, void *closure)
1742{
1743 return PyFloat_FromDouble(0.0);
1744}
1745
Eric Smith8c663262007-08-25 02:26:07 +00001746static PyObject *
1747float__format__(PyObject *self, PyObject *args)
1748{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001749 PyObject *format_spec;
1750
1751 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1752 return NULL;
1753 return _PyFloat_FormatAdvanced(self,
1754 PyUnicode_AS_UNICODE(format_spec),
1755 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001756}
1757
1758PyDoc_STRVAR(float__format__doc,
1759"float.__format__(format_spec) -> string\n"
1760"\n"
1761"Formats the float according to format_spec.");
1762
1763
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001764static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001765 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001766 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001767 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1768 "Returns the Integral closest to x between 0 and x."},
1769 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1770 "Returns the Integral closest to x, rounding half toward even.\n"
1771 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001772 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1773 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001774 {"fromhex", (PyCFunction)float_fromhex,
1775 METH_O|METH_CLASS, float_fromhex_doc},
1776 {"hex", (PyCFunction)float_hex,
1777 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001778 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1779 "Returns True if the float is an integer."},
1780#if 0
1781 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1782 "Returns True if the float is positive or negative infinite."},
1783 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1784 "Returns True if the float is finite, neither infinite nor NaN."},
1785 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1786 "Returns True if the float is not a number (NaN)."},
1787#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001788 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001789 {"__getformat__", (PyCFunction)float_getformat,
1790 METH_O|METH_CLASS, float_getformat_doc},
1791 {"__setformat__", (PyCFunction)float_setformat,
1792 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001793 {"__format__", (PyCFunction)float__format__,
1794 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001795 {NULL, NULL} /* sentinel */
1796};
1797
Guido van Rossumb43daf72007-08-01 18:08:08 +00001798static PyGetSetDef float_getset[] = {
1799 {"real",
1800 (getter)float_float, (setter)NULL,
1801 "the real part of a complex number",
1802 NULL},
1803 {"imag",
1804 (getter)float_getzero, (setter)NULL,
1805 "the imaginary part of a complex number",
1806 NULL},
1807 {NULL} /* Sentinel */
1808};
1809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001810PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811"float(x) -> floating point number\n\
1812\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001813Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814
1815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001816static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001817 float_add, /*nb_add*/
1818 float_sub, /*nb_subtract*/
1819 float_mul, /*nb_multiply*/
1820 float_rem, /*nb_remainder*/
1821 float_divmod, /*nb_divmod*/
1822 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001823 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001824 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001825 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001826 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001827 0, /*nb_invert*/
1828 0, /*nb_lshift*/
1829 0, /*nb_rshift*/
1830 0, /*nb_and*/
1831 0, /*nb_xor*/
1832 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001833 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001834 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001835 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001836 0, /* nb_inplace_add */
1837 0, /* nb_inplace_subtract */
1838 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001839 0, /* nb_inplace_remainder */
1840 0, /* nb_inplace_power */
1841 0, /* nb_inplace_lshift */
1842 0, /* nb_inplace_rshift */
1843 0, /* nb_inplace_and */
1844 0, /* nb_inplace_xor */
1845 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001846 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001847 float_div, /* nb_true_divide */
1848 0, /* nb_inplace_floor_divide */
1849 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001850};
1851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001853 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001855 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001858 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 0, /* tp_getattr */
1860 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001861 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862 (reprfunc)float_repr, /* tp_repr */
1863 &float_as_number, /* tp_as_number */
1864 0, /* tp_as_sequence */
1865 0, /* tp_as_mapping */
1866 (hashfunc)float_hash, /* tp_hash */
1867 0, /* tp_call */
1868 (reprfunc)float_str, /* tp_str */
1869 PyObject_GenericGetAttr, /* tp_getattro */
1870 0, /* tp_setattro */
1871 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001872 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873 float_doc, /* tp_doc */
1874 0, /* tp_traverse */
1875 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001876 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877 0, /* tp_weaklistoffset */
1878 0, /* tp_iter */
1879 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001880 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001882 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001883 0, /* tp_base */
1884 0, /* tp_dict */
1885 0, /* tp_descr_get */
1886 0, /* tp_descr_set */
1887 0, /* tp_dictoffset */
1888 0, /* tp_init */
1889 0, /* tp_alloc */
1890 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001891};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001892
1893void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001894_PyFloat_Init(void)
1895{
1896 /* We attempt to determine if this machine is using IEEE
1897 floating point formats by peering at the bits of some
1898 carefully chosen values. If it looks like we are on an
1899 IEEE platform, the float packing/unpacking routines can
1900 just copy bits, if not they resort to arithmetic & shifts
1901 and masks. The shifts & masks approach works on all finite
1902 values, but what happens to infinities, NaNs and signed
1903 zeroes on packing is an accident, and attempting to unpack
1904 a NaN or an infinity will raise an exception.
1905
1906 Note that if we're on some whacked-out platform which uses
1907 IEEE formats but isn't strictly little-endian or big-
1908 endian, we will fall back to the portable shifts & masks
1909 method. */
1910
1911#if SIZEOF_DOUBLE == 8
1912 {
1913 double x = 9006104071832581.0;
1914 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1915 detected_double_format = ieee_big_endian_format;
1916 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1917 detected_double_format = ieee_little_endian_format;
1918 else
1919 detected_double_format = unknown_format;
1920 }
1921#else
1922 detected_double_format = unknown_format;
1923#endif
1924
1925#if SIZEOF_FLOAT == 4
1926 {
1927 float y = 16711938.0;
1928 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1929 detected_float_format = ieee_big_endian_format;
1930 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1931 detected_float_format = ieee_little_endian_format;
1932 else
1933 detected_float_format = unknown_format;
1934 }
1935#else
1936 detected_float_format = unknown_format;
1937#endif
1938
1939 double_format = detected_double_format;
1940 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001941
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001942 /* Init float info */
1943 if (FloatInfoType.tp_name == 0)
1944 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001945}
1946
Georg Brandl2ee470f2008-07-16 12:55:28 +00001947int
1948PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001949{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001950 PyFloatObject *p;
1951 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001952 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001953 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001954 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001955
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001956 list = block_list;
1957 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001958 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001959 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001960 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001961 for (i = 0, p = &list->objects[0];
1962 i < N_FLOATOBJECTS;
1963 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001964 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001965 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001966 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001967 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001968 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001969 list->next = block_list;
1970 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001971 for (i = 0, p = &list->objects[0];
1972 i < N_FLOATOBJECTS;
1973 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001974 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001975 Py_REFCNT(p) == 0) {
1976 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001977 free_list;
1978 free_list = p;
1979 }
1980 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001981 }
1982 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001983 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001984 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001985 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001986 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001987 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001988 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001989}
1990
1991void
1992PyFloat_Fini(void)
1993{
1994 PyFloatObject *p;
1995 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001996 int i;
1997 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001998
Georg Brandl2ee470f2008-07-16 12:55:28 +00001999 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00002000
Guido van Rossum3fce8831999-03-12 19:43:17 +00002001 if (!Py_VerboseFlag)
2002 return;
2003 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00002004 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002005 fprintf(stderr, "\n");
2006 }
2007 else {
2008 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00002009 ": %d unfreed float%s\n",
2010 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002011 }
2012 if (Py_VerboseFlag > 1) {
2013 list = block_list;
2014 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002015 for (i = 0, p = &list->objects[0];
2016 i < N_FLOATOBJECTS;
2017 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002018 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00002019 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00002020 char *buf = PyOS_double_to_string(
2021 PyFloat_AS_DOUBLE(p), 'r',
2022 0, 0, NULL);
2023 if (buf) {
2024 /* XXX(twouters) cast
2025 refcount to long
2026 until %zd is
2027 universally
2028 available
2029 */
2030 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002031 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00002032 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00002033 PyMem_Free(buf);
2034 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002035 }
2036 }
2037 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002038 }
2039 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002040}
Tim Peters9905b942003-03-20 20:53:32 +00002041
2042/*----------------------------------------------------------------------------
2043 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002044 */
2045int
2046_PyFloat_Pack4(double x, unsigned char *p, int le)
2047{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002048 if (float_format == unknown_format) {
2049 unsigned char sign;
2050 int e;
2051 double f;
2052 unsigned int fbits;
2053 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002054
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002055 if (le) {
2056 p += 3;
2057 incr = -1;
2058 }
Tim Peters9905b942003-03-20 20:53:32 +00002059
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002060 if (x < 0) {
2061 sign = 1;
2062 x = -x;
2063 }
2064 else
2065 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002066
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002067 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002068
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002069 /* Normalize f to be in the range [1.0, 2.0) */
2070 if (0.5 <= f && f < 1.0) {
2071 f *= 2.0;
2072 e--;
2073 }
2074 else if (f == 0.0)
2075 e = 0;
2076 else {
2077 PyErr_SetString(PyExc_SystemError,
2078 "frexp() result out of range");
2079 return -1;
2080 }
2081
2082 if (e >= 128)
2083 goto Overflow;
2084 else if (e < -126) {
2085 /* Gradual underflow */
2086 f = ldexp(f, 126 + e);
2087 e = 0;
2088 }
2089 else if (!(e == 0 && f == 0.0)) {
2090 e += 127;
2091 f -= 1.0; /* Get rid of leading 1 */
2092 }
2093
2094 f *= 8388608.0; /* 2**23 */
2095 fbits = (unsigned int)(f + 0.5); /* Round */
2096 assert(fbits <= 8388608);
2097 if (fbits >> 23) {
2098 /* The carry propagated out of a string of 23 1 bits. */
2099 fbits = 0;
2100 ++e;
2101 if (e >= 255)
2102 goto Overflow;
2103 }
2104
2105 /* First byte */
2106 *p = (sign << 7) | (e >> 1);
2107 p += incr;
2108
2109 /* Second byte */
2110 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2111 p += incr;
2112
2113 /* Third byte */
2114 *p = (fbits >> 8) & 0xFF;
2115 p += incr;
2116
2117 /* Fourth byte */
2118 *p = fbits & 0xFF;
2119
2120 /* Done */
2121 return 0;
2122
Tim Peters9905b942003-03-20 20:53:32 +00002123 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002125 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002126 const char *s = (char*)&y;
2127 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002128
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002129 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2130 goto Overflow;
2131
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002132 if ((float_format == ieee_little_endian_format && !le)
2133 || (float_format == ieee_big_endian_format && le)) {
2134 p += 3;
2135 incr = -1;
2136 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002137
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138 for (i = 0; i < 4; i++) {
2139 *p = *s++;
2140 p += incr;
2141 }
2142 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002143 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002144 Overflow:
2145 PyErr_SetString(PyExc_OverflowError,
2146 "float too large to pack with f format");
2147 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002148}
2149
2150int
2151_PyFloat_Pack8(double x, unsigned char *p, int le)
2152{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002153 if (double_format == unknown_format) {
2154 unsigned char sign;
2155 int e;
2156 double f;
2157 unsigned int fhi, flo;
2158 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002159
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002160 if (le) {
2161 p += 7;
2162 incr = -1;
2163 }
Tim Peters9905b942003-03-20 20:53:32 +00002164
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002165 if (x < 0) {
2166 sign = 1;
2167 x = -x;
2168 }
2169 else
2170 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002171
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002172 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002173
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002174 /* Normalize f to be in the range [1.0, 2.0) */
2175 if (0.5 <= f && f < 1.0) {
2176 f *= 2.0;
2177 e--;
2178 }
2179 else if (f == 0.0)
2180 e = 0;
2181 else {
2182 PyErr_SetString(PyExc_SystemError,
2183 "frexp() result out of range");
2184 return -1;
2185 }
2186
2187 if (e >= 1024)
2188 goto Overflow;
2189 else if (e < -1022) {
2190 /* Gradual underflow */
2191 f = ldexp(f, 1022 + e);
2192 e = 0;
2193 }
2194 else if (!(e == 0 && f == 0.0)) {
2195 e += 1023;
2196 f -= 1.0; /* Get rid of leading 1 */
2197 }
2198
2199 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2200 f *= 268435456.0; /* 2**28 */
2201 fhi = (unsigned int)f; /* Truncate */
2202 assert(fhi < 268435456);
2203
2204 f -= (double)fhi;
2205 f *= 16777216.0; /* 2**24 */
2206 flo = (unsigned int)(f + 0.5); /* Round */
2207 assert(flo <= 16777216);
2208 if (flo >> 24) {
2209 /* The carry propagated out of a string of 24 1 bits. */
2210 flo = 0;
2211 ++fhi;
2212 if (fhi >> 28) {
2213 /* And it also progagated out of the next 28 bits. */
2214 fhi = 0;
2215 ++e;
2216 if (e >= 2047)
2217 goto Overflow;
2218 }
2219 }
2220
2221 /* First byte */
2222 *p = (sign << 7) | (e >> 4);
2223 p += incr;
2224
2225 /* Second byte */
2226 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2227 p += incr;
2228
2229 /* Third byte */
2230 *p = (fhi >> 16) & 0xFF;
2231 p += incr;
2232
2233 /* Fourth byte */
2234 *p = (fhi >> 8) & 0xFF;
2235 p += incr;
2236
2237 /* Fifth byte */
2238 *p = fhi & 0xFF;
2239 p += incr;
2240
2241 /* Sixth byte */
2242 *p = (flo >> 16) & 0xFF;
2243 p += incr;
2244
2245 /* Seventh byte */
2246 *p = (flo >> 8) & 0xFF;
2247 p += incr;
2248
2249 /* Eighth byte */
2250 *p = flo & 0xFF;
2251 p += incr;
2252
2253 /* Done */
2254 return 0;
2255
2256 Overflow:
2257 PyErr_SetString(PyExc_OverflowError,
2258 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002259 return -1;
2260 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002261 else {
2262 const char *s = (char*)&x;
2263 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002264
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002265 if ((double_format == ieee_little_endian_format && !le)
2266 || (double_format == ieee_big_endian_format && le)) {
2267 p += 7;
2268 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002269 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002270
2271 for (i = 0; i < 8; i++) {
2272 *p = *s++;
2273 p += incr;
2274 }
2275 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002276 }
Tim Peters9905b942003-03-20 20:53:32 +00002277}
2278
2279double
2280_PyFloat_Unpack4(const unsigned char *p, int le)
2281{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002282 if (float_format == unknown_format) {
2283 unsigned char sign;
2284 int e;
2285 unsigned int f;
2286 double x;
2287 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002288
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002289 if (le) {
2290 p += 3;
2291 incr = -1;
2292 }
2293
2294 /* First byte */
2295 sign = (*p >> 7) & 1;
2296 e = (*p & 0x7F) << 1;
2297 p += incr;
2298
2299 /* Second byte */
2300 e |= (*p >> 7) & 1;
2301 f = (*p & 0x7F) << 16;
2302 p += incr;
2303
2304 if (e == 255) {
2305 PyErr_SetString(
2306 PyExc_ValueError,
2307 "can't unpack IEEE 754 special value "
2308 "on non-IEEE platform");
2309 return -1;
2310 }
2311
2312 /* Third byte */
2313 f |= *p << 8;
2314 p += incr;
2315
2316 /* Fourth byte */
2317 f |= *p;
2318
2319 x = (double)f / 8388608.0;
2320
2321 /* XXX This sadly ignores Inf/NaN issues */
2322 if (e == 0)
2323 e = -126;
2324 else {
2325 x += 1.0;
2326 e -= 127;
2327 }
2328 x = ldexp(x, e);
2329
2330 if (sign)
2331 x = -x;
2332
2333 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002334 }
Tim Peters9905b942003-03-20 20:53:32 +00002335 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002336 float x;
2337
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338 if ((float_format == ieee_little_endian_format && !le)
2339 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002340 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341 char *d = &buf[3];
2342 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002343
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002344 for (i = 0; i < 4; i++) {
2345 *d-- = *p++;
2346 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002347 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002348 }
2349 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002350 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002351 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002352
2353 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354 }
Tim Peters9905b942003-03-20 20:53:32 +00002355}
2356
2357double
2358_PyFloat_Unpack8(const unsigned char *p, int le)
2359{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360 if (double_format == unknown_format) {
2361 unsigned char sign;
2362 int e;
2363 unsigned int fhi, flo;
2364 double x;
2365 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002366
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002367 if (le) {
2368 p += 7;
2369 incr = -1;
2370 }
2371
2372 /* First byte */
2373 sign = (*p >> 7) & 1;
2374 e = (*p & 0x7F) << 4;
2375
2376 p += incr;
2377
2378 /* Second byte */
2379 e |= (*p >> 4) & 0xF;
2380 fhi = (*p & 0xF) << 24;
2381 p += incr;
2382
2383 if (e == 2047) {
2384 PyErr_SetString(
2385 PyExc_ValueError,
2386 "can't unpack IEEE 754 special value "
2387 "on non-IEEE platform");
2388 return -1.0;
2389 }
2390
2391 /* Third byte */
2392 fhi |= *p << 16;
2393 p += incr;
2394
2395 /* Fourth byte */
2396 fhi |= *p << 8;
2397 p += incr;
2398
2399 /* Fifth byte */
2400 fhi |= *p;
2401 p += incr;
2402
2403 /* Sixth byte */
2404 flo = *p << 16;
2405 p += incr;
2406
2407 /* Seventh byte */
2408 flo |= *p << 8;
2409 p += incr;
2410
2411 /* Eighth byte */
2412 flo |= *p;
2413
2414 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2415 x /= 268435456.0; /* 2**28 */
2416
2417 if (e == 0)
2418 e = -1022;
2419 else {
2420 x += 1.0;
2421 e -= 1023;
2422 }
2423 x = ldexp(x, e);
2424
2425 if (sign)
2426 x = -x;
2427
2428 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002429 }
Tim Peters9905b942003-03-20 20:53:32 +00002430 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002431 double x;
2432
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002433 if ((double_format == ieee_little_endian_format && !le)
2434 || (double_format == ieee_big_endian_format && le)) {
2435 char buf[8];
2436 char *d = &buf[7];
2437 int i;
2438
2439 for (i = 0; i < 8; i++) {
2440 *d-- = *p++;
2441 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002442 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002443 }
2444 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002445 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002446 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002447
2448 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002449 }
Tim Peters9905b942003-03-20 20:53:32 +00002450}