blob: 20c1eef01468480d41629054b472c56f7af863d6 [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
Christian Heimes292d3512008-02-03 16:51:08 +00001498 /* Returns ints instead of longs where possible */
1499 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1500 if (numerator == NULL) goto error;
1501 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1502 if (denominator == NULL) goto error;
1503
Christian Heimes26855632008-01-27 23:50:43 +00001504 result_pair = PyTuple_Pack(2, numerator, denominator);
1505
1506#undef INPLACE_UPDATE
1507error:
1508 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001509 Py_XDECREF(denominator);
1510 Py_XDECREF(numerator);
1511 return result_pair;
1512}
1513
1514PyDoc_STRVAR(float_as_integer_ratio_doc,
1515"float.as_integer_ratio() -> (int, int)\n"
1516"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001517"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1518"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001519"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001520"\n"
1521">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001522"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001523">>> (0.0).as_integer_ratio()\n"
1524"(0, 1)\n"
1525">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001526"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001527
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001528
Jeremy Hylton938ace62002-07-17 16:30:39 +00001529static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001530float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1531
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532static PyObject *
1533float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1534{
1535 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001536 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537
Guido van Rossumbef14172001-08-29 15:47:46 +00001538 if (type != &PyFloat_Type)
1539 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1541 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001542 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001543 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 return PyNumber_Float(x);
1545}
1546
Guido van Rossumbef14172001-08-29 15:47:46 +00001547/* Wimpy, slow approach to tp_new calls for subtypes of float:
1548 first create a regular float from whatever arguments we got,
1549 then allocate a subtype instance and initialize its ob_fval
1550 from the regular float. The regular float is then thrown away.
1551*/
1552static PyObject *
1553float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1554{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001555 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001556
1557 assert(PyType_IsSubtype(type, &PyFloat_Type));
1558 tmp = float_new(&PyFloat_Type, args, kwds);
1559 if (tmp == NULL)
1560 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001561 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001562 newobj = type->tp_alloc(type, 0);
1563 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001564 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001565 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001566 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001567 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001568 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001569 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001570}
1571
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001572static PyObject *
1573float_getnewargs(PyFloatObject *v)
1574{
1575 return Py_BuildValue("(d)", v->ob_fval);
1576}
1577
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001578/* this is for the benefit of the pack/unpack routines below */
1579
1580typedef enum {
1581 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1582} float_format_type;
1583
1584static float_format_type double_format, float_format;
1585static float_format_type detected_double_format, detected_float_format;
1586
1587static PyObject *
1588float_getformat(PyTypeObject *v, PyObject* arg)
1589{
1590 char* s;
1591 float_format_type r;
1592
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001593 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001594 PyErr_Format(PyExc_TypeError,
1595 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001596 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597 return NULL;
1598 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001599 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001600 if (s == NULL)
1601 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001602 if (strcmp(s, "double") == 0) {
1603 r = double_format;
1604 }
1605 else if (strcmp(s, "float") == 0) {
1606 r = float_format;
1607 }
1608 else {
1609 PyErr_SetString(PyExc_ValueError,
1610 "__getformat__() argument 1 must be "
1611 "'double' or 'float'");
1612 return NULL;
1613 }
1614
1615 switch (r) {
1616 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001617 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001619 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001621 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001622 default:
1623 Py_FatalError("insane float_format or double_format");
1624 return NULL;
1625 }
1626}
1627
1628PyDoc_STRVAR(float_getformat_doc,
1629"float.__getformat__(typestr) -> string\n"
1630"\n"
1631"You probably don't want to use this function. It exists mainly to be\n"
1632"used in Python's test suite.\n"
1633"\n"
1634"typestr must be 'double' or 'float'. This function returns whichever of\n"
1635"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1636"format of floating point numbers used by the C type named by typestr.");
1637
1638static PyObject *
1639float_setformat(PyTypeObject *v, PyObject* args)
1640{
1641 char* typestr;
1642 char* format;
1643 float_format_type f;
1644 float_format_type detected;
1645 float_format_type *p;
1646
1647 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1648 return NULL;
1649
1650 if (strcmp(typestr, "double") == 0) {
1651 p = &double_format;
1652 detected = detected_double_format;
1653 }
1654 else if (strcmp(typestr, "float") == 0) {
1655 p = &float_format;
1656 detected = detected_float_format;
1657 }
1658 else {
1659 PyErr_SetString(PyExc_ValueError,
1660 "__setformat__() argument 1 must "
1661 "be 'double' or 'float'");
1662 return NULL;
1663 }
1664
1665 if (strcmp(format, "unknown") == 0) {
1666 f = unknown_format;
1667 }
1668 else if (strcmp(format, "IEEE, little-endian") == 0) {
1669 f = ieee_little_endian_format;
1670 }
1671 else if (strcmp(format, "IEEE, big-endian") == 0) {
1672 f = ieee_big_endian_format;
1673 }
1674 else {
1675 PyErr_SetString(PyExc_ValueError,
1676 "__setformat__() argument 2 must be "
1677 "'unknown', 'IEEE, little-endian' or "
1678 "'IEEE, big-endian'");
1679 return NULL;
1680
1681 }
1682
1683 if (f != unknown_format && f != detected) {
1684 PyErr_Format(PyExc_ValueError,
1685 "can only set %s format to 'unknown' or the "
1686 "detected platform value", typestr);
1687 return NULL;
1688 }
1689
1690 *p = f;
1691 Py_RETURN_NONE;
1692}
1693
1694PyDoc_STRVAR(float_setformat_doc,
1695"float.__setformat__(typestr, fmt) -> None\n"
1696"\n"
1697"You probably don't want to use this function. It exists mainly to be\n"
1698"used in Python's test suite.\n"
1699"\n"
1700"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1701"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1702"one of the latter two if it appears to match the underlying C reality.\n"
1703"\n"
1704"Overrides the automatic determination of C-level floating point type.\n"
1705"This affects how floats are converted to and from binary strings.");
1706
Guido van Rossumb43daf72007-08-01 18:08:08 +00001707static PyObject *
1708float_getzero(PyObject *v, void *closure)
1709{
1710 return PyFloat_FromDouble(0.0);
1711}
1712
Eric Smith8c663262007-08-25 02:26:07 +00001713static PyObject *
1714float__format__(PyObject *self, PyObject *args)
1715{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001716 PyObject *format_spec;
1717
1718 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1719 return NULL;
1720 return _PyFloat_FormatAdvanced(self,
1721 PyUnicode_AS_UNICODE(format_spec),
1722 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001723}
1724
1725PyDoc_STRVAR(float__format__doc,
1726"float.__format__(format_spec) -> string\n"
1727"\n"
1728"Formats the float according to format_spec.");
1729
1730
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001731static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001732 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001733 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001734 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1735 "Returns the Integral closest to x between 0 and x."},
1736 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1737 "Returns the Integral closest to x, rounding half toward even.\n"
1738 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001739 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1740 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001741 {"fromhex", (PyCFunction)float_fromhex,
1742 METH_O|METH_CLASS, float_fromhex_doc},
1743 {"hex", (PyCFunction)float_hex,
1744 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001745 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1746 "Returns True if the float is an integer."},
1747#if 0
1748 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1749 "Returns True if the float is positive or negative infinite."},
1750 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1751 "Returns True if the float is finite, neither infinite nor NaN."},
1752 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1753 "Returns True if the float is not a number (NaN)."},
1754#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001755 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001756 {"__getformat__", (PyCFunction)float_getformat,
1757 METH_O|METH_CLASS, float_getformat_doc},
1758 {"__setformat__", (PyCFunction)float_setformat,
1759 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001760 {"__format__", (PyCFunction)float__format__,
1761 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001762 {NULL, NULL} /* sentinel */
1763};
1764
Guido van Rossumb43daf72007-08-01 18:08:08 +00001765static PyGetSetDef float_getset[] = {
1766 {"real",
1767 (getter)float_float, (setter)NULL,
1768 "the real part of a complex number",
1769 NULL},
1770 {"imag",
1771 (getter)float_getzero, (setter)NULL,
1772 "the imaginary part of a complex number",
1773 NULL},
1774 {NULL} /* Sentinel */
1775};
1776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001777PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778"float(x) -> floating point number\n\
1779\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001780Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781
1782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001783static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001784 float_add, /*nb_add*/
1785 float_sub, /*nb_subtract*/
1786 float_mul, /*nb_multiply*/
1787 float_rem, /*nb_remainder*/
1788 float_divmod, /*nb_divmod*/
1789 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001790 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001791 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001792 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001793 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001794 0, /*nb_invert*/
1795 0, /*nb_lshift*/
1796 0, /*nb_rshift*/
1797 0, /*nb_and*/
1798 0, /*nb_xor*/
1799 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001800 float_trunc, /*nb_int*/
1801 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001802 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001803 0, /* nb_inplace_add */
1804 0, /* nb_inplace_subtract */
1805 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001806 0, /* nb_inplace_remainder */
1807 0, /* nb_inplace_power */
1808 0, /* nb_inplace_lshift */
1809 0, /* nb_inplace_rshift */
1810 0, /* nb_inplace_and */
1811 0, /* nb_inplace_xor */
1812 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001813 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001814 float_div, /* nb_true_divide */
1815 0, /* nb_inplace_floor_divide */
1816 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001817};
1818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001820 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001821 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001822 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001825 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 0, /* tp_getattr */
1827 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001828 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 (reprfunc)float_repr, /* tp_repr */
1830 &float_as_number, /* tp_as_number */
1831 0, /* tp_as_sequence */
1832 0, /* tp_as_mapping */
1833 (hashfunc)float_hash, /* tp_hash */
1834 0, /* tp_call */
1835 (reprfunc)float_str, /* tp_str */
1836 PyObject_GenericGetAttr, /* tp_getattro */
1837 0, /* tp_setattro */
1838 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001839 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 float_doc, /* tp_doc */
1841 0, /* tp_traverse */
1842 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001843 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 0, /* tp_weaklistoffset */
1845 0, /* tp_iter */
1846 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001847 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001849 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 0, /* tp_base */
1851 0, /* tp_dict */
1852 0, /* tp_descr_get */
1853 0, /* tp_descr_set */
1854 0, /* tp_dictoffset */
1855 0, /* tp_init */
1856 0, /* tp_alloc */
1857 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001859
1860void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001861_PyFloat_Init(void)
1862{
1863 /* We attempt to determine if this machine is using IEEE
1864 floating point formats by peering at the bits of some
1865 carefully chosen values. If it looks like we are on an
1866 IEEE platform, the float packing/unpacking routines can
1867 just copy bits, if not they resort to arithmetic & shifts
1868 and masks. The shifts & masks approach works on all finite
1869 values, but what happens to infinities, NaNs and signed
1870 zeroes on packing is an accident, and attempting to unpack
1871 a NaN or an infinity will raise an exception.
1872
1873 Note that if we're on some whacked-out platform which uses
1874 IEEE formats but isn't strictly little-endian or big-
1875 endian, we will fall back to the portable shifts & masks
1876 method. */
1877
1878#if SIZEOF_DOUBLE == 8
1879 {
1880 double x = 9006104071832581.0;
1881 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1882 detected_double_format = ieee_big_endian_format;
1883 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1884 detected_double_format = ieee_little_endian_format;
1885 else
1886 detected_double_format = unknown_format;
1887 }
1888#else
1889 detected_double_format = unknown_format;
1890#endif
1891
1892#if SIZEOF_FLOAT == 4
1893 {
1894 float y = 16711938.0;
1895 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1896 detected_float_format = ieee_big_endian_format;
1897 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1898 detected_float_format = ieee_little_endian_format;
1899 else
1900 detected_float_format = unknown_format;
1901 }
1902#else
1903 detected_float_format = unknown_format;
1904#endif
1905
1906 double_format = detected_double_format;
1907 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001908
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001909 /* Init float info */
1910 if (FloatInfoType.tp_name == 0)
1911 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001912}
1913
Georg Brandl2ee470f2008-07-16 12:55:28 +00001914int
1915PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001916{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001917 PyFloatObject *p;
1918 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001919 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001920 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001921 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001922
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001923 list = block_list;
1924 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001925 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001926 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001927 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001928 for (i = 0, p = &list->objects[0];
1929 i < N_FLOATOBJECTS;
1930 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001931 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001932 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001933 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001934 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001935 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001936 list->next = block_list;
1937 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001938 for (i = 0, p = &list->objects[0];
1939 i < N_FLOATOBJECTS;
1940 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001941 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001942 Py_REFCNT(p) == 0) {
1943 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001944 free_list;
1945 free_list = p;
1946 }
1947 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001948 }
1949 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001950 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001951 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001952 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001953 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001954 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001955 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001956}
1957
1958void
1959PyFloat_Fini(void)
1960{
1961 PyFloatObject *p;
1962 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001963 int i;
1964 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001965
Georg Brandl2ee470f2008-07-16 12:55:28 +00001966 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001967
Guido van Rossum3fce8831999-03-12 19:43:17 +00001968 if (!Py_VerboseFlag)
1969 return;
1970 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001971 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001972 fprintf(stderr, "\n");
1973 }
1974 else {
1975 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001976 ": %d unfreed float%s\n",
1977 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001978 }
1979 if (Py_VerboseFlag > 1) {
1980 list = block_list;
1981 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001982 for (i = 0, p = &list->objects[0];
1983 i < N_FLOATOBJECTS;
1984 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001985 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001986 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001987 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001988 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001989 /* XXX(twouters) cast refcount to
1990 long until %zd is universally
1991 available
1992 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001993 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001994 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001995 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001996 }
1997 }
1998 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001999 }
2000 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002001}
Tim Peters9905b942003-03-20 20:53:32 +00002002
2003/*----------------------------------------------------------------------------
2004 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002005 */
2006int
2007_PyFloat_Pack4(double x, unsigned char *p, int le)
2008{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 if (float_format == unknown_format) {
2010 unsigned char sign;
2011 int e;
2012 double f;
2013 unsigned int fbits;
2014 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002015
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002016 if (le) {
2017 p += 3;
2018 incr = -1;
2019 }
Tim Peters9905b942003-03-20 20:53:32 +00002020
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002021 if (x < 0) {
2022 sign = 1;
2023 x = -x;
2024 }
2025 else
2026 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002027
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002028 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002029
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002030 /* Normalize f to be in the range [1.0, 2.0) */
2031 if (0.5 <= f && f < 1.0) {
2032 f *= 2.0;
2033 e--;
2034 }
2035 else if (f == 0.0)
2036 e = 0;
2037 else {
2038 PyErr_SetString(PyExc_SystemError,
2039 "frexp() result out of range");
2040 return -1;
2041 }
2042
2043 if (e >= 128)
2044 goto Overflow;
2045 else if (e < -126) {
2046 /* Gradual underflow */
2047 f = ldexp(f, 126 + e);
2048 e = 0;
2049 }
2050 else if (!(e == 0 && f == 0.0)) {
2051 e += 127;
2052 f -= 1.0; /* Get rid of leading 1 */
2053 }
2054
2055 f *= 8388608.0; /* 2**23 */
2056 fbits = (unsigned int)(f + 0.5); /* Round */
2057 assert(fbits <= 8388608);
2058 if (fbits >> 23) {
2059 /* The carry propagated out of a string of 23 1 bits. */
2060 fbits = 0;
2061 ++e;
2062 if (e >= 255)
2063 goto Overflow;
2064 }
2065
2066 /* First byte */
2067 *p = (sign << 7) | (e >> 1);
2068 p += incr;
2069
2070 /* Second byte */
2071 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2072 p += incr;
2073
2074 /* Third byte */
2075 *p = (fbits >> 8) & 0xFF;
2076 p += incr;
2077
2078 /* Fourth byte */
2079 *p = fbits & 0xFF;
2080
2081 /* Done */
2082 return 0;
2083
Tim Peters9905b942003-03-20 20:53:32 +00002084 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002085 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002086 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002087 const char *s = (char*)&y;
2088 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002089
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002090 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2091 goto Overflow;
2092
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002093 if ((float_format == ieee_little_endian_format && !le)
2094 || (float_format == ieee_big_endian_format && le)) {
2095 p += 3;
2096 incr = -1;
2097 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002098
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002099 for (i = 0; i < 4; i++) {
2100 *p = *s++;
2101 p += incr;
2102 }
2103 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002104 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002105 Overflow:
2106 PyErr_SetString(PyExc_OverflowError,
2107 "float too large to pack with f format");
2108 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002109}
2110
2111int
2112_PyFloat_Pack8(double x, unsigned char *p, int le)
2113{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114 if (double_format == unknown_format) {
2115 unsigned char sign;
2116 int e;
2117 double f;
2118 unsigned int fhi, flo;
2119 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002120
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002121 if (le) {
2122 p += 7;
2123 incr = -1;
2124 }
Tim Peters9905b942003-03-20 20:53:32 +00002125
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002126 if (x < 0) {
2127 sign = 1;
2128 x = -x;
2129 }
2130 else
2131 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002132
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002133 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002134
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002135 /* Normalize f to be in the range [1.0, 2.0) */
2136 if (0.5 <= f && f < 1.0) {
2137 f *= 2.0;
2138 e--;
2139 }
2140 else if (f == 0.0)
2141 e = 0;
2142 else {
2143 PyErr_SetString(PyExc_SystemError,
2144 "frexp() result out of range");
2145 return -1;
2146 }
2147
2148 if (e >= 1024)
2149 goto Overflow;
2150 else if (e < -1022) {
2151 /* Gradual underflow */
2152 f = ldexp(f, 1022 + e);
2153 e = 0;
2154 }
2155 else if (!(e == 0 && f == 0.0)) {
2156 e += 1023;
2157 f -= 1.0; /* Get rid of leading 1 */
2158 }
2159
2160 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2161 f *= 268435456.0; /* 2**28 */
2162 fhi = (unsigned int)f; /* Truncate */
2163 assert(fhi < 268435456);
2164
2165 f -= (double)fhi;
2166 f *= 16777216.0; /* 2**24 */
2167 flo = (unsigned int)(f + 0.5); /* Round */
2168 assert(flo <= 16777216);
2169 if (flo >> 24) {
2170 /* The carry propagated out of a string of 24 1 bits. */
2171 flo = 0;
2172 ++fhi;
2173 if (fhi >> 28) {
2174 /* And it also progagated out of the next 28 bits. */
2175 fhi = 0;
2176 ++e;
2177 if (e >= 2047)
2178 goto Overflow;
2179 }
2180 }
2181
2182 /* First byte */
2183 *p = (sign << 7) | (e >> 4);
2184 p += incr;
2185
2186 /* Second byte */
2187 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2188 p += incr;
2189
2190 /* Third byte */
2191 *p = (fhi >> 16) & 0xFF;
2192 p += incr;
2193
2194 /* Fourth byte */
2195 *p = (fhi >> 8) & 0xFF;
2196 p += incr;
2197
2198 /* Fifth byte */
2199 *p = fhi & 0xFF;
2200 p += incr;
2201
2202 /* Sixth byte */
2203 *p = (flo >> 16) & 0xFF;
2204 p += incr;
2205
2206 /* Seventh byte */
2207 *p = (flo >> 8) & 0xFF;
2208 p += incr;
2209
2210 /* Eighth byte */
2211 *p = flo & 0xFF;
2212 p += incr;
2213
2214 /* Done */
2215 return 0;
2216
2217 Overflow:
2218 PyErr_SetString(PyExc_OverflowError,
2219 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002220 return -1;
2221 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222 else {
2223 const char *s = (char*)&x;
2224 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002225
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226 if ((double_format == ieee_little_endian_format && !le)
2227 || (double_format == ieee_big_endian_format && le)) {
2228 p += 7;
2229 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002230 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
2232 for (i = 0; i < 8; i++) {
2233 *p = *s++;
2234 p += incr;
2235 }
2236 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002237 }
Tim Peters9905b942003-03-20 20:53:32 +00002238}
2239
Neal Norwitz545686b2006-12-28 04:45:06 +00002240/* Should only be used by marshal. */
2241int
2242_PyFloat_Repr(double x, char *p, size_t len)
2243{
2244 format_double(p, len, x, PREC_REPR);
2245 return (int)strlen(p);
2246}
2247
Tim Peters9905b942003-03-20 20:53:32 +00002248double
2249_PyFloat_Unpack4(const unsigned char *p, int le)
2250{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002251 if (float_format == unknown_format) {
2252 unsigned char sign;
2253 int e;
2254 unsigned int f;
2255 double x;
2256 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002257
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258 if (le) {
2259 p += 3;
2260 incr = -1;
2261 }
2262
2263 /* First byte */
2264 sign = (*p >> 7) & 1;
2265 e = (*p & 0x7F) << 1;
2266 p += incr;
2267
2268 /* Second byte */
2269 e |= (*p >> 7) & 1;
2270 f = (*p & 0x7F) << 16;
2271 p += incr;
2272
2273 if (e == 255) {
2274 PyErr_SetString(
2275 PyExc_ValueError,
2276 "can't unpack IEEE 754 special value "
2277 "on non-IEEE platform");
2278 return -1;
2279 }
2280
2281 /* Third byte */
2282 f |= *p << 8;
2283 p += incr;
2284
2285 /* Fourth byte */
2286 f |= *p;
2287
2288 x = (double)f / 8388608.0;
2289
2290 /* XXX This sadly ignores Inf/NaN issues */
2291 if (e == 0)
2292 e = -126;
2293 else {
2294 x += 1.0;
2295 e -= 127;
2296 }
2297 x = ldexp(x, e);
2298
2299 if (sign)
2300 x = -x;
2301
2302 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002303 }
Tim Peters9905b942003-03-20 20:53:32 +00002304 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002305 float x;
2306
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307 if ((float_format == ieee_little_endian_format && !le)
2308 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002309 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310 char *d = &buf[3];
2311 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002312
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313 for (i = 0; i < 4; i++) {
2314 *d-- = *p++;
2315 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002316 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317 }
2318 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002319 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002321
2322 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323 }
Tim Peters9905b942003-03-20 20:53:32 +00002324}
2325
2326double
2327_PyFloat_Unpack8(const unsigned char *p, int le)
2328{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329 if (double_format == unknown_format) {
2330 unsigned char sign;
2331 int e;
2332 unsigned int fhi, flo;
2333 double x;
2334 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002335
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336 if (le) {
2337 p += 7;
2338 incr = -1;
2339 }
2340
2341 /* First byte */
2342 sign = (*p >> 7) & 1;
2343 e = (*p & 0x7F) << 4;
2344
2345 p += incr;
2346
2347 /* Second byte */
2348 e |= (*p >> 4) & 0xF;
2349 fhi = (*p & 0xF) << 24;
2350 p += incr;
2351
2352 if (e == 2047) {
2353 PyErr_SetString(
2354 PyExc_ValueError,
2355 "can't unpack IEEE 754 special value "
2356 "on non-IEEE platform");
2357 return -1.0;
2358 }
2359
2360 /* Third byte */
2361 fhi |= *p << 16;
2362 p += incr;
2363
2364 /* Fourth byte */
2365 fhi |= *p << 8;
2366 p += incr;
2367
2368 /* Fifth byte */
2369 fhi |= *p;
2370 p += incr;
2371
2372 /* Sixth byte */
2373 flo = *p << 16;
2374 p += incr;
2375
2376 /* Seventh byte */
2377 flo |= *p << 8;
2378 p += incr;
2379
2380 /* Eighth byte */
2381 flo |= *p;
2382
2383 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2384 x /= 268435456.0; /* 2**28 */
2385
2386 if (e == 0)
2387 e = -1022;
2388 else {
2389 x += 1.0;
2390 e -= 1023;
2391 }
2392 x = ldexp(x, e);
2393
2394 if (sign)
2395 x = -x;
2396
2397 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002398 }
Tim Peters9905b942003-03-20 20:53:32 +00002399 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002400 double x;
2401
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002402 if ((double_format == ieee_little_endian_format && !le)
2403 || (double_format == ieee_big_endian_format && le)) {
2404 char buf[8];
2405 char *d = &buf[7];
2406 int i;
2407
2408 for (i = 0; i < 8; i++) {
2409 *d-- = *p++;
2410 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002411 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002412 }
2413 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002414 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002415 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002416
2417 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002418 }
Tim Peters9905b942003-03-20 20:53:32 +00002419}