blob: 2ef4d1a865a1364e55523b99625f3d0f14e209b8 [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.
200 * However, strtod can return 0 for denormalized numbers, where atof
201 * does not. So (alas!) we special-case a zero result. Note that
202 * whether strtod sets errno on underflow is not defined, so we can't
203 * key off errno.
204 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000205 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000206 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000207 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000209 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000210 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000211 if (end > last)
212 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000213 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000214 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000215 char *p = (char*)sp;
216 int sign = 1;
217
218 if (*p == '-') {
219 sign = -1;
220 p++;
221 }
222 if (*p == '+') {
223 p++;
224 }
225 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000226 if (s_buffer != NULL)
227 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000228 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000229 }
Georg Brandl2ee470f2008-07-16 12:55:28 +0000230 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000231 if (s_buffer != NULL)
232 PyMem_FREE(s_buffer);
Georg Brandl2ee470f2008-07-16 12:55:28 +0000233 Py_RETURN_INF(sign);
234 }
Christian Heimes99170a52007-12-19 02:07:34 +0000235#ifdef Py_NAN
236 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000237 if (s_buffer != NULL)
238 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000239 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000240 }
241#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000242 PyOS_snprintf(buffer, sizeof(buffer),
243 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000244 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000245 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000246 }
247 /* Since end != s, the platform made *some* kind of sense out
248 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 while (*end && isspace(Py_CHARMASK(*end)))
250 end++;
251 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000252 PyOS_snprintf(buffer, sizeof(buffer),
253 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000254 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000255 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000256 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000257 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000258 PyErr_SetString(PyExc_ValueError,
259 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000260 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000261 }
Tim Petersef14d732000-09-23 03:39:17 +0000262 if (x == 0.0) {
263 /* See above -- may have been strtod being anal
264 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000265 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000266 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000267 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000268 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000269 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000270 result = PyFloat_FromDouble(x);
271 error:
272 if (s_buffer)
273 PyMem_FREE(s_buffer);
274 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000275}
276
Guido van Rossum234f9421993-06-17 12:35:49 +0000277static void
Fred Drakefd99de62000-07-09 05:02:18 +0000278float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000279{
Guido van Rossum9475a232001-10-05 20:51:39 +0000280 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000281 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000282 free_list = op;
283 }
284 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000285 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000286}
287
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288double
Fred Drakefd99de62000-07-09 05:02:18 +0000289PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000291 PyNumberMethods *nb;
292 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000293 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000294
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 if (op && PyFloat_Check(op))
296 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000297
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000298 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300 return -1;
301 }
Tim Petersd2364e82001-11-01 20:09:42 +0000302
Christian Heimes90aa7642007-12-19 02:45:37 +0000303 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000304 PyErr_SetString(PyExc_TypeError, "a float is required");
305 return -1;
306 }
307
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309 if (fo == NULL)
310 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311 if (!PyFloat_Check(fo)) {
312 PyErr_SetString(PyExc_TypeError,
313 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314 return -1;
315 }
Tim Petersd2364e82001-11-01 20:09:42 +0000316
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000317 val = PyFloat_AS_DOUBLE(fo);
318 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000319
Guido van Rossumb6775db1994-08-01 11:34:53 +0000320 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321}
322
323/* Methods */
324
Tim Peters97019e42001-11-28 22:43:45 +0000325static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000326format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000327{
328 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000329 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000330 int i;
331
332 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333 We want float numbers to be recognizable as such,
334 i.e., they should contain a decimal point or an exponent.
335 However, %g may print the number as an integer;
336 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000337
Martin v. Löwis737ea822004-06-08 18:52:54 +0000338 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000339 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340 cp = buf;
341 if (*cp == '-')
342 cp++;
343 for (; *cp != '\0'; cp++) {
344 /* Any non-digit means it's not an integer;
345 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000346 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 break;
348 }
349 if (*cp == '\0') {
350 *cp++ = '.';
351 *cp++ = '0';
352 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000353 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000354 }
Christian Heimes99170a52007-12-19 02:07:34 +0000355 /* Checking the next three chars should be more than enough to
356 * detect inf or nan, even on Windows. We check for inf or nan
357 * at last because they are rare cases.
358 */
359 for (i=0; *cp != '\0' && i<3; cp++, i++) {
360 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
361 continue;
362 /* found something that is neither a digit nor point
363 * it might be a NaN or INF
364 */
365#ifdef Py_NAN
366 if (Py_IS_NAN(ob_fval)) {
367 strcpy(buf, "nan");
368 }
369 else
370#endif
371 if (Py_IS_INFINITY(ob_fval)) {
372 cp = buf;
373 if (*cp == '-')
374 cp++;
375 strcpy(cp, "inf");
376 }
377 break;
378 }
379
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380}
381
Neal Norwitz545686b2006-12-28 04:45:06 +0000382static void
383format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000384{
Neal Norwitz545686b2006-12-28 04:45:06 +0000385 assert(PyFloat_Check(v));
386 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000387}
388
Neil Schemenauer32117e52001-01-04 01:44:34 +0000389/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000390 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000391 set to NULL, and the function invoking this macro returns NULL. If
392 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
393 stored in obj, and returned from the function invoking this macro.
394*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000395#define CONVERT_TO_DOUBLE(obj, dbl) \
396 if (PyFloat_Check(obj)) \
397 dbl = PyFloat_AS_DOUBLE(obj); \
398 else if (convert_to_double(&(obj), &(dbl)) < 0) \
399 return obj;
400
401static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000402convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000403{
404 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000405
Guido van Rossumddefaf32007-01-14 03:31:43 +0000406 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000407 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000408 if (*dbl == -1.0 && PyErr_Occurred()) {
409 *v = NULL;
410 return -1;
411 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000412 }
413 else {
414 Py_INCREF(Py_NotImplemented);
415 *v = Py_NotImplemented;
416 return -1;
417 }
418 return 0;
419}
420
Guido van Rossum57072eb1999-12-23 19:00:28 +0000421/* Precisions used by repr() and str(), respectively.
422
423 The repr() precision (17 significant decimal digits) is the minimal number
424 that is guaranteed to have enough precision so that if the number is read
425 back in the exact same binary value is recreated. This is true for IEEE
426 floating point by design, and also happens to work for all other modern
427 hardware.
428
429 The str() precision is chosen so that in most cases, the rounding noise
430 created by various operations is suppressed, while giving plenty of
431 precision for practical use.
432
433*/
434
435#define PREC_REPR 17
436#define PREC_STR 12
437
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000439float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440{
Christian Heimesb76922a2007-12-11 01:06:40 +0000441 char buf[100];
442 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesb76922a2007-12-11 01:06:40 +0000443
Walter Dörwald1ab83302007-05-18 17:15:44 +0000444 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000445}
446
447static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000448float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000449{
450 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000451 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000452 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453}
454
Tim Peters307fa782004-09-23 08:06:40 +0000455/* Comparison is pretty much a nightmare. When comparing float to float,
456 * we do it as straightforwardly (and long-windedly) as conceivable, so
457 * that, e.g., Python x == y delivers the same result as the platform
458 * C x == y when x and/or y is a NaN.
459 * When mixing float with an integer type, there's no good *uniform* approach.
460 * Converting the double to an integer obviously doesn't work, since we
461 * may lose info from fractional bits. Converting the integer to a double
462 * also has two failure modes: (1) a long int may trigger overflow (too
463 * large to fit in the dynamic range of a C double); (2) even a C long may have
464 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
465 * 63 bits of precision, but a C double probably has only 53), and then
466 * we can falsely claim equality when low-order integer bits are lost by
467 * coercion to double. So this part is painful too.
468 */
469
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000470static PyObject*
471float_richcompare(PyObject *v, PyObject *w, int op)
472{
473 double i, j;
474 int r = 0;
475
Tim Peters307fa782004-09-23 08:06:40 +0000476 assert(PyFloat_Check(v));
477 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000478
Tim Peters307fa782004-09-23 08:06:40 +0000479 /* Switch on the type of w. Set i and j to doubles to be compared,
480 * and op to the richcomp to use.
481 */
482 if (PyFloat_Check(w))
483 j = PyFloat_AS_DOUBLE(w);
484
Thomas Wouters477c8d52006-05-27 19:21:47 +0000485 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000486 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000487 /* If i is an infinity, its magnitude exceeds any
488 * finite integer, so it doesn't matter which int we
489 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000490 */
491 j = 0.0;
492 else
493 goto Unimplemented;
494 }
495
Tim Peters307fa782004-09-23 08:06:40 +0000496 else if (PyLong_Check(w)) {
497 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
498 int wsign = _PyLong_Sign(w);
499 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000500 int exponent;
501
502 if (vsign != wsign) {
503 /* Magnitudes are irrelevant -- the signs alone
504 * determine the outcome.
505 */
506 i = (double)vsign;
507 j = (double)wsign;
508 goto Compare;
509 }
510 /* The signs are the same. */
511 /* Convert w to a double if it fits. In particular, 0 fits. */
512 nbits = _PyLong_NumBits(w);
513 if (nbits == (size_t)-1 && PyErr_Occurred()) {
514 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000515 * to hold the # of bits. Replace with little doubles
516 * that give the same outcome -- w is so large that
517 * its magnitude must exceed the magnitude of any
518 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000519 */
520 PyErr_Clear();
521 i = (double)vsign;
522 assert(wsign != 0);
523 j = wsign * 2.0;
524 goto Compare;
525 }
526 if (nbits <= 48) {
527 j = PyLong_AsDouble(w);
528 /* It's impossible that <= 48 bits overflowed. */
529 assert(j != -1.0 || ! PyErr_Occurred());
530 goto Compare;
531 }
532 assert(wsign != 0); /* else nbits was 0 */
533 assert(vsign != 0); /* if vsign were 0, then since wsign is
534 * not 0, we would have taken the
535 * vsign != wsign branch at the start */
536 /* We want to work with non-negative numbers. */
537 if (vsign < 0) {
538 /* "Multiply both sides" by -1; this also swaps the
539 * comparator.
540 */
541 i = -i;
542 op = _Py_SwappedOp[op];
543 }
544 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000545 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000546 /* exponent is the # of bits in v before the radix point;
547 * we know that nbits (the # of bits in w) > 48 at this point
548 */
549 if (exponent < 0 || (size_t)exponent < nbits) {
550 i = 1.0;
551 j = 2.0;
552 goto Compare;
553 }
554 if ((size_t)exponent > nbits) {
555 i = 2.0;
556 j = 1.0;
557 goto Compare;
558 }
559 /* v and w have the same number of bits before the radix
560 * point. Construct two longs that have the same comparison
561 * outcome.
562 */
563 {
564 double fracpart;
565 double intpart;
566 PyObject *result = NULL;
567 PyObject *one = NULL;
568 PyObject *vv = NULL;
569 PyObject *ww = w;
570
571 if (wsign < 0) {
572 ww = PyNumber_Negative(w);
573 if (ww == NULL)
574 goto Error;
575 }
576 else
577 Py_INCREF(ww);
578
579 fracpart = modf(i, &intpart);
580 vv = PyLong_FromDouble(intpart);
581 if (vv == NULL)
582 goto Error;
583
584 if (fracpart != 0.0) {
585 /* Shift left, and or a 1 bit into vv
586 * to represent the lost fraction.
587 */
588 PyObject *temp;
589
Christian Heimes217cfd12007-12-02 14:31:20 +0000590 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000591 if (one == NULL)
592 goto Error;
593
594 temp = PyNumber_Lshift(ww, one);
595 if (temp == NULL)
596 goto Error;
597 Py_DECREF(ww);
598 ww = temp;
599
600 temp = PyNumber_Lshift(vv, one);
601 if (temp == NULL)
602 goto Error;
603 Py_DECREF(vv);
604 vv = temp;
605
606 temp = PyNumber_Or(vv, one);
607 if (temp == NULL)
608 goto Error;
609 Py_DECREF(vv);
610 vv = temp;
611 }
612
613 r = PyObject_RichCompareBool(vv, ww, op);
614 if (r < 0)
615 goto Error;
616 result = PyBool_FromLong(r);
617 Error:
618 Py_XDECREF(vv);
619 Py_XDECREF(ww);
620 Py_XDECREF(one);
621 return result;
622 }
623 } /* else if (PyLong_Check(w)) */
624
625 else /* w isn't float, int, or long */
626 goto Unimplemented;
627
628 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000629 PyFPE_START_PROTECT("richcompare", return NULL)
630 switch (op) {
631 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000632 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633 break;
634 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000635 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000636 break;
637 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000638 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000639 break;
640 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000641 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000642 break;
643 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000644 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000645 break;
646 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000647 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000648 break;
649 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000650 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000651 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000652
653 Unimplemented:
654 Py_INCREF(Py_NotImplemented);
655 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000656}
657
Guido van Rossum9bfef441993-03-29 10:43:31 +0000658static long
Fred Drakefd99de62000-07-09 05:02:18 +0000659float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000660{
Tim Peters39dce292000-08-15 03:34:48 +0000661 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000662}
663
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000664static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000665float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000666{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000667 double a,b;
668 CONVERT_TO_DOUBLE(v, a);
669 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000670 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000671 a = a + b;
672 PyFPE_END_PROTECT(a)
673 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674}
675
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679 double a,b;
680 CONVERT_TO_DOUBLE(v, a);
681 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000682 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000683 a = a - b;
684 PyFPE_END_PROTECT(a)
685 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686}
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000689float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000690{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000691 double a,b;
692 CONVERT_TO_DOUBLE(v, a);
693 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000694 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000695 a = a * b;
696 PyFPE_END_PROTECT(a)
697 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000698}
699
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000701float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000703 double a,b;
704 CONVERT_TO_DOUBLE(v, a);
705 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000706#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000707 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000708 PyErr_SetString(PyExc_ZeroDivisionError,
709 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000710 return NULL;
711 }
Christian Heimes53876d92008-04-19 00:31:39 +0000712#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000713 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000714 a = a / b;
715 PyFPE_END_PROTECT(a)
716 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000717}
718
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000719static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000720float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000722 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000723 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000724 CONVERT_TO_DOUBLE(v, vx);
725 CONVERT_TO_DOUBLE(w, wx);
726#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000728 PyErr_SetString(PyExc_ZeroDivisionError,
729 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730 return NULL;
731 }
Christian Heimes53876d92008-04-19 00:31:39 +0000732#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000733 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000734 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000735 /* note: checking mod*wx < 0 is incorrect -- underflows to
736 0 if wx < sqrt(smallest nonzero double) */
737 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000738 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000739 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000740 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000742}
743
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000745float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000746{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000747 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000748 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000749 CONVERT_TO_DOUBLE(v, vx);
750 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000751 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000753 return NULL;
754 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000755 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000756 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000757 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000758 exact multiple of wx. But this is fp arithmetic, and fp
759 vx - mod is an approximation; the result is that div may
760 not be an exact integral value after the division, although
761 it will always be very close to one.
762 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000763 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000764 if (mod) {
765 /* ensure the remainder has the same sign as the denominator */
766 if ((wx < 0) != (mod < 0)) {
767 mod += wx;
768 div -= 1.0;
769 }
770 }
771 else {
772 /* the remainder is zero, and in the presence of signed zeroes
773 fmod returns different results across platforms; ensure
774 it has the same sign as the denominator; we'd like to do
775 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000776 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000777 if (wx < 0.0)
778 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000779 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000780 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000781 if (div) {
782 floordiv = floor(div);
783 if (div - floordiv > 0.5)
784 floordiv += 1.0;
785 }
786 else {
787 /* div is zero - get the same sign as the true quotient */
788 div *= div; /* hide "div = +0" from optimizers */
789 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
790 }
791 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000792 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000793}
794
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000795static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000796float_floor_div(PyObject *v, PyObject *w)
797{
798 PyObject *t, *r;
799
800 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000801 if (t == NULL || t == Py_NotImplemented)
802 return t;
803 assert(PyTuple_CheckExact(t));
804 r = PyTuple_GET_ITEM(t, 0);
805 Py_INCREF(r);
806 Py_DECREF(t);
807 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000808}
809
810static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000811float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812{
813 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000814
815 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000816 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000817 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000818 return NULL;
819 }
820
Neil Schemenauer32117e52001-01-04 01:44:34 +0000821 CONVERT_TO_DOUBLE(v, iv);
822 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000823
824 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000825 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000826 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000827 }
Tim Peters96685bf2001-08-23 22:31:37 +0000828 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000829 if (iw < 0.0) {
830 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000831 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000832 return NULL;
833 }
834 return PyFloat_FromDouble(0.0);
835 }
Christian Heimes53876d92008-04-19 00:31:39 +0000836 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
837 return PyFloat_FromDouble(1.0);
838 }
Tim Peterse87568d2003-05-24 20:18:24 +0000839 if (iv < 0.0) {
840 /* Whether this is an error is a mess, and bumps into libm
841 * bugs so we have to figure it out ourselves.
842 */
843 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000844 /* Negative numbers raised to fractional powers
845 * become complex.
846 */
847 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000848 }
849 /* iw is an exact integer, albeit perhaps a very large one.
850 * -1 raised to an exact integer should never be exceptional.
851 * Alas, some libms (chiefly glibc as of early 2003) return
852 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
853 * happen to be representable in a *C* integer. That's a
854 * bug; we let that slide in math.pow() (which currently
855 * reflects all platform accidents), but not for Python's **.
856 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000857 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000858 /* Return 1 if iw is even, -1 if iw is odd; there's
859 * no guarantee that any C integral type is big
860 * enough to hold iw, so we have to check this
861 * indirectly.
862 */
863 ix = floor(iw * 0.5) * 2.0;
864 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
865 }
866 /* Else iv != -1.0, and overflow or underflow are possible.
867 * Unless we're to write pow() ourselves, we have to trust
868 * the platform to do this correctly.
869 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000870 }
Tim Peters96685bf2001-08-23 22:31:37 +0000871 errno = 0;
872 PyFPE_START_PROTECT("pow", return NULL)
873 ix = pow(iv, iw);
874 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000875 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000876 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000877 /* We don't expect any errno value other than ERANGE, but
878 * the range of libm bugs appears unbounded.
879 */
880 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
881 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000882 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000883 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000884 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000885}
886
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000887static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000888float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000890 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000891}
892
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000893static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000894float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000895{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000896 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000897}
898
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000899static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000900float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000901{
902 return v->ob_fval != 0.0;
903}
904
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000905static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000906float_is_integer(PyObject *v)
907{
908 double x = PyFloat_AsDouble(v);
909 PyObject *o;
910
911 if (x == -1.0 && PyErr_Occurred())
912 return NULL;
913 if (!Py_IS_FINITE(x))
914 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000915 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000916 PyFPE_START_PROTECT("is_integer", return NULL)
917 o = (floor(x) == x) ? Py_True : Py_False;
918 PyFPE_END_PROTECT(x)
919 if (errno != 0) {
920 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
921 PyExc_ValueError);
922 return NULL;
923 }
924 Py_INCREF(o);
925 return o;
926}
927
928#if 0
929static PyObject *
930float_is_inf(PyObject *v)
931{
932 double x = PyFloat_AsDouble(v);
933 if (x == -1.0 && PyErr_Occurred())
934 return NULL;
935 return PyBool_FromLong((long)Py_IS_INFINITY(x));
936}
937
938static PyObject *
939float_is_nan(PyObject *v)
940{
941 double x = PyFloat_AsDouble(v);
942 if (x == -1.0 && PyErr_Occurred())
943 return NULL;
944 return PyBool_FromLong((long)Py_IS_NAN(x));
945}
946
947static PyObject *
948float_is_finite(PyObject *v)
949{
950 double x = PyFloat_AsDouble(v);
951 if (x == -1.0 && PyErr_Occurred())
952 return NULL;
953 return PyBool_FromLong((long)Py_IS_FINITE(x));
954}
955#endif
956
957static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000958float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000959{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000960 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000961 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000962
963 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000964 /* Try to get out cheap if this fits in a Python int. The attempt
965 * to cast to long must be protected, as C doesn't define what
966 * happens if the double is too big to fit in a long. Some rare
967 * systems raise an exception then (RISCOS was mentioned as one,
968 * and someone using a non-default option on Sun also bumped into
969 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
970 * still be vulnerable: if a long has more bits of precision than
971 * a double, casting MIN/MAX to double may yield an approximation,
972 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
973 * yield true from the C expression wholepart<=LONG_MAX, despite
974 * that wholepart is actually greater than LONG_MAX.
975 */
976 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
977 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000978 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000979 }
980 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000981}
982
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000984float_round(PyObject *v, PyObject *args)
985{
986#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
987 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000988 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000989 double flr, cil;
990 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000991 int ndigits = UNDEF_NDIGITS;
992
993 if (!PyArg_ParseTuple(args, "|i", &ndigits))
994 return NULL;
995
996 x = PyFloat_AsDouble(v);
997
998 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000999 f = pow(10.0, ndigits);
1000 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001001 }
1002
1003 flr = floor(x);
1004 cil = ceil(x);
1005
1006 if (x-flr > 0.5)
1007 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001008 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001009 rounded = fmod(flr, 2) == 0 ? flr : cil;
1010 else
1011 rounded = flr;
1012
1013 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001014 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001015 return PyFloat_FromDouble(rounded);
1016 }
1017
1018 return PyLong_FromDouble(rounded);
1019#undef UNDEF_NDIGITS
1020}
1021
1022static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001023float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001024{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001025 if (PyFloat_CheckExact(v))
1026 Py_INCREF(v);
1027 else
1028 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001029 return v;
1030}
1031
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001032/* turn ASCII hex characters into integer values and vice versa */
1033
1034static char
1035char_from_hex(int x)
1036{
1037 assert(0 <= x && x < 16);
1038 return "0123456789abcdef"[x];
1039}
1040
1041static int
1042hex_from_char(char c) {
1043 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001044 switch(c) {
1045 case '0':
1046 x = 0;
1047 break;
1048 case '1':
1049 x = 1;
1050 break;
1051 case '2':
1052 x = 2;
1053 break;
1054 case '3':
1055 x = 3;
1056 break;
1057 case '4':
1058 x = 4;
1059 break;
1060 case '5':
1061 x = 5;
1062 break;
1063 case '6':
1064 x = 6;
1065 break;
1066 case '7':
1067 x = 7;
1068 break;
1069 case '8':
1070 x = 8;
1071 break;
1072 case '9':
1073 x = 9;
1074 break;
1075 case 'a':
1076 case 'A':
1077 x = 10;
1078 break;
1079 case 'b':
1080 case 'B':
1081 x = 11;
1082 break;
1083 case 'c':
1084 case 'C':
1085 x = 12;
1086 break;
1087 case 'd':
1088 case 'D':
1089 x = 13;
1090 break;
1091 case 'e':
1092 case 'E':
1093 x = 14;
1094 break;
1095 case 'f':
1096 case 'F':
1097 x = 15;
1098 break;
1099 default:
1100 x = -1;
1101 break;
1102 }
1103 return x;
1104}
1105
1106/* convert a float to a hexadecimal string */
1107
1108/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1109 of the form 4k+1. */
1110#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1111
1112static PyObject *
1113float_hex(PyObject *v)
1114{
1115 double x, m;
1116 int e, shift, i, si, esign;
1117 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1118 trailing NUL byte. */
1119 char s[(TOHEX_NBITS-1)/4+3];
1120
1121 CONVERT_TO_DOUBLE(v, x);
1122
1123 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1124 return float_str((PyFloatObject *)v);
1125
1126 if (x == 0.0) {
1127 if(copysign(1.0, x) == -1.0)
1128 return PyUnicode_FromString("-0x0.0p+0");
1129 else
1130 return PyUnicode_FromString("0x0.0p+0");
1131 }
1132
1133 m = frexp(fabs(x), &e);
1134 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1135 m = ldexp(m, shift);
1136 e -= shift;
1137
1138 si = 0;
1139 s[si] = char_from_hex((int)m);
1140 si++;
1141 m -= (int)m;
1142 s[si] = '.';
1143 si++;
1144 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1145 m *= 16.0;
1146 s[si] = char_from_hex((int)m);
1147 si++;
1148 m -= (int)m;
1149 }
1150 s[si] = '\0';
1151
1152 if (e < 0) {
1153 esign = (int)'-';
1154 e = -e;
1155 }
1156 else
1157 esign = (int)'+';
1158
1159 if (x < 0.0)
1160 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1161 else
1162 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1163}
1164
1165PyDoc_STRVAR(float_hex_doc,
1166"float.hex() -> string\n\
1167\n\
1168Return a hexadecimal representation of a floating-point number.\n\
1169>>> (-0.1).hex()\n\
1170'-0x1.999999999999ap-4'\n\
1171>>> 3.14159.hex()\n\
1172'0x1.921f9f01b866ep+1'");
1173
1174/* Convert a hexadecimal string to a float. */
1175
1176static PyObject *
1177float_fromhex(PyObject *cls, PyObject *arg)
1178{
1179 PyObject *result_as_float, *result;
1180 double x;
1181 long exp, top_exp, lsb, key_digit;
1182 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1183 int half_eps, digit, round_up, sign=1;
1184 Py_ssize_t length, ndigits, fdigits, i;
1185
1186 /*
1187 * For the sake of simplicity and correctness, we impose an artificial
1188 * limit on ndigits, the total number of hex digits in the coefficient
1189 * The limit is chosen to ensure that, writing exp for the exponent,
1190 *
1191 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1192 * guaranteed to overflow (provided it's nonzero)
1193 *
1194 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1195 * guaranteed to underflow to 0.
1196 *
1197 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1198 * overflow in the calculation of exp and top_exp below.
1199 *
1200 * More specifically, ndigits is assumed to satisfy the following
1201 * inequalities:
1202 *
1203 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1204 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1205 *
1206 * If either of these inequalities is not satisfied, a ValueError is
1207 * raised. Otherwise, write x for the value of the hex string, and
1208 * assume x is nonzero. Then
1209 *
1210 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1211 *
1212 * Now if exp > LONG_MAX/2 then:
1213 *
1214 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1215 * = DBL_MAX_EXP
1216 *
1217 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1218 * double, so overflows. If exp < LONG_MIN/2, then
1219 *
1220 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1221 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1222 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1223 *
1224 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1225 * when converted to a C double.
1226 *
1227 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1228 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1229 */
1230
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001231 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001232 if (s == NULL)
1233 return NULL;
1234 s_end = s + length;
1235
1236 /********************
1237 * Parse the string *
1238 ********************/
1239
1240 /* leading whitespace and optional sign */
Kristján Valur Jónssonbaa45462008-12-18 17:08:57 +00001241 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001242 s++;
1243 if (*s == '-') {
1244 s++;
1245 sign = -1;
1246 }
1247 else if (*s == '+')
1248 s++;
1249
1250 /* infinities and nans */
Andrew MacIntyre45612572008-09-22 14:49:01 +00001251 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001252 x = Py_NAN;
1253 goto finished;
1254 }
Andrew MacIntyre45612572008-09-22 14:49:01 +00001255 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1256 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001257 x = sign*Py_HUGE_VAL;
1258 goto finished;
1259 }
1260
1261 /* [0x] */
1262 s_store = s;
1263 if (*s == '0') {
1264 s++;
1265 if (tolower(*s) == (int)'x')
1266 s++;
1267 else
1268 s = s_store;
1269 }
1270
1271 /* coefficient: <integer> [. <fraction>] */
1272 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001273 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274 s++;
1275 s_store = s;
1276 if (*s == '.') {
1277 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001278 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001279 s++;
1280 coeff_end = s-1;
1281 }
1282 else
1283 coeff_end = s;
1284
1285 /* ndigits = total # of hex digits; fdigits = # after point */
1286 ndigits = coeff_end - coeff_start;
1287 fdigits = coeff_end - s_store;
1288 if (ndigits == 0)
1289 goto parse_error;
1290 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1291 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1292 goto insane_length_error;
1293
1294 /* [p <exponent>] */
1295 if (tolower(*s) == (int)'p') {
1296 s++;
1297 exp_start = s;
1298 if (*s == '-' || *s == '+')
1299 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001300 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001301 goto parse_error;
1302 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001303 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304 s++;
1305 exp = strtol(exp_start, NULL, 10);
1306 }
1307 else
1308 exp = 0;
1309
1310 /* optional trailing whitespace leading to the end of the string */
Kristján Valur Jónssonbaa45462008-12-18 17:08:57 +00001311 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001312 s++;
1313 if (s != s_end)
1314 goto parse_error;
1315
1316/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1317#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1318 coeff_end-(j) : \
1319 coeff_end-1-(j)))
1320
1321 /*******************************************
1322 * Compute rounded value of the hex string *
1323 *******************************************/
1324
1325 /* Discard leading zeros, and catch extreme overflow and underflow */
1326 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1327 ndigits--;
1328 if (ndigits == 0 || exp < LONG_MIN/2) {
1329 x = sign * 0.0;
1330 goto finished;
1331 }
1332 if (exp > LONG_MAX/2)
1333 goto overflow_error;
1334
1335 /* Adjust exponent for fractional part. */
1336 exp = exp - 4*((long)fdigits);
1337
1338 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1339 top_exp = exp + 4*((long)ndigits - 1);
1340 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1341 top_exp++;
1342
1343 /* catch almost all nonextreme cases of overflow and underflow here */
1344 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1345 x = sign * 0.0;
1346 goto finished;
1347 }
1348 if (top_exp > DBL_MAX_EXP)
1349 goto overflow_error;
1350
1351 /* lsb = exponent of least significant bit of the *rounded* value.
1352 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1353 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1354
1355 x = 0.0;
1356 if (exp >= lsb) {
1357 /* no rounding required */
1358 for (i = ndigits-1; i >= 0; i--)
1359 x = 16.0*x + HEX_DIGIT(i);
1360 x = sign * ldexp(x, (int)(exp));
1361 goto finished;
1362 }
1363 /* rounding required. key_digit is the index of the hex digit
1364 containing the first bit to be rounded away. */
1365 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1366 key_digit = (lsb - exp - 1) / 4;
1367 for (i = ndigits-1; i > key_digit; i--)
1368 x = 16.0*x + HEX_DIGIT(i);
1369 digit = HEX_DIGIT(key_digit);
1370 x = 16.0*x + (double)(digit & (16-2*half_eps));
1371
1372 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1373 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1374 if ((digit & half_eps) != 0) {
1375 round_up = 0;
1376 if ((digit & (3*half_eps-1)) != 0 ||
1377 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1378 round_up = 1;
1379 else
1380 for (i = key_digit-1; i >= 0; i--)
1381 if (HEX_DIGIT(i) != 0) {
1382 round_up = 1;
1383 break;
1384 }
1385 if (round_up == 1) {
1386 x += 2*half_eps;
1387 if (top_exp == DBL_MAX_EXP &&
1388 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1389 /* overflow corner case: pre-rounded value <
1390 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1391 goto overflow_error;
1392 }
1393 }
1394 x = sign * ldexp(x, (int)(exp+4*key_digit));
1395
1396 finished:
1397 result_as_float = Py_BuildValue("(d)", x);
1398 if (result_as_float == NULL)
1399 return NULL;
1400 result = PyObject_CallObject(cls, result_as_float);
1401 Py_DECREF(result_as_float);
1402 return result;
1403
1404 overflow_error:
1405 PyErr_SetString(PyExc_OverflowError,
1406 "hexadecimal value too large to represent as a float");
1407 return NULL;
1408
1409 parse_error:
1410 PyErr_SetString(PyExc_ValueError,
1411 "invalid hexadecimal floating-point string");
1412 return NULL;
1413
1414 insane_length_error:
1415 PyErr_SetString(PyExc_ValueError,
1416 "hexadecimal string too long to convert");
1417 return NULL;
1418}
1419
1420PyDoc_STRVAR(float_fromhex_doc,
1421"float.fromhex(string) -> float\n\
1422\n\
1423Create a floating-point number from a hexadecimal string.\n\
1424>>> float.fromhex('0x1.ffffp10')\n\
14252047.984375\n\
1426>>> float.fromhex('-0x1p-1074')\n\
1427-4.9406564584124654e-324");
1428
1429
Christian Heimes26855632008-01-27 23:50:43 +00001430static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001431float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001432{
1433 double self;
1434 double float_part;
1435 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001436 int i;
1437
Christian Heimes26855632008-01-27 23:50:43 +00001438 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001439 PyObject *py_exponent = NULL;
1440 PyObject *numerator = NULL;
1441 PyObject *denominator = NULL;
1442 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001443 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001444
1445#define INPLACE_UPDATE(obj, call) \
1446 prev = obj; \
1447 obj = call; \
1448 Py_DECREF(prev); \
1449
1450 CONVERT_TO_DOUBLE(v, self);
1451
1452 if (Py_IS_INFINITY(self)) {
1453 PyErr_SetString(PyExc_OverflowError,
1454 "Cannot pass infinity to float.as_integer_ratio.");
1455 return NULL;
1456 }
1457#ifdef Py_NAN
1458 if (Py_IS_NAN(self)) {
1459 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001460 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001461 return NULL;
1462 }
1463#endif
1464
Christian Heimes26855632008-01-27 23:50:43 +00001465 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001466 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001467 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001468
1469 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1470 float_part *= 2.0;
1471 exponent--;
1472 }
1473 /* self == float_part * 2**exponent exactly and float_part is integral.
1474 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1475 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001476
Christian Heimes292d3512008-02-03 16:51:08 +00001477 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001478 if (numerator == NULL) goto error;
1479
Christian Heimes292d3512008-02-03 16:51:08 +00001480 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001481 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001482 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001483 if (py_exponent == NULL) goto error;
1484 INPLACE_UPDATE(py_exponent,
1485 long_methods->nb_lshift(denominator, py_exponent));
1486 if (py_exponent == NULL) goto error;
1487 if (exponent > 0) {
1488 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001489 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001490 if (numerator == NULL) goto error;
1491 }
1492 else {
1493 Py_DECREF(denominator);
1494 denominator = py_exponent;
1495 py_exponent = NULL;
1496 }
1497
1498 result_pair = PyTuple_Pack(2, numerator, denominator);
1499
1500#undef INPLACE_UPDATE
1501error:
1502 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001503 Py_XDECREF(denominator);
1504 Py_XDECREF(numerator);
1505 return result_pair;
1506}
1507
1508PyDoc_STRVAR(float_as_integer_ratio_doc,
1509"float.as_integer_ratio() -> (int, int)\n"
1510"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001511"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1512"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001513"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001514"\n"
1515">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001516"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001517">>> (0.0).as_integer_ratio()\n"
1518"(0, 1)\n"
1519">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001520"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001521
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001522
Jeremy Hylton938ace62002-07-17 16:30:39 +00001523static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001524float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1525
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526static PyObject *
1527float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1528{
1529 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001530 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531
Guido van Rossumbef14172001-08-29 15:47:46 +00001532 if (type != &PyFloat_Type)
1533 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1535 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001536 /* If it's a string, but not a string subclass, use
1537 PyFloat_FromString. */
1538 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001539 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540 return PyNumber_Float(x);
1541}
1542
Guido van Rossumbef14172001-08-29 15:47:46 +00001543/* Wimpy, slow approach to tp_new calls for subtypes of float:
1544 first create a regular float from whatever arguments we got,
1545 then allocate a subtype instance and initialize its ob_fval
1546 from the regular float. The regular float is then thrown away.
1547*/
1548static PyObject *
1549float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1550{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001551 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001552
1553 assert(PyType_IsSubtype(type, &PyFloat_Type));
1554 tmp = float_new(&PyFloat_Type, args, kwds);
1555 if (tmp == NULL)
1556 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001557 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001558 newobj = type->tp_alloc(type, 0);
1559 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001560 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001561 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001562 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001564 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001565 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001566}
1567
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001568static PyObject *
1569float_getnewargs(PyFloatObject *v)
1570{
1571 return Py_BuildValue("(d)", v->ob_fval);
1572}
1573
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001574/* this is for the benefit of the pack/unpack routines below */
1575
1576typedef enum {
1577 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1578} float_format_type;
1579
1580static float_format_type double_format, float_format;
1581static float_format_type detected_double_format, detected_float_format;
1582
1583static PyObject *
1584float_getformat(PyTypeObject *v, PyObject* arg)
1585{
1586 char* s;
1587 float_format_type r;
1588
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001589 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001590 PyErr_Format(PyExc_TypeError,
1591 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001592 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001593 return NULL;
1594 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001595 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001596 if (s == NULL)
1597 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001598 if (strcmp(s, "double") == 0) {
1599 r = double_format;
1600 }
1601 else if (strcmp(s, "float") == 0) {
1602 r = float_format;
1603 }
1604 else {
1605 PyErr_SetString(PyExc_ValueError,
1606 "__getformat__() argument 1 must be "
1607 "'double' or 'float'");
1608 return NULL;
1609 }
1610
1611 switch (r) {
1612 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001613 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001615 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001616 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001617 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618 default:
1619 Py_FatalError("insane float_format or double_format");
1620 return NULL;
1621 }
1622}
1623
1624PyDoc_STRVAR(float_getformat_doc,
1625"float.__getformat__(typestr) -> string\n"
1626"\n"
1627"You probably don't want to use this function. It exists mainly to be\n"
1628"used in Python's test suite.\n"
1629"\n"
1630"typestr must be 'double' or 'float'. This function returns whichever of\n"
1631"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1632"format of floating point numbers used by the C type named by typestr.");
1633
1634static PyObject *
1635float_setformat(PyTypeObject *v, PyObject* args)
1636{
1637 char* typestr;
1638 char* format;
1639 float_format_type f;
1640 float_format_type detected;
1641 float_format_type *p;
1642
1643 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1644 return NULL;
1645
1646 if (strcmp(typestr, "double") == 0) {
1647 p = &double_format;
1648 detected = detected_double_format;
1649 }
1650 else if (strcmp(typestr, "float") == 0) {
1651 p = &float_format;
1652 detected = detected_float_format;
1653 }
1654 else {
1655 PyErr_SetString(PyExc_ValueError,
1656 "__setformat__() argument 1 must "
1657 "be 'double' or 'float'");
1658 return NULL;
1659 }
1660
1661 if (strcmp(format, "unknown") == 0) {
1662 f = unknown_format;
1663 }
1664 else if (strcmp(format, "IEEE, little-endian") == 0) {
1665 f = ieee_little_endian_format;
1666 }
1667 else if (strcmp(format, "IEEE, big-endian") == 0) {
1668 f = ieee_big_endian_format;
1669 }
1670 else {
1671 PyErr_SetString(PyExc_ValueError,
1672 "__setformat__() argument 2 must be "
1673 "'unknown', 'IEEE, little-endian' or "
1674 "'IEEE, big-endian'");
1675 return NULL;
1676
1677 }
1678
1679 if (f != unknown_format && f != detected) {
1680 PyErr_Format(PyExc_ValueError,
1681 "can only set %s format to 'unknown' or the "
1682 "detected platform value", typestr);
1683 return NULL;
1684 }
1685
1686 *p = f;
1687 Py_RETURN_NONE;
1688}
1689
1690PyDoc_STRVAR(float_setformat_doc,
1691"float.__setformat__(typestr, fmt) -> None\n"
1692"\n"
1693"You probably don't want to use this function. It exists mainly to be\n"
1694"used in Python's test suite.\n"
1695"\n"
1696"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1697"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1698"one of the latter two if it appears to match the underlying C reality.\n"
1699"\n"
1700"Overrides the automatic determination of C-level floating point type.\n"
1701"This affects how floats are converted to and from binary strings.");
1702
Guido van Rossumb43daf72007-08-01 18:08:08 +00001703static PyObject *
1704float_getzero(PyObject *v, void *closure)
1705{
1706 return PyFloat_FromDouble(0.0);
1707}
1708
Eric Smith8c663262007-08-25 02:26:07 +00001709static PyObject *
1710float__format__(PyObject *self, PyObject *args)
1711{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001712 PyObject *format_spec;
1713
1714 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1715 return NULL;
1716 return _PyFloat_FormatAdvanced(self,
1717 PyUnicode_AS_UNICODE(format_spec),
1718 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001719}
1720
1721PyDoc_STRVAR(float__format__doc,
1722"float.__format__(format_spec) -> string\n"
1723"\n"
1724"Formats the float according to format_spec.");
1725
1726
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001727static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001728 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001729 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001730 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1731 "Returns the Integral closest to x between 0 and x."},
1732 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1733 "Returns the Integral closest to x, rounding half toward even.\n"
1734 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001735 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1736 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001737 {"fromhex", (PyCFunction)float_fromhex,
1738 METH_O|METH_CLASS, float_fromhex_doc},
1739 {"hex", (PyCFunction)float_hex,
1740 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001741 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1742 "Returns True if the float is an integer."},
1743#if 0
1744 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1745 "Returns True if the float is positive or negative infinite."},
1746 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1747 "Returns True if the float is finite, neither infinite nor NaN."},
1748 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1749 "Returns True if the float is not a number (NaN)."},
1750#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001751 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001752 {"__getformat__", (PyCFunction)float_getformat,
1753 METH_O|METH_CLASS, float_getformat_doc},
1754 {"__setformat__", (PyCFunction)float_setformat,
1755 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001756 {"__format__", (PyCFunction)float__format__,
1757 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001758 {NULL, NULL} /* sentinel */
1759};
1760
Guido van Rossumb43daf72007-08-01 18:08:08 +00001761static PyGetSetDef float_getset[] = {
1762 {"real",
1763 (getter)float_float, (setter)NULL,
1764 "the real part of a complex number",
1765 NULL},
1766 {"imag",
1767 (getter)float_getzero, (setter)NULL,
1768 "the imaginary part of a complex number",
1769 NULL},
1770 {NULL} /* Sentinel */
1771};
1772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001773PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774"float(x) -> floating point number\n\
1775\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001776Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
1778
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001779static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001780 float_add, /*nb_add*/
1781 float_sub, /*nb_subtract*/
1782 float_mul, /*nb_multiply*/
1783 float_rem, /*nb_remainder*/
1784 float_divmod, /*nb_divmod*/
1785 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001786 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001787 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001788 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001789 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001790 0, /*nb_invert*/
1791 0, /*nb_lshift*/
1792 0, /*nb_rshift*/
1793 0, /*nb_and*/
1794 0, /*nb_xor*/
1795 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001796 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001797 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001798 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001799 0, /* nb_inplace_add */
1800 0, /* nb_inplace_subtract */
1801 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001802 0, /* nb_inplace_remainder */
1803 0, /* nb_inplace_power */
1804 0, /* nb_inplace_lshift */
1805 0, /* nb_inplace_rshift */
1806 0, /* nb_inplace_and */
1807 0, /* nb_inplace_xor */
1808 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001809 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001810 float_div, /* nb_true_divide */
1811 0, /* nb_inplace_floor_divide */
1812 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001813};
1814
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001815PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001816 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001817 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001818 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001821 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822 0, /* tp_getattr */
1823 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001824 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 (reprfunc)float_repr, /* tp_repr */
1826 &float_as_number, /* tp_as_number */
1827 0, /* tp_as_sequence */
1828 0, /* tp_as_mapping */
1829 (hashfunc)float_hash, /* tp_hash */
1830 0, /* tp_call */
1831 (reprfunc)float_str, /* tp_str */
1832 PyObject_GenericGetAttr, /* tp_getattro */
1833 0, /* tp_setattro */
1834 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001835 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 float_doc, /* tp_doc */
1837 0, /* tp_traverse */
1838 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001839 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 0, /* tp_weaklistoffset */
1841 0, /* tp_iter */
1842 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001843 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001845 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 0, /* tp_base */
1847 0, /* tp_dict */
1848 0, /* tp_descr_get */
1849 0, /* tp_descr_set */
1850 0, /* tp_dictoffset */
1851 0, /* tp_init */
1852 0, /* tp_alloc */
1853 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001855
1856void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001857_PyFloat_Init(void)
1858{
1859 /* We attempt to determine if this machine is using IEEE
1860 floating point formats by peering at the bits of some
1861 carefully chosen values. If it looks like we are on an
1862 IEEE platform, the float packing/unpacking routines can
1863 just copy bits, if not they resort to arithmetic & shifts
1864 and masks. The shifts & masks approach works on all finite
1865 values, but what happens to infinities, NaNs and signed
1866 zeroes on packing is an accident, and attempting to unpack
1867 a NaN or an infinity will raise an exception.
1868
1869 Note that if we're on some whacked-out platform which uses
1870 IEEE formats but isn't strictly little-endian or big-
1871 endian, we will fall back to the portable shifts & masks
1872 method. */
1873
1874#if SIZEOF_DOUBLE == 8
1875 {
1876 double x = 9006104071832581.0;
1877 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1878 detected_double_format = ieee_big_endian_format;
1879 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1880 detected_double_format = ieee_little_endian_format;
1881 else
1882 detected_double_format = unknown_format;
1883 }
1884#else
1885 detected_double_format = unknown_format;
1886#endif
1887
1888#if SIZEOF_FLOAT == 4
1889 {
1890 float y = 16711938.0;
1891 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1892 detected_float_format = ieee_big_endian_format;
1893 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1894 detected_float_format = ieee_little_endian_format;
1895 else
1896 detected_float_format = unknown_format;
1897 }
1898#else
1899 detected_float_format = unknown_format;
1900#endif
1901
1902 double_format = detected_double_format;
1903 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001904
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001905 /* Init float info */
1906 if (FloatInfoType.tp_name == 0)
1907 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908}
1909
Georg Brandl2ee470f2008-07-16 12:55:28 +00001910int
1911PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001912{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001913 PyFloatObject *p;
1914 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001915 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001916 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001917 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001918
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001919 list = block_list;
1920 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001921 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001922 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001923 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001924 for (i = 0, p = &list->objects[0];
1925 i < N_FLOATOBJECTS;
1926 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001927 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001928 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001929 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001930 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001931 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001932 list->next = block_list;
1933 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001934 for (i = 0, p = &list->objects[0];
1935 i < N_FLOATOBJECTS;
1936 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001937 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001938 Py_REFCNT(p) == 0) {
1939 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001940 free_list;
1941 free_list = p;
1942 }
1943 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001944 }
1945 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001946 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001947 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001948 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001949 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001950 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001951 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001952}
1953
1954void
1955PyFloat_Fini(void)
1956{
1957 PyFloatObject *p;
1958 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001959 int i;
1960 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001961
Georg Brandl2ee470f2008-07-16 12:55:28 +00001962 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001963
Guido van Rossum3fce8831999-03-12 19:43:17 +00001964 if (!Py_VerboseFlag)
1965 return;
1966 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001967 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001968 fprintf(stderr, "\n");
1969 }
1970 else {
1971 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001972 ": %d unfreed float%s\n",
1973 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001974 }
1975 if (Py_VerboseFlag > 1) {
1976 list = block_list;
1977 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001978 for (i = 0, p = &list->objects[0];
1979 i < N_FLOATOBJECTS;
1980 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001981 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001982 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001983 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001984 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001985 /* XXX(twouters) cast refcount to
1986 long until %zd is universally
1987 available
1988 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001989 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001990 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001991 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001992 }
1993 }
1994 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001995 }
1996 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001997}
Tim Peters9905b942003-03-20 20:53:32 +00001998
1999/*----------------------------------------------------------------------------
2000 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002001 */
2002int
2003_PyFloat_Pack4(double x, unsigned char *p, int le)
2004{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002005 if (float_format == unknown_format) {
2006 unsigned char sign;
2007 int e;
2008 double f;
2009 unsigned int fbits;
2010 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002011
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012 if (le) {
2013 p += 3;
2014 incr = -1;
2015 }
Tim Peters9905b942003-03-20 20:53:32 +00002016
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002017 if (x < 0) {
2018 sign = 1;
2019 x = -x;
2020 }
2021 else
2022 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002023
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002025
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002026 /* Normalize f to be in the range [1.0, 2.0) */
2027 if (0.5 <= f && f < 1.0) {
2028 f *= 2.0;
2029 e--;
2030 }
2031 else if (f == 0.0)
2032 e = 0;
2033 else {
2034 PyErr_SetString(PyExc_SystemError,
2035 "frexp() result out of range");
2036 return -1;
2037 }
2038
2039 if (e >= 128)
2040 goto Overflow;
2041 else if (e < -126) {
2042 /* Gradual underflow */
2043 f = ldexp(f, 126 + e);
2044 e = 0;
2045 }
2046 else if (!(e == 0 && f == 0.0)) {
2047 e += 127;
2048 f -= 1.0; /* Get rid of leading 1 */
2049 }
2050
2051 f *= 8388608.0; /* 2**23 */
2052 fbits = (unsigned int)(f + 0.5); /* Round */
2053 assert(fbits <= 8388608);
2054 if (fbits >> 23) {
2055 /* The carry propagated out of a string of 23 1 bits. */
2056 fbits = 0;
2057 ++e;
2058 if (e >= 255)
2059 goto Overflow;
2060 }
2061
2062 /* First byte */
2063 *p = (sign << 7) | (e >> 1);
2064 p += incr;
2065
2066 /* Second byte */
2067 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2068 p += incr;
2069
2070 /* Third byte */
2071 *p = (fbits >> 8) & 0xFF;
2072 p += incr;
2073
2074 /* Fourth byte */
2075 *p = fbits & 0xFF;
2076
2077 /* Done */
2078 return 0;
2079
Tim Peters9905b942003-03-20 20:53:32 +00002080 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002081 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002082 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002083 const char *s = (char*)&y;
2084 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002085
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002086 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2087 goto Overflow;
2088
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002089 if ((float_format == ieee_little_endian_format && !le)
2090 || (float_format == ieee_big_endian_format && le)) {
2091 p += 3;
2092 incr = -1;
2093 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002094
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002095 for (i = 0; i < 4; i++) {
2096 *p = *s++;
2097 p += incr;
2098 }
2099 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002100 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002101 Overflow:
2102 PyErr_SetString(PyExc_OverflowError,
2103 "float too large to pack with f format");
2104 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002105}
2106
2107int
2108_PyFloat_Pack8(double x, unsigned char *p, int le)
2109{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002110 if (double_format == unknown_format) {
2111 unsigned char sign;
2112 int e;
2113 double f;
2114 unsigned int fhi, flo;
2115 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002116
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117 if (le) {
2118 p += 7;
2119 incr = -1;
2120 }
Tim Peters9905b942003-03-20 20:53:32 +00002121
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 if (x < 0) {
2123 sign = 1;
2124 x = -x;
2125 }
2126 else
2127 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002128
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002130
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002131 /* Normalize f to be in the range [1.0, 2.0) */
2132 if (0.5 <= f && f < 1.0) {
2133 f *= 2.0;
2134 e--;
2135 }
2136 else if (f == 0.0)
2137 e = 0;
2138 else {
2139 PyErr_SetString(PyExc_SystemError,
2140 "frexp() result out of range");
2141 return -1;
2142 }
2143
2144 if (e >= 1024)
2145 goto Overflow;
2146 else if (e < -1022) {
2147 /* Gradual underflow */
2148 f = ldexp(f, 1022 + e);
2149 e = 0;
2150 }
2151 else if (!(e == 0 && f == 0.0)) {
2152 e += 1023;
2153 f -= 1.0; /* Get rid of leading 1 */
2154 }
2155
2156 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2157 f *= 268435456.0; /* 2**28 */
2158 fhi = (unsigned int)f; /* Truncate */
2159 assert(fhi < 268435456);
2160
2161 f -= (double)fhi;
2162 f *= 16777216.0; /* 2**24 */
2163 flo = (unsigned int)(f + 0.5); /* Round */
2164 assert(flo <= 16777216);
2165 if (flo >> 24) {
2166 /* The carry propagated out of a string of 24 1 bits. */
2167 flo = 0;
2168 ++fhi;
2169 if (fhi >> 28) {
2170 /* And it also progagated out of the next 28 bits. */
2171 fhi = 0;
2172 ++e;
2173 if (e >= 2047)
2174 goto Overflow;
2175 }
2176 }
2177
2178 /* First byte */
2179 *p = (sign << 7) | (e >> 4);
2180 p += incr;
2181
2182 /* Second byte */
2183 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2184 p += incr;
2185
2186 /* Third byte */
2187 *p = (fhi >> 16) & 0xFF;
2188 p += incr;
2189
2190 /* Fourth byte */
2191 *p = (fhi >> 8) & 0xFF;
2192 p += incr;
2193
2194 /* Fifth byte */
2195 *p = fhi & 0xFF;
2196 p += incr;
2197
2198 /* Sixth byte */
2199 *p = (flo >> 16) & 0xFF;
2200 p += incr;
2201
2202 /* Seventh byte */
2203 *p = (flo >> 8) & 0xFF;
2204 p += incr;
2205
2206 /* Eighth byte */
2207 *p = flo & 0xFF;
2208 p += incr;
2209
2210 /* Done */
2211 return 0;
2212
2213 Overflow:
2214 PyErr_SetString(PyExc_OverflowError,
2215 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002216 return -1;
2217 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218 else {
2219 const char *s = (char*)&x;
2220 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002221
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222 if ((double_format == ieee_little_endian_format && !le)
2223 || (double_format == ieee_big_endian_format && le)) {
2224 p += 7;
2225 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002226 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227
2228 for (i = 0; i < 8; i++) {
2229 *p = *s++;
2230 p += incr;
2231 }
2232 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002233 }
Tim Peters9905b942003-03-20 20:53:32 +00002234}
2235
Neal Norwitz545686b2006-12-28 04:45:06 +00002236/* Should only be used by marshal. */
2237int
2238_PyFloat_Repr(double x, char *p, size_t len)
2239{
2240 format_double(p, len, x, PREC_REPR);
2241 return (int)strlen(p);
2242}
2243
Tim Peters9905b942003-03-20 20:53:32 +00002244double
2245_PyFloat_Unpack4(const unsigned char *p, int le)
2246{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002247 if (float_format == unknown_format) {
2248 unsigned char sign;
2249 int e;
2250 unsigned int f;
2251 double x;
2252 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002253
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002254 if (le) {
2255 p += 3;
2256 incr = -1;
2257 }
2258
2259 /* First byte */
2260 sign = (*p >> 7) & 1;
2261 e = (*p & 0x7F) << 1;
2262 p += incr;
2263
2264 /* Second byte */
2265 e |= (*p >> 7) & 1;
2266 f = (*p & 0x7F) << 16;
2267 p += incr;
2268
2269 if (e == 255) {
2270 PyErr_SetString(
2271 PyExc_ValueError,
2272 "can't unpack IEEE 754 special value "
2273 "on non-IEEE platform");
2274 return -1;
2275 }
2276
2277 /* Third byte */
2278 f |= *p << 8;
2279 p += incr;
2280
2281 /* Fourth byte */
2282 f |= *p;
2283
2284 x = (double)f / 8388608.0;
2285
2286 /* XXX This sadly ignores Inf/NaN issues */
2287 if (e == 0)
2288 e = -126;
2289 else {
2290 x += 1.0;
2291 e -= 127;
2292 }
2293 x = ldexp(x, e);
2294
2295 if (sign)
2296 x = -x;
2297
2298 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002299 }
Tim Peters9905b942003-03-20 20:53:32 +00002300 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002301 float x;
2302
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002303 if ((float_format == ieee_little_endian_format && !le)
2304 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002305 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306 char *d = &buf[3];
2307 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002308
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309 for (i = 0; i < 4; i++) {
2310 *d-- = *p++;
2311 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002312 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313 }
2314 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002315 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002316 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002317
2318 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002319 }
Tim Peters9905b942003-03-20 20:53:32 +00002320}
2321
2322double
2323_PyFloat_Unpack8(const unsigned char *p, int le)
2324{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325 if (double_format == unknown_format) {
2326 unsigned char sign;
2327 int e;
2328 unsigned int fhi, flo;
2329 double x;
2330 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002331
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002332 if (le) {
2333 p += 7;
2334 incr = -1;
2335 }
2336
2337 /* First byte */
2338 sign = (*p >> 7) & 1;
2339 e = (*p & 0x7F) << 4;
2340
2341 p += incr;
2342
2343 /* Second byte */
2344 e |= (*p >> 4) & 0xF;
2345 fhi = (*p & 0xF) << 24;
2346 p += incr;
2347
2348 if (e == 2047) {
2349 PyErr_SetString(
2350 PyExc_ValueError,
2351 "can't unpack IEEE 754 special value "
2352 "on non-IEEE platform");
2353 return -1.0;
2354 }
2355
2356 /* Third byte */
2357 fhi |= *p << 16;
2358 p += incr;
2359
2360 /* Fourth byte */
2361 fhi |= *p << 8;
2362 p += incr;
2363
2364 /* Fifth byte */
2365 fhi |= *p;
2366 p += incr;
2367
2368 /* Sixth byte */
2369 flo = *p << 16;
2370 p += incr;
2371
2372 /* Seventh byte */
2373 flo |= *p << 8;
2374 p += incr;
2375
2376 /* Eighth byte */
2377 flo |= *p;
2378
2379 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2380 x /= 268435456.0; /* 2**28 */
2381
2382 if (e == 0)
2383 e = -1022;
2384 else {
2385 x += 1.0;
2386 e -= 1023;
2387 }
2388 x = ldexp(x, e);
2389
2390 if (sign)
2391 x = -x;
2392
2393 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002394 }
Tim Peters9905b942003-03-20 20:53:32 +00002395 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002396 double x;
2397
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002398 if ((double_format == ieee_little_endian_format && !le)
2399 || (double_format == ieee_big_endian_format && le)) {
2400 char buf[8];
2401 char *d = &buf[7];
2402 int i;
2403
2404 for (i = 0; i < 8; i++) {
2405 *d-- = *p++;
2406 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002407 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002408 }
2409 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002410 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002411 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002412
2413 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002414 }
Tim Peters9905b942003-03-20 20:53:32 +00002415}