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