blob: 8161ed51e23daf60e0f900264aad76cdbd2733b4 [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
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Christian Heimes969fe572008-01-25 11:23:10 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
26#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
27#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000030 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000032};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000042 PyFloatObject *p, *q;
43 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
45 if (p == NULL)
46 return (PyFloatObject *) PyErr_NoMemory();
47 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
50 q = p + N_FLOATOBJECTS;
51 while (--q > p)
52 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
54 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055}
56
Christian Heimes93852662007-12-01 12:22:32 +000057double
58PyFloat_GetMax(void)
59{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000060 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000061}
62
63double
64PyFloat_GetMin(void)
65{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000066 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000067}
68
Christian Heimesd32ed6f2008-01-14 18:49:24 +000069static PyTypeObject FloatInfoType;
70
71PyDoc_STRVAR(floatinfo__doc__,
72"sys.floatinfo\n\
73\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000079 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000096};
97
98static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000099 "sys.floatinfo", /* name */
100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000103};
104
Christian Heimes93852662007-12-01 12:22:32 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000108 PyObject* floatinfo;
109 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000110
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000111 floatinfo = PyStructSequence_New(&FloatInfoType);
112 if (floatinfo == NULL) {
113 return NULL;
114 }
Christian Heimes93852662007-12-01 12:22:32 +0000115
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000116#define SetIntFlag(flag) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000118#define SetDblFlag(flag) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000119 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000120
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000121 SetDblFlag(DBL_MAX);
122 SetIntFlag(DBL_MAX_EXP);
123 SetIntFlag(DBL_MAX_10_EXP);
124 SetDblFlag(DBL_MIN);
125 SetIntFlag(DBL_MIN_EXP);
126 SetIntFlag(DBL_MIN_10_EXP);
127 SetIntFlag(DBL_DIG);
128 SetIntFlag(DBL_MANT_DIG);
129 SetDblFlag(DBL_EPSILON);
130 SetIntFlag(FLT_RADIX);
131 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000132#undef SetIntFlag
133#undef SetDblFlag
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000134
135 if (PyErr_Occurred()) {
136 Py_CLEAR(floatinfo);
137 return NULL;
138 }
139 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000140}
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000145 register PyFloatObject *op;
146 if (free_list == NULL) {
147 if ((free_list = fill_free_list()) == NULL)
148 return NULL;
149 }
150 /* Inline PyObject_New */
151 op = free_list;
152 free_list = (PyFloatObject *)Py_TYPE(op);
153 PyObject_INIT(op, &PyFloat_Type);
154 op->ob_fval = fval;
155 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000158PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000159PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000161 const char *s, *last, *end;
162 double x;
163 char buffer[256]; /* for errors */
164 char *s_buffer = NULL;
165 Py_ssize_t len;
166 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000168 if (PyUnicode_Check(v)) {
169 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
170 if (s_buffer == NULL)
171 return PyErr_NoMemory();
172 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
173 PyUnicode_GET_SIZE(v),
174 s_buffer,
175 NULL))
176 goto error;
177 s = s_buffer;
178 len = strlen(s);
179 }
180 else if (PyObject_AsCharBuffer(v, &s, &len)) {
181 PyErr_SetString(PyExc_TypeError,
182 "float() argument must be a string or a number");
183 return NULL;
184 }
185 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000186
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000187 while (Py_ISSPACE(*s))
188 s++;
189 /* We don't care about overflow or underflow. If the platform
190 * supports them, infinities and signed zeroes (on underflow) are
191 * fine. */
192 x = PyOS_string_to_double(s, (char **)&end, NULL);
193 if (x == -1.0 && PyErr_Occurred())
194 goto error;
195 while (Py_ISSPACE(*end))
196 end++;
197 if (end == last)
198 result = PyFloat_FromDouble(x);
199 else {
200 PyOS_snprintf(buffer, sizeof(buffer),
201 "invalid literal for float(): %.200s", s);
202 PyErr_SetString(PyExc_ValueError, buffer);
203 result = NULL;
204 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000205
Guido van Rossum2be161d2007-05-15 20:43:51 +0000206 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000207 if (s_buffer)
208 PyMem_FREE(s_buffer);
209 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210}
211
Guido van Rossum234f9421993-06-17 12:35:49 +0000212static void
Fred Drakefd99de62000-07-09 05:02:18 +0000213float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000214{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000215 if (PyFloat_CheckExact(op)) {
216 Py_TYPE(op) = (struct _typeobject *)free_list;
217 free_list = op;
218 }
219 else
220 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000221}
222
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223double
Fred Drakefd99de62000-07-09 05:02:18 +0000224PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000226 PyNumberMethods *nb;
227 PyFloatObject *fo;
228 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000229
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000230 if (op && PyFloat_Check(op))
231 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000233 if (op == NULL) {
234 PyErr_BadArgument();
235 return -1;
236 }
Tim Petersd2364e82001-11-01 20:09:42 +0000237
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000238 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
239 PyErr_SetString(PyExc_TypeError, "a float is required");
240 return -1;
241 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000242
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000243 fo = (PyFloatObject*) (*nb->nb_float) (op);
244 if (fo == NULL)
245 return -1;
246 if (!PyFloat_Check(fo)) {
247 PyErr_SetString(PyExc_TypeError,
248 "nb_float should return float object");
249 return -1;
250 }
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000252 val = PyFloat_AS_DOUBLE(fo);
253 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000255 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256}
257
Neil Schemenauer32117e52001-01-04 01:44:34 +0000258/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000259 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000260 set to NULL, and the function invoking this macro returns NULL. If
261 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
262 stored in obj, and returned from the function invoking this macro.
263*/
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000264#define CONVERT_TO_DOUBLE(obj, dbl) \
265 if (PyFloat_Check(obj)) \
266 dbl = PyFloat_AS_DOUBLE(obj); \
267 else if (convert_to_double(&(obj), &(dbl)) < 0) \
268 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000269
Eric Smith0923d1d2009-04-16 20:16:10 +0000270/* Methods */
271
Neil Schemenauer32117e52001-01-04 01:44:34 +0000272static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000273convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000274{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000275 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000276
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000277 if (PyLong_Check(obj)) {
278 *dbl = PyLong_AsDouble(obj);
279 if (*dbl == -1.0 && PyErr_Occurred()) {
280 *v = NULL;
281 return -1;
282 }
283 }
284 else {
285 Py_INCREF(Py_NotImplemented);
286 *v = Py_NotImplemented;
287 return -1;
288 }
289 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000290}
291
Eric Smith0923d1d2009-04-16 20:16:10 +0000292static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000293float_str_or_repr(PyFloatObject *v, int precision, char format_code)
Eric Smith0923d1d2009-04-16 20:16:10 +0000294{
295 PyObject *result;
296 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Eric Smith63376222009-05-05 14:04:18 +0000297 format_code, precision,
298 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000299 NULL);
300 if (!buf)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000301 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000302 result = PyUnicode_FromString(buf);
303 PyMem_Free(buf);
304 return result;
305}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000306
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000308float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Eric Smith63376222009-05-05 14:04:18 +0000310 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000311}
312
313static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000314float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000315{
Eric Smith63376222009-05-05 14:04:18 +0000316 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317}
318
Tim Peters307fa782004-09-23 08:06:40 +0000319/* Comparison is pretty much a nightmare. When comparing float to float,
320 * we do it as straightforwardly (and long-windedly) as conceivable, so
321 * that, e.g., Python x == y delivers the same result as the platform
322 * C x == y when x and/or y is a NaN.
323 * When mixing float with an integer type, there's no good *uniform* approach.
324 * Converting the double to an integer obviously doesn't work, since we
325 * may lose info from fractional bits. Converting the integer to a double
326 * also has two failure modes: (1) a long int may trigger overflow (too
327 * large to fit in the dynamic range of a C double); (2) even a C long may have
328 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
329 * 63 bits of precision, but a C double probably has only 53), and then
330 * we can falsely claim equality when low-order integer bits are lost by
331 * coercion to double. So this part is painful too.
332 */
333
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000334static PyObject*
335float_richcompare(PyObject *v, PyObject *w, int op)
336{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000337 double i, j;
338 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000339
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000340 assert(PyFloat_Check(v));
341 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000343 /* Switch on the type of w. Set i and j to doubles to be compared,
344 * and op to the richcomp to use.
345 */
346 if (PyFloat_Check(w))
347 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000348
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000349 else if (!Py_IS_FINITE(i)) {
350 if (PyLong_Check(w))
351 /* If i is an infinity, its magnitude exceeds any
352 * finite integer, so it doesn't matter which int we
353 * compare i with. If i is a NaN, similarly.
354 */
355 j = 0.0;
356 else
357 goto Unimplemented;
358 }
Tim Peters307fa782004-09-23 08:06:40 +0000359
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000360 else if (PyLong_Check(w)) {
361 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
362 int wsign = _PyLong_Sign(w);
363 size_t nbits;
364 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000365
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000366 if (vsign != wsign) {
367 /* Magnitudes are irrelevant -- the signs alone
368 * determine the outcome.
369 */
370 i = (double)vsign;
371 j = (double)wsign;
372 goto Compare;
373 }
374 /* The signs are the same. */
375 /* Convert w to a double if it fits. In particular, 0 fits. */
376 nbits = _PyLong_NumBits(w);
377 if (nbits == (size_t)-1 && PyErr_Occurred()) {
378 /* This long is so large that size_t isn't big enough
379 * to hold the # of bits. Replace with little doubles
380 * that give the same outcome -- w is so large that
381 * its magnitude must exceed the magnitude of any
382 * finite float.
383 */
384 PyErr_Clear();
385 i = (double)vsign;
386 assert(wsign != 0);
387 j = wsign * 2.0;
388 goto Compare;
389 }
390 if (nbits <= 48) {
391 j = PyLong_AsDouble(w);
392 /* It's impossible that <= 48 bits overflowed. */
393 assert(j != -1.0 || ! PyErr_Occurred());
394 goto Compare;
395 }
396 assert(wsign != 0); /* else nbits was 0 */
397 assert(vsign != 0); /* if vsign were 0, then since wsign is
398 * not 0, we would have taken the
399 * vsign != wsign branch at the start */
400 /* We want to work with non-negative numbers. */
401 if (vsign < 0) {
402 /* "Multiply both sides" by -1; this also swaps the
403 * comparator.
404 */
405 i = -i;
406 op = _Py_SwappedOp[op];
407 }
408 assert(i > 0.0);
409 (void) frexp(i, &exponent);
410 /* exponent is the # of bits in v before the radix point;
411 * we know that nbits (the # of bits in w) > 48 at this point
412 */
413 if (exponent < 0 || (size_t)exponent < nbits) {
414 i = 1.0;
415 j = 2.0;
416 goto Compare;
417 }
418 if ((size_t)exponent > nbits) {
419 i = 2.0;
420 j = 1.0;
421 goto Compare;
422 }
423 /* v and w have the same number of bits before the radix
424 * point. Construct two longs that have the same comparison
425 * outcome.
426 */
427 {
428 double fracpart;
429 double intpart;
430 PyObject *result = NULL;
431 PyObject *one = NULL;
432 PyObject *vv = NULL;
433 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000434
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000435 if (wsign < 0) {
436 ww = PyNumber_Negative(w);
437 if (ww == NULL)
438 goto Error;
439 }
440 else
441 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000442
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000443 fracpart = modf(i, &intpart);
444 vv = PyLong_FromDouble(intpart);
445 if (vv == NULL)
446 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000447
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000448 if (fracpart != 0.0) {
449 /* Shift left, and or a 1 bit into vv
450 * to represent the lost fraction.
451 */
452 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000453
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000454 one = PyLong_FromLong(1);
455 if (one == NULL)
456 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000458 temp = PyNumber_Lshift(ww, one);
459 if (temp == NULL)
460 goto Error;
461 Py_DECREF(ww);
462 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000463
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000464 temp = PyNumber_Lshift(vv, one);
465 if (temp == NULL)
466 goto Error;
467 Py_DECREF(vv);
468 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000469
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000470 temp = PyNumber_Or(vv, one);
471 if (temp == NULL)
472 goto Error;
473 Py_DECREF(vv);
474 vv = temp;
475 }
Tim Peters307fa782004-09-23 08:06:40 +0000476
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000477 r = PyObject_RichCompareBool(vv, ww, op);
478 if (r < 0)
479 goto Error;
480 result = PyBool_FromLong(r);
481 Error:
482 Py_XDECREF(vv);
483 Py_XDECREF(ww);
484 Py_XDECREF(one);
485 return result;
486 }
487 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000488
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000489 else /* w isn't float, int, or long */
490 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000491
492 Compare:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000493 PyFPE_START_PROTECT("richcompare", return NULL)
494 switch (op) {
495 case Py_EQ:
496 r = i == j;
497 break;
498 case Py_NE:
499 r = i != j;
500 break;
501 case Py_LE:
502 r = i <= j;
503 break;
504 case Py_GE:
505 r = i >= j;
506 break;
507 case Py_LT:
508 r = i < j;
509 break;
510 case Py_GT:
511 r = i > j;
512 break;
513 }
514 PyFPE_END_PROTECT(r)
515 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000516
517 Unimplemented:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000518 Py_INCREF(Py_NotImplemented);
519 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000520}
521
Guido van Rossum9bfef441993-03-29 10:43:31 +0000522static long
Fred Drakefd99de62000-07-09 05:02:18 +0000523float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000524{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000525 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526}
527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000531 double a,b;
532 CONVERT_TO_DOUBLE(v, a);
533 CONVERT_TO_DOUBLE(w, b);
534 PyFPE_START_PROTECT("add", return 0)
535 a = a + b;
536 PyFPE_END_PROTECT(a)
537 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538}
539
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000543 double a,b;
544 CONVERT_TO_DOUBLE(v, a);
545 CONVERT_TO_DOUBLE(w, b);
546 PyFPE_START_PROTECT("subtract", return 0)
547 a = a - b;
548 PyFPE_END_PROTECT(a)
549 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000555 double a,b;
556 CONVERT_TO_DOUBLE(v, a);
557 CONVERT_TO_DOUBLE(w, b);
558 PyFPE_START_PROTECT("multiply", return 0)
559 a = a * b;
560 PyFPE_END_PROTECT(a)
561 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000567 double a,b;
568 CONVERT_TO_DOUBLE(v, a);
569 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000570#ifdef Py_NAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000571 if (b == 0.0) {
572 PyErr_SetString(PyExc_ZeroDivisionError,
573 "float division");
574 return NULL;
575 }
Christian Heimes53876d92008-04-19 00:31:39 +0000576#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000577 PyFPE_START_PROTECT("divide", return 0)
578 a = a / b;
579 PyFPE_END_PROTECT(a)
580 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000586 double vx, wx;
587 double mod;
588 CONVERT_TO_DOUBLE(v, vx);
589 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000590#ifdef Py_NAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000591 if (wx == 0.0) {
592 PyErr_SetString(PyExc_ZeroDivisionError,
593 "float modulo");
594 return NULL;
595 }
Christian Heimes53876d92008-04-19 00:31:39 +0000596#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000597 PyFPE_START_PROTECT("modulo", return 0)
598 mod = fmod(vx, wx);
Mark Dickinson0169af12010-12-04 13:04:18 +0000599 if (mod) {
600 /* ensure the remainder has the same sign as the denominator */
601 if ((wx < 0) != (mod < 0)) {
602 mod += wx;
603 }
604 }
605 else {
606 /* the remainder is zero, and in the presence of signed zeroes
607 fmod returns different results across platforms; ensure
608 it has the same sign as the denominator; we'd like to do
609 "mod = wx * 0.0", but that may get optimized away */
610 mod *= mod; /* hide "mod = +0" from optimizer */
611 if (wx < 0.0)
612 mod = -mod;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000613 }
614 PyFPE_END_PROTECT(mod)
615 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616}
617
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000619float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000620{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000621 double vx, wx;
622 double div, mod, floordiv;
623 CONVERT_TO_DOUBLE(v, vx);
624 CONVERT_TO_DOUBLE(w, wx);
625 if (wx == 0.0) {
626 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
627 return NULL;
628 }
629 PyFPE_START_PROTECT("divmod", return 0)
630 mod = fmod(vx, wx);
631 /* fmod is typically exact, so vx-mod is *mathematically* an
632 exact multiple of wx. But this is fp arithmetic, and fp
633 vx - mod is an approximation; the result is that div may
634 not be an exact integral value after the division, although
635 it will always be very close to one.
636 */
637 div = (vx - mod) / wx;
638 if (mod) {
639 /* ensure the remainder has the same sign as the denominator */
640 if ((wx < 0) != (mod < 0)) {
641 mod += wx;
642 div -= 1.0;
643 }
644 }
645 else {
646 /* the remainder is zero, and in the presence of signed zeroes
647 fmod returns different results across platforms; ensure
648 it has the same sign as the denominator; we'd like to do
649 "mod = wx * 0.0", but that may get optimized away */
650 mod *= mod; /* hide "mod = +0" from optimizer */
651 if (wx < 0.0)
652 mod = -mod;
653 }
654 /* snap quotient to nearest integral value */
655 if (div) {
656 floordiv = floor(div);
657 if (div - floordiv > 0.5)
658 floordiv += 1.0;
659 }
660 else {
661 /* div is zero - get the same sign as the true quotient */
662 div *= div; /* hide "div = +0" from optimizers */
663 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
664 }
665 PyFPE_END_PROTECT(floordiv)
666 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000667}
668
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000670float_floor_div(PyObject *v, PyObject *w)
671{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000672 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000673
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000674 t = float_divmod(v, w);
675 if (t == NULL || t == Py_NotImplemented)
676 return t;
677 assert(PyTuple_CheckExact(t));
678 r = PyTuple_GET_ITEM(t, 0);
679 Py_INCREF(r);
680 Py_DECREF(t);
681 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000682}
683
684static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000685float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000687 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000688
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000689 if ((PyObject *)z != Py_None) {
690 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
691 "allowed unless all arguments are integers");
692 return NULL;
693 }
Tim Peters32f453e2001-09-03 08:35:41 +0000694
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000695 CONVERT_TO_DOUBLE(v, iv);
696 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000697
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000698 /* Sort out special cases here instead of relying on pow() */
699 if (iw == 0) { /* v**0 is 1, even 0**0 */
700 return PyFloat_FromDouble(1.0);
701 }
702 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
703 if (iw < 0.0) {
704 PyErr_SetString(PyExc_ZeroDivisionError,
705 "0.0 cannot be raised to a negative power");
706 return NULL;
707 }
708 return PyFloat_FromDouble(0.0);
709 }
710 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
711 return PyFloat_FromDouble(1.0);
712 }
713 if (iv < 0.0) {
714 /* Whether this is an error is a mess, and bumps into libm
715 * bugs so we have to figure it out ourselves.
716 */
717 if (iw != floor(iw)) {
718 /* Negative numbers raised to fractional powers
719 * become complex.
720 */
721 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
722 }
723 /* iw is an exact integer, albeit perhaps a very large one.
724 * -1 raised to an exact integer should never be exceptional.
725 * Alas, some libms (chiefly glibc as of early 2003) return
726 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
727 * happen to be representable in a *C* integer. That's a
728 * bug; we let that slide in math.pow() (which currently
729 * reflects all platform accidents), but not for Python's **.
730 */
731 if (iv == -1.0 && Py_IS_FINITE(iw)) {
732 /* Return 1 if iw is even, -1 if iw is odd; there's
733 * no guarantee that any C integral type is big
734 * enough to hold iw, so we have to check this
735 * indirectly.
736 */
737 ix = floor(iw * 0.5) * 2.0;
738 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
739 }
740 /* Else iv != -1.0, and overflow or underflow are possible.
741 * Unless we're to write pow() ourselves, we have to trust
742 * the platform to do this correctly.
743 */
744 }
745 errno = 0;
746 PyFPE_START_PROTECT("pow", return NULL)
747 ix = pow(iv, iw);
748 PyFPE_END_PROTECT(ix)
749 Py_ADJUST_ERANGE1(ix);
750 if (errno != 0) {
751 /* We don't expect any errno value other than ERANGE, but
752 * the range of libm bugs appears unbounded.
753 */
754 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
755 PyExc_ValueError);
756 return NULL;
757 }
758 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759}
760
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000762float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000764 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000765}
766
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000768float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000769{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000770 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771}
772
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000773static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000774float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000775{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000776 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000777}
778
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000779static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000780float_is_integer(PyObject *v)
781{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000782 double x = PyFloat_AsDouble(v);
783 PyObject *o;
784
785 if (x == -1.0 && PyErr_Occurred())
786 return NULL;
787 if (!Py_IS_FINITE(x))
788 Py_RETURN_FALSE;
789 errno = 0;
790 PyFPE_START_PROTECT("is_integer", return NULL)
791 o = (floor(x) == x) ? Py_True : Py_False;
792 PyFPE_END_PROTECT(x)
793 if (errno != 0) {
794 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
795 PyExc_ValueError);
796 return NULL;
797 }
798 Py_INCREF(o);
799 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000800}
801
802#if 0
803static PyObject *
804float_is_inf(PyObject *v)
805{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000806 double x = PyFloat_AsDouble(v);
807 if (x == -1.0 && PyErr_Occurred())
808 return NULL;
809 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000810}
811
812static PyObject *
813float_is_nan(PyObject *v)
814{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000815 double x = PyFloat_AsDouble(v);
816 if (x == -1.0 && PyErr_Occurred())
817 return NULL;
818 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000819}
820
821static PyObject *
822float_is_finite(PyObject *v)
823{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000824 double x = PyFloat_AsDouble(v);
825 if (x == -1.0 && PyErr_Occurred())
826 return NULL;
827 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000828}
829#endif
830
831static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000832float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000833{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000834 double x = PyFloat_AsDouble(v);
835 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000836
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000837 (void)modf(x, &wholepart);
838 /* Try to get out cheap if this fits in a Python int. The attempt
839 * to cast to long must be protected, as C doesn't define what
840 * happens if the double is too big to fit in a long. Some rare
841 * systems raise an exception then (RISCOS was mentioned as one,
842 * and someone using a non-default option on Sun also bumped into
843 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
844 * still be vulnerable: if a long has more bits of precision than
845 * a double, casting MIN/MAX to double may yield an approximation,
846 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
847 * yield true from the C expression wholepart<=LONG_MAX, despite
848 * that wholepart is actually greater than LONG_MAX.
849 */
850 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
851 const long aslong = (long)wholepart;
852 return PyLong_FromLong(aslong);
853 }
854 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000855}
856
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000857/* double_round: rounds a finite double to the closest multiple of
858 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
859 ndigits <= 323). Returns a Python float, or sets a Python error and
860 returns NULL on failure (OverflowError and memory errors are possible). */
861
862#ifndef PY_NO_SHORT_FLOAT_REPR
863/* version of double_round that uses the correctly-rounded string<->double
864 conversions from Python/dtoa.c */
865
866static PyObject *
867double_round(double x, int ndigits) {
868
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000869 double rounded;
870 Py_ssize_t buflen, mybuflen=100;
871 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
872 int decpt, sign;
873 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000874
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000875 /* round to a decimal string */
876 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
877 if (buf == NULL) {
878 PyErr_NoMemory();
879 return NULL;
880 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000881
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000882 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
883 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
884 buflen = buf_end - buf;
885 if (buflen + 8 > mybuflen) {
886 mybuflen = buflen+8;
887 mybuf = (char *)PyMem_Malloc(mybuflen);
888 if (mybuf == NULL) {
889 PyErr_NoMemory();
890 goto exit;
891 }
892 }
893 /* copy buf to mybuf, adding exponent, sign and leading 0 */
894 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
895 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000896
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000897 /* and convert the resulting string back to a double */
898 errno = 0;
899 rounded = _Py_dg_strtod(mybuf, NULL);
900 if (errno == ERANGE && fabs(rounded) >= 1.)
901 PyErr_SetString(PyExc_OverflowError,
902 "rounded value too large to represent");
903 else
904 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000905
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000906 /* done computing value; now clean up */
907 if (mybuf != shortbuf)
908 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000909 exit:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000910 _Py_dg_freedtoa(buf);
911 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000912}
913
914#else /* PY_NO_SHORT_FLOAT_REPR */
915
916/* fallback version, to be used when correctly rounded binary<->decimal
917 conversions aren't available */
918
919static PyObject *
920double_round(double x, int ndigits) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000921 double pow1, pow2, y, z;
922 if (ndigits >= 0) {
923 if (ndigits > 22) {
924 /* pow1 and pow2 are each safe from overflow, but
925 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
926 pow1 = pow(10.0, (double)(ndigits-22));
927 pow2 = 1e22;
928 }
929 else {
930 pow1 = pow(10.0, (double)ndigits);
931 pow2 = 1.0;
932 }
933 y = (x*pow1)*pow2;
934 /* if y overflows, then rounded value is exactly x */
935 if (!Py_IS_FINITE(y))
936 return PyFloat_FromDouble(x);
937 }
938 else {
939 pow1 = pow(10.0, (double)-ndigits);
940 pow2 = 1.0; /* unused; silences a gcc compiler warning */
941 y = x / pow1;
942 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000943
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000944 z = round(y);
945 if (fabs(y-z) == 0.5)
946 /* halfway between two integers; use round-half-even */
947 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000948
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000949 if (ndigits >= 0)
950 z = (z / pow2) / pow1;
951 else
952 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000953
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000954 /* if computation resulted in overflow, raise OverflowError */
955 if (!Py_IS_FINITE(z)) {
956 PyErr_SetString(PyExc_OverflowError,
957 "overflow occurred during round");
958 return NULL;
959 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000960
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000961 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000962}
963
964#endif /* PY_NO_SHORT_FLOAT_REPR */
965
966/* round a Python float v to the closest multiple of 10**-ndigits */
967
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000968static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000969float_round(PyObject *v, PyObject *args)
970{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000971 double x, rounded;
972 PyObject *o_ndigits = NULL;
973 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000974
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000975 x = PyFloat_AsDouble(v);
976 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
977 return NULL;
978 if (o_ndigits == NULL) {
979 /* single-argument round: round to nearest integer */
980 rounded = round(x);
981 if (fabs(x-rounded) == 0.5)
982 /* halfway case: round to even */
983 rounded = 2.0*round(x/2.0);
984 return PyLong_FromDouble(rounded);
985 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000986
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000987 /* interpret second argument as a Py_ssize_t; clips on overflow */
988 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
989 if (ndigits == -1 && PyErr_Occurred())
990 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000991
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000992 /* nans and infinities round to themselves */
993 if (!Py_IS_FINITE(x))
994 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000995
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000996 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
997 always rounds to itself. For ndigits < NDIGITS_MIN, x always
998 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000999#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1000#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001001 if (ndigits > NDIGITS_MAX)
1002 /* return x */
1003 return PyFloat_FromDouble(x);
1004 else if (ndigits < NDIGITS_MIN)
1005 /* return 0.0, but with sign of x */
1006 return PyFloat_FromDouble(0.0*x);
1007 else
1008 /* finite x, and ndigits is not unreasonably large */
1009 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001010#undef NDIGITS_MAX
1011#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001012}
1013
1014static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001015float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001016{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001017 if (PyFloat_CheckExact(v))
1018 Py_INCREF(v);
1019 else
1020 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1021 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001022}
1023
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001024/* turn ASCII hex characters into integer values and vice versa */
1025
1026static char
1027char_from_hex(int x)
1028{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001029 assert(0 <= x && x < 16);
1030 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001031}
1032
1033static int
1034hex_from_char(char c) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001035 int x;
1036 switch(c) {
1037 case '0':
1038 x = 0;
1039 break;
1040 case '1':
1041 x = 1;
1042 break;
1043 case '2':
1044 x = 2;
1045 break;
1046 case '3':
1047 x = 3;
1048 break;
1049 case '4':
1050 x = 4;
1051 break;
1052 case '5':
1053 x = 5;
1054 break;
1055 case '6':
1056 x = 6;
1057 break;
1058 case '7':
1059 x = 7;
1060 break;
1061 case '8':
1062 x = 8;
1063 break;
1064 case '9':
1065 x = 9;
1066 break;
1067 case 'a':
1068 case 'A':
1069 x = 10;
1070 break;
1071 case 'b':
1072 case 'B':
1073 x = 11;
1074 break;
1075 case 'c':
1076 case 'C':
1077 x = 12;
1078 break;
1079 case 'd':
1080 case 'D':
1081 x = 13;
1082 break;
1083 case 'e':
1084 case 'E':
1085 x = 14;
1086 break;
1087 case 'f':
1088 case 'F':
1089 x = 15;
1090 break;
1091 default:
1092 x = -1;
1093 break;
1094 }
1095 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001096}
1097
1098/* convert a float to a hexadecimal string */
1099
1100/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1101 of the form 4k+1. */
1102#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1103
1104static PyObject *
1105float_hex(PyObject *v)
1106{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001107 double x, m;
1108 int e, shift, i, si, esign;
1109 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1110 trailing NUL byte. */
1111 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001112
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001113 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001114
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001115 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1116 return float_str((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001117
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001118 if (x == 0.0) {
Benjamin Peterson1ed66702010-07-02 19:50:16 +00001119 if (copysign(1.0, x) == -1.0)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001120 return PyUnicode_FromString("-0x0.0p+0");
1121 else
1122 return PyUnicode_FromString("0x0.0p+0");
1123 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001124
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001125 m = frexp(fabs(x), &e);
1126 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1127 m = ldexp(m, shift);
1128 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001129
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001130 si = 0;
1131 s[si] = char_from_hex((int)m);
1132 si++;
1133 m -= (int)m;
1134 s[si] = '.';
1135 si++;
1136 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1137 m *= 16.0;
1138 s[si] = char_from_hex((int)m);
1139 si++;
1140 m -= (int)m;
1141 }
1142 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001143
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001144 if (e < 0) {
1145 esign = (int)'-';
1146 e = -e;
1147 }
1148 else
1149 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001151 if (x < 0.0)
1152 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1153 else
1154 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001155}
1156
1157PyDoc_STRVAR(float_hex_doc,
1158"float.hex() -> string\n\
1159\n\
1160Return a hexadecimal representation of a floating-point number.\n\
1161>>> (-0.1).hex()\n\
1162'-0x1.999999999999ap-4'\n\
1163>>> 3.14159.hex()\n\
1164'0x1.921f9f01b866ep+1'");
1165
1166/* Convert a hexadecimal string to a float. */
1167
1168static PyObject *
1169float_fromhex(PyObject *cls, PyObject *arg)
1170{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001171 PyObject *result_as_float, *result;
1172 double x;
1173 long exp, top_exp, lsb, key_digit;
1174 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1175 int half_eps, digit, round_up, negate=0;
1176 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001177
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001178 /*
1179 * For the sake of simplicity and correctness, we impose an artificial
1180 * limit on ndigits, the total number of hex digits in the coefficient
1181 * The limit is chosen to ensure that, writing exp for the exponent,
1182 *
1183 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1184 * guaranteed to overflow (provided it's nonzero)
1185 *
1186 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1187 * guaranteed to underflow to 0.
1188 *
1189 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1190 * overflow in the calculation of exp and top_exp below.
1191 *
1192 * More specifically, ndigits is assumed to satisfy the following
1193 * inequalities:
1194 *
1195 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1196 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1197 *
1198 * If either of these inequalities is not satisfied, a ValueError is
1199 * raised. Otherwise, write x for the value of the hex string, and
1200 * assume x is nonzero. Then
1201 *
1202 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1203 *
1204 * Now if exp > LONG_MAX/2 then:
1205 *
1206 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1207 * = DBL_MAX_EXP
1208 *
1209 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1210 * double, so overflows. If exp < LONG_MIN/2, then
1211 *
1212 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1213 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1214 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1215 *
1216 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1217 * when converted to a C double.
1218 *
1219 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1220 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1221 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001222
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001223 s = _PyUnicode_AsStringAndSize(arg, &length);
1224 if (s == NULL)
1225 return NULL;
1226 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001228 /********************
1229 * Parse the string *
1230 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001232 /* leading whitespace */
1233 while (Py_ISSPACE(*s))
1234 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001235
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001236 /* infinities and nans */
1237 x = _Py_parse_inf_or_nan(s, &coeff_end);
1238 if (coeff_end != s) {
1239 s = coeff_end;
1240 goto finished;
1241 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001242
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001243 /* optional sign */
1244 if (*s == '-') {
1245 s++;
1246 negate = 1;
1247 }
1248 else if (*s == '+')
1249 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001251 /* [0x] */
1252 s_store = s;
1253 if (*s == '0') {
1254 s++;
1255 if (*s == 'x' || *s == 'X')
1256 s++;
1257 else
1258 s = s_store;
1259 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001260
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001261 /* coefficient: <integer> [. <fraction>] */
1262 coeff_start = s;
1263 while (hex_from_char(*s) >= 0)
1264 s++;
1265 s_store = s;
1266 if (*s == '.') {
1267 s++;
1268 while (hex_from_char(*s) >= 0)
1269 s++;
1270 coeff_end = s-1;
1271 }
1272 else
1273 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001275 /* ndigits = total # of hex digits; fdigits = # after point */
1276 ndigits = coeff_end - coeff_start;
1277 fdigits = coeff_end - s_store;
1278 if (ndigits == 0)
1279 goto parse_error;
1280 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1281 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1282 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001283
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001284 /* [p <exponent>] */
1285 if (*s == 'p' || *s == 'P') {
1286 s++;
1287 exp_start = s;
1288 if (*s == '-' || *s == '+')
1289 s++;
1290 if (!('0' <= *s && *s <= '9'))
1291 goto parse_error;
1292 s++;
1293 while ('0' <= *s && *s <= '9')
1294 s++;
1295 exp = strtol(exp_start, NULL, 10);
1296 }
1297 else
1298 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001299
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001300/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001301#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1302 coeff_end-(j) : \
1303 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001305 /*******************************************
1306 * Compute rounded value of the hex string *
1307 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001309 /* Discard leading zeros, and catch extreme overflow and underflow */
1310 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1311 ndigits--;
1312 if (ndigits == 0 || exp < LONG_MIN/2) {
1313 x = 0.0;
1314 goto finished;
1315 }
1316 if (exp > LONG_MAX/2)
1317 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001318
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001319 /* Adjust exponent for fractional part. */
1320 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001321
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001322 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1323 top_exp = exp + 4*((long)ndigits - 1);
1324 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1325 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001326
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001327 /* catch almost all nonextreme cases of overflow and underflow here */
1328 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1329 x = 0.0;
1330 goto finished;
1331 }
1332 if (top_exp > DBL_MAX_EXP)
1333 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001334
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001335 /* lsb = exponent of least significant bit of the *rounded* value.
1336 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1337 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001339 x = 0.0;
1340 if (exp >= lsb) {
1341 /* no rounding required */
1342 for (i = ndigits-1; i >= 0; i--)
1343 x = 16.0*x + HEX_DIGIT(i);
1344 x = ldexp(x, (int)(exp));
1345 goto finished;
1346 }
1347 /* rounding required. key_digit is the index of the hex digit
1348 containing the first bit to be rounded away. */
1349 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1350 key_digit = (lsb - exp - 1) / 4;
1351 for (i = ndigits-1; i > key_digit; i--)
1352 x = 16.0*x + HEX_DIGIT(i);
1353 digit = HEX_DIGIT(key_digit);
1354 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001355
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001356 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1357 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1358 if ((digit & half_eps) != 0) {
1359 round_up = 0;
1360 if ((digit & (3*half_eps-1)) != 0 ||
1361 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1362 round_up = 1;
1363 else
1364 for (i = key_digit-1; i >= 0; i--)
1365 if (HEX_DIGIT(i) != 0) {
1366 round_up = 1;
1367 break;
1368 }
1369 if (round_up == 1) {
1370 x += 2*half_eps;
1371 if (top_exp == DBL_MAX_EXP &&
1372 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1373 /* overflow corner case: pre-rounded value <
1374 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1375 goto overflow_error;
1376 }
1377 }
1378 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001379
1380 finished:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001381 /* optional trailing whitespace leading to the end of the string */
1382 while (Py_ISSPACE(*s))
1383 s++;
1384 if (s != s_end)
1385 goto parse_error;
1386 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1387 if (result_as_float == NULL)
1388 return NULL;
1389 result = PyObject_CallObject(cls, result_as_float);
1390 Py_DECREF(result_as_float);
1391 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001392
1393 overflow_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001394 PyErr_SetString(PyExc_OverflowError,
1395 "hexadecimal value too large to represent as a float");
1396 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001397
1398 parse_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001399 PyErr_SetString(PyExc_ValueError,
1400 "invalid hexadecimal floating-point string");
1401 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001402
1403 insane_length_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001404 PyErr_SetString(PyExc_ValueError,
1405 "hexadecimal string too long to convert");
1406 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001407}
1408
1409PyDoc_STRVAR(float_fromhex_doc,
1410"float.fromhex(string) -> float\n\
1411\n\
1412Create a floating-point number from a hexadecimal string.\n\
1413>>> float.fromhex('0x1.ffffp10')\n\
14142047.984375\n\
1415>>> float.fromhex('-0x1p-1074')\n\
1416-4.9406564584124654e-324");
1417
1418
Christian Heimes26855632008-01-27 23:50:43 +00001419static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001420float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001421{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001422 double self;
1423 double float_part;
1424 int exponent;
1425 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001426
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001427 PyObject *prev;
1428 PyObject *py_exponent = NULL;
1429 PyObject *numerator = NULL;
1430 PyObject *denominator = NULL;
1431 PyObject *result_pair = NULL;
1432 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001433
1434#define INPLACE_UPDATE(obj, call) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001435 prev = obj; \
1436 obj = call; \
1437 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001438
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001439 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001440
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001441 if (Py_IS_INFINITY(self)) {
1442 PyErr_SetString(PyExc_OverflowError,
1443 "Cannot pass infinity to float.as_integer_ratio.");
1444 return NULL;
1445 }
Christian Heimes26855632008-01-27 23:50:43 +00001446#ifdef Py_NAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001447 if (Py_IS_NAN(self)) {
1448 PyErr_SetString(PyExc_ValueError,
1449 "Cannot pass NaN to float.as_integer_ratio.");
1450 return NULL;
1451 }
Christian Heimes26855632008-01-27 23:50:43 +00001452#endif
1453
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001454 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1455 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1456 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001458 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1459 float_part *= 2.0;
1460 exponent--;
1461 }
1462 /* self == float_part * 2**exponent exactly and float_part is integral.
1463 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1464 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001465
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001466 numerator = PyLong_FromDouble(float_part);
1467 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001468
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001469 /* fold in 2**exponent */
1470 denominator = PyLong_FromLong(1);
1471 py_exponent = PyLong_FromLong(labs((long)exponent));
1472 if (py_exponent == NULL) goto error;
1473 INPLACE_UPDATE(py_exponent,
1474 long_methods->nb_lshift(denominator, py_exponent));
1475 if (py_exponent == NULL) goto error;
1476 if (exponent > 0) {
1477 INPLACE_UPDATE(numerator,
1478 long_methods->nb_multiply(numerator, py_exponent));
1479 if (numerator == NULL) goto error;
1480 }
1481 else {
1482 Py_DECREF(denominator);
1483 denominator = py_exponent;
1484 py_exponent = NULL;
1485 }
1486
1487 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001488
1489#undef INPLACE_UPDATE
1490error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001491 Py_XDECREF(py_exponent);
1492 Py_XDECREF(denominator);
1493 Py_XDECREF(numerator);
1494 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001495}
1496
1497PyDoc_STRVAR(float_as_integer_ratio_doc,
1498"float.as_integer_ratio() -> (int, int)\n"
1499"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001500"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1501"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001502"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001503"\n"
1504">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001505"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001506">>> (0.0).as_integer_ratio()\n"
1507"(0, 1)\n"
1508">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001509"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001510
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001511
Jeremy Hylton938ace62002-07-17 16:30:39 +00001512static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001513float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1514
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515static PyObject *
1516float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1517{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001518 PyObject *x = Py_False; /* Integer zero */
1519 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001521 if (type != &PyFloat_Type)
1522 return float_subtype_new(type, args, kwds); /* Wimp out */
1523 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1524 return NULL;
1525 /* If it's a string, but not a string subclass, use
1526 PyFloat_FromString. */
1527 if (PyUnicode_CheckExact(x))
1528 return PyFloat_FromString(x);
1529 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001530}
1531
Guido van Rossumbef14172001-08-29 15:47:46 +00001532/* Wimpy, slow approach to tp_new calls for subtypes of float:
1533 first create a regular float from whatever arguments we got,
1534 then allocate a subtype instance and initialize its ob_fval
1535 from the regular float. The regular float is then thrown away.
1536*/
1537static PyObject *
1538float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1539{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001540 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001541
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001542 assert(PyType_IsSubtype(type, &PyFloat_Type));
1543 tmp = float_new(&PyFloat_Type, args, kwds);
1544 if (tmp == NULL)
1545 return NULL;
1546 assert(PyFloat_CheckExact(tmp));
1547 newobj = type->tp_alloc(type, 0);
1548 if (newobj == NULL) {
1549 Py_DECREF(tmp);
1550 return NULL;
1551 }
1552 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1553 Py_DECREF(tmp);
1554 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001555}
1556
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001557static PyObject *
1558float_getnewargs(PyFloatObject *v)
1559{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001560 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001561}
1562
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001563/* this is for the benefit of the pack/unpack routines below */
1564
1565typedef enum {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001566 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001567} float_format_type;
1568
1569static float_format_type double_format, float_format;
1570static float_format_type detected_double_format, detected_float_format;
1571
1572static PyObject *
1573float_getformat(PyTypeObject *v, PyObject* arg)
1574{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001575 char* s;
1576 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001577
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001578 if (!PyUnicode_Check(arg)) {
1579 PyErr_Format(PyExc_TypeError,
1580 "__getformat__() argument must be string, not %.500s",
1581 Py_TYPE(arg)->tp_name);
1582 return NULL;
1583 }
1584 s = _PyUnicode_AsString(arg);
1585 if (s == NULL)
1586 return NULL;
1587 if (strcmp(s, "double") == 0) {
1588 r = double_format;
1589 }
1590 else if (strcmp(s, "float") == 0) {
1591 r = float_format;
1592 }
1593 else {
1594 PyErr_SetString(PyExc_ValueError,
1595 "__getformat__() argument 1 must be "
1596 "'double' or 'float'");
1597 return NULL;
1598 }
1599
1600 switch (r) {
1601 case unknown_format:
1602 return PyUnicode_FromString("unknown");
1603 case ieee_little_endian_format:
1604 return PyUnicode_FromString("IEEE, little-endian");
1605 case ieee_big_endian_format:
1606 return PyUnicode_FromString("IEEE, big-endian");
1607 default:
1608 Py_FatalError("insane float_format or double_format");
1609 return NULL;
1610 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611}
1612
1613PyDoc_STRVAR(float_getformat_doc,
1614"float.__getformat__(typestr) -> string\n"
1615"\n"
1616"You probably don't want to use this function. It exists mainly to be\n"
1617"used in Python's test suite.\n"
1618"\n"
1619"typestr must be 'double' or 'float'. This function returns whichever of\n"
1620"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1621"format of floating point numbers used by the C type named by typestr.");
1622
1623static PyObject *
1624float_setformat(PyTypeObject *v, PyObject* args)
1625{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001626 char* typestr;
1627 char* format;
1628 float_format_type f;
1629 float_format_type detected;
1630 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001631
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001632 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1633 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001634
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001635 if (strcmp(typestr, "double") == 0) {
1636 p = &double_format;
1637 detected = detected_double_format;
1638 }
1639 else if (strcmp(typestr, "float") == 0) {
1640 p = &float_format;
1641 detected = detected_float_format;
1642 }
1643 else {
1644 PyErr_SetString(PyExc_ValueError,
1645 "__setformat__() argument 1 must "
1646 "be 'double' or 'float'");
1647 return NULL;
1648 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001649
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001650 if (strcmp(format, "unknown") == 0) {
1651 f = unknown_format;
1652 }
1653 else if (strcmp(format, "IEEE, little-endian") == 0) {
1654 f = ieee_little_endian_format;
1655 }
1656 else if (strcmp(format, "IEEE, big-endian") == 0) {
1657 f = ieee_big_endian_format;
1658 }
1659 else {
1660 PyErr_SetString(PyExc_ValueError,
1661 "__setformat__() argument 2 must be "
1662 "'unknown', 'IEEE, little-endian' or "
1663 "'IEEE, big-endian'");
1664 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001665
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001666 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001667
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001668 if (f != unknown_format && f != detected) {
1669 PyErr_Format(PyExc_ValueError,
1670 "can only set %s format to 'unknown' or the "
1671 "detected platform value", typestr);
1672 return NULL;
1673 }
1674
1675 *p = f;
1676 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001677}
1678
1679PyDoc_STRVAR(float_setformat_doc,
1680"float.__setformat__(typestr, fmt) -> None\n"
1681"\n"
1682"You probably don't want to use this function. It exists mainly to be\n"
1683"used in Python's test suite.\n"
1684"\n"
1685"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1686"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1687"one of the latter two if it appears to match the underlying C reality.\n"
1688"\n"
1689"Overrides the automatic determination of C-level floating point type.\n"
1690"This affects how floats are converted to and from binary strings.");
1691
Guido van Rossumb43daf72007-08-01 18:08:08 +00001692static PyObject *
1693float_getzero(PyObject *v, void *closure)
1694{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001695 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001696}
1697
Eric Smith8c663262007-08-25 02:26:07 +00001698static PyObject *
1699float__format__(PyObject *self, PyObject *args)
1700{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001701 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001702
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001703 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1704 return NULL;
1705 return _PyFloat_FormatAdvanced(self,
1706 PyUnicode_AS_UNICODE(format_spec),
1707 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001708}
1709
1710PyDoc_STRVAR(float__format__doc,
1711"float.__format__(format_spec) -> string\n"
1712"\n"
1713"Formats the float according to format_spec.");
1714
1715
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001716static PyMethodDef float_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001717 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1718 "Returns self, the complex conjugate of any float."},
1719 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1720 "Returns the Integral closest to x between 0 and x."},
1721 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1722 "Returns the Integral closest to x, rounding half toward even.\n"
1723 "When an argument is passed, works like built-in round(x, ndigits)."},
1724 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1725 float_as_integer_ratio_doc},
1726 {"fromhex", (PyCFunction)float_fromhex,
1727 METH_O|METH_CLASS, float_fromhex_doc},
1728 {"hex", (PyCFunction)float_hex,
1729 METH_NOARGS, float_hex_doc},
1730 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1731 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001732#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001733 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1734 "Returns True if the float is positive or negative infinite."},
1735 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1736 "Returns True if the float is finite, neither infinite nor NaN."},
1737 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1738 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001739#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001740 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1741 {"__getformat__", (PyCFunction)float_getformat,
1742 METH_O|METH_CLASS, float_getformat_doc},
1743 {"__setformat__", (PyCFunction)float_setformat,
1744 METH_VARARGS|METH_CLASS, float_setformat_doc},
1745 {"__format__", (PyCFunction)float__format__,
1746 METH_VARARGS, float__format__doc},
1747 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001748};
1749
Guido van Rossumb43daf72007-08-01 18:08:08 +00001750static PyGetSetDef float_getset[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001751 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001752 (getter)float_float, (setter)NULL,
1753 "the real part of a complex number",
1754 NULL},
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001755 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001756 (getter)float_getzero, (setter)NULL,
1757 "the imaginary part of a complex number",
1758 NULL},
1759 {NULL} /* Sentinel */
1760};
1761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001762PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763"float(x) -> floating point number\n\
1764\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001765Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766
1767
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001768static PyNumberMethods float_as_number = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001769 float_add, /*nb_add*/
1770 float_sub, /*nb_subtract*/
1771 float_mul, /*nb_multiply*/
1772 float_rem, /*nb_remainder*/
1773 float_divmod, /*nb_divmod*/
1774 float_pow, /*nb_power*/
1775 (unaryfunc)float_neg, /*nb_negative*/
1776 (unaryfunc)float_float, /*nb_positive*/
1777 (unaryfunc)float_abs, /*nb_absolute*/
1778 (inquiry)float_bool, /*nb_bool*/
1779 0, /*nb_invert*/
1780 0, /*nb_lshift*/
1781 0, /*nb_rshift*/
1782 0, /*nb_and*/
1783 0, /*nb_xor*/
1784 0, /*nb_or*/
1785 float_trunc, /*nb_int*/
1786 0, /*nb_reserved*/
1787 float_float, /*nb_float*/
1788 0, /* nb_inplace_add */
1789 0, /* nb_inplace_subtract */
1790 0, /* nb_inplace_multiply */
1791 0, /* nb_inplace_remainder */
1792 0, /* nb_inplace_power */
1793 0, /* nb_inplace_lshift */
1794 0, /* nb_inplace_rshift */
1795 0, /* nb_inplace_and */
1796 0, /* nb_inplace_xor */
1797 0, /* nb_inplace_or */
1798 float_floor_div, /* nb_floor_divide */
1799 float_div, /* nb_true_divide */
1800 0, /* nb_inplace_floor_divide */
1801 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001802};
1803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001804PyTypeObject PyFloat_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001805 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1806 "float",
1807 sizeof(PyFloatObject),
1808 0,
1809 (destructor)float_dealloc, /* tp_dealloc */
1810 0, /* tp_print */
1811 0, /* tp_getattr */
1812 0, /* tp_setattr */
1813 0, /* tp_reserved */
1814 (reprfunc)float_repr, /* tp_repr */
1815 &float_as_number, /* tp_as_number */
1816 0, /* tp_as_sequence */
1817 0, /* tp_as_mapping */
1818 (hashfunc)float_hash, /* tp_hash */
1819 0, /* tp_call */
1820 (reprfunc)float_str, /* tp_str */
1821 PyObject_GenericGetAttr, /* tp_getattro */
1822 0, /* tp_setattro */
1823 0, /* tp_as_buffer */
1824 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1825 float_doc, /* tp_doc */
1826 0, /* tp_traverse */
1827 0, /* tp_clear */
1828 float_richcompare, /* tp_richcompare */
1829 0, /* tp_weaklistoffset */
1830 0, /* tp_iter */
1831 0, /* tp_iternext */
1832 float_methods, /* tp_methods */
1833 0, /* tp_members */
1834 float_getset, /* tp_getset */
1835 0, /* tp_base */
1836 0, /* tp_dict */
1837 0, /* tp_descr_get */
1838 0, /* tp_descr_set */
1839 0, /* tp_dictoffset */
1840 0, /* tp_init */
1841 0, /* tp_alloc */
1842 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001843};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001844
1845void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001846_PyFloat_Init(void)
1847{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001848 /* We attempt to determine if this machine is using IEEE
1849 floating point formats by peering at the bits of some
1850 carefully chosen values. If it looks like we are on an
1851 IEEE platform, the float packing/unpacking routines can
1852 just copy bits, if not they resort to arithmetic & shifts
1853 and masks. The shifts & masks approach works on all finite
1854 values, but what happens to infinities, NaNs and signed
1855 zeroes on packing is an accident, and attempting to unpack
1856 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001857
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001858 Note that if we're on some whacked-out platform which uses
1859 IEEE formats but isn't strictly little-endian or big-
1860 endian, we will fall back to the portable shifts & masks
1861 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001862
1863#if SIZEOF_DOUBLE == 8
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001864 {
1865 double x = 9006104071832581.0;
1866 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1867 detected_double_format = ieee_big_endian_format;
1868 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1869 detected_double_format = ieee_little_endian_format;
1870 else
1871 detected_double_format = unknown_format;
1872 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001873#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001874 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001875#endif
1876
1877#if SIZEOF_FLOAT == 4
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001878 {
1879 float y = 16711938.0;
1880 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1881 detected_float_format = ieee_big_endian_format;
1882 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1883 detected_float_format = ieee_little_endian_format;
1884 else
1885 detected_float_format = unknown_format;
1886 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001888 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001889#endif
1890
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001891 double_format = detected_double_format;
1892 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001893
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001894 /* Init float info */
1895 if (FloatInfoType.tp_name == 0)
1896 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001897}
1898
Georg Brandl2ee470f2008-07-16 12:55:28 +00001899int
1900PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001901{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001902 PyFloatObject *p;
1903 PyFloatBlock *list, *next;
1904 int i;
1905 int u; /* remaining unfreed floats per block */
1906 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001907
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001908 list = block_list;
1909 block_list = NULL;
1910 free_list = NULL;
1911 while (list != NULL) {
1912 u = 0;
1913 for (i = 0, p = &list->objects[0];
1914 i < N_FLOATOBJECTS;
1915 i++, p++) {
1916 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1917 u++;
1918 }
1919 next = list->next;
1920 if (u) {
1921 list->next = block_list;
1922 block_list = list;
1923 for (i = 0, p = &list->objects[0];
1924 i < N_FLOATOBJECTS;
1925 i++, p++) {
1926 if (!PyFloat_CheckExact(p) ||
1927 Py_REFCNT(p) == 0) {
1928 Py_TYPE(p) = (struct _typeobject *)
1929 free_list;
1930 free_list = p;
1931 }
1932 }
1933 }
1934 else {
1935 PyMem_FREE(list);
1936 }
1937 freelist_size += u;
1938 list = next;
1939 }
1940 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001941}
1942
1943void
1944PyFloat_Fini(void)
1945{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001946 PyFloatObject *p;
1947 PyFloatBlock *list;
1948 int i;
1949 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001950
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001951 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001952
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001953 if (!Py_VerboseFlag)
1954 return;
1955 fprintf(stderr, "# cleanup floats");
1956 if (!u) {
1957 fprintf(stderr, "\n");
1958 }
1959 else {
1960 fprintf(stderr,
1961 ": %d unfreed float%s\n",
1962 u, u == 1 ? "" : "s");
1963 }
1964 if (Py_VerboseFlag > 1) {
1965 list = block_list;
1966 while (list != NULL) {
1967 for (i = 0, p = &list->objects[0];
1968 i < N_FLOATOBJECTS;
1969 i++, p++) {
1970 if (PyFloat_CheckExact(p) &&
1971 Py_REFCNT(p) != 0) {
1972 char *buf = PyOS_double_to_string(
1973 PyFloat_AS_DOUBLE(p), 'r',
1974 0, 0, NULL);
1975 if (buf) {
1976 /* XXX(twouters) cast
1977 refcount to long
1978 until %zd is
1979 universally
1980 available
1981 */
1982 fprintf(stderr,
1983 "# <float at %p, refcnt=%ld, val=%s>\n",
1984 p, (long)Py_REFCNT(p), buf);
1985 PyMem_Free(buf);
1986 }
1987 }
1988 }
1989 list = list->next;
1990 }
1991 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001992}
Tim Peters9905b942003-03-20 20:53:32 +00001993
1994/*----------------------------------------------------------------------------
1995 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001996 */
1997int
1998_PyFloat_Pack4(double x, unsigned char *p, int le)
1999{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002000 if (float_format == unknown_format) {
2001 unsigned char sign;
2002 int e;
2003 double f;
2004 unsigned int fbits;
2005 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002006
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002007 if (le) {
2008 p += 3;
2009 incr = -1;
2010 }
Tim Peters9905b942003-03-20 20:53:32 +00002011
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002012 if (x < 0) {
2013 sign = 1;
2014 x = -x;
2015 }
2016 else
2017 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002018
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002019 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002020
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002021 /* Normalize f to be in the range [1.0, 2.0) */
2022 if (0.5 <= f && f < 1.0) {
2023 f *= 2.0;
2024 e--;
2025 }
2026 else if (f == 0.0)
2027 e = 0;
2028 else {
2029 PyErr_SetString(PyExc_SystemError,
2030 "frexp() result out of range");
2031 return -1;
2032 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002033
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002034 if (e >= 128)
2035 goto Overflow;
2036 else if (e < -126) {
2037 /* Gradual underflow */
2038 f = ldexp(f, 126 + e);
2039 e = 0;
2040 }
2041 else if (!(e == 0 && f == 0.0)) {
2042 e += 127;
2043 f -= 1.0; /* Get rid of leading 1 */
2044 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002045
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002046 f *= 8388608.0; /* 2**23 */
2047 fbits = (unsigned int)(f + 0.5); /* Round */
2048 assert(fbits <= 8388608);
2049 if (fbits >> 23) {
2050 /* The carry propagated out of a string of 23 1 bits. */
2051 fbits = 0;
2052 ++e;
2053 if (e >= 255)
2054 goto Overflow;
2055 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002056
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002057 /* First byte */
2058 *p = (sign << 7) | (e >> 1);
2059 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002061 /* Second byte */
2062 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2063 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002064
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002065 /* Third byte */
2066 *p = (fbits >> 8) & 0xFF;
2067 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002068
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002069 /* Fourth byte */
2070 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002071
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002072 /* Done */
2073 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002074
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002075 }
2076 else {
2077 float y = (float)x;
2078 const char *s = (char*)&y;
2079 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002080
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002081 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2082 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002083
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002084 if ((float_format == ieee_little_endian_format && !le)
2085 || (float_format == ieee_big_endian_format && le)) {
2086 p += 3;
2087 incr = -1;
2088 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002089
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002090 for (i = 0; i < 4; i++) {
2091 *p = *s++;
2092 p += incr;
2093 }
2094 return 0;
2095 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002096 Overflow:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002097 PyErr_SetString(PyExc_OverflowError,
2098 "float too large to pack with f format");
2099 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002100}
2101
2102int
2103_PyFloat_Pack8(double x, unsigned char *p, int le)
2104{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002105 if (double_format == unknown_format) {
2106 unsigned char sign;
2107 int e;
2108 double f;
2109 unsigned int fhi, flo;
2110 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002111
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002112 if (le) {
2113 p += 7;
2114 incr = -1;
2115 }
Tim Peters9905b942003-03-20 20:53:32 +00002116
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002117 if (x < 0) {
2118 sign = 1;
2119 x = -x;
2120 }
2121 else
2122 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002123
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002124 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002125
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002126 /* Normalize f to be in the range [1.0, 2.0) */
2127 if (0.5 <= f && f < 1.0) {
2128 f *= 2.0;
2129 e--;
2130 }
2131 else if (f == 0.0)
2132 e = 0;
2133 else {
2134 PyErr_SetString(PyExc_SystemError,
2135 "frexp() result out of range");
2136 return -1;
2137 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002139 if (e >= 1024)
2140 goto Overflow;
2141 else if (e < -1022) {
2142 /* Gradual underflow */
2143 f = ldexp(f, 1022 + e);
2144 e = 0;
2145 }
2146 else if (!(e == 0 && f == 0.0)) {
2147 e += 1023;
2148 f -= 1.0; /* Get rid of leading 1 */
2149 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002151 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2152 f *= 268435456.0; /* 2**28 */
2153 fhi = (unsigned int)f; /* Truncate */
2154 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002155
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002156 f -= (double)fhi;
2157 f *= 16777216.0; /* 2**24 */
2158 flo = (unsigned int)(f + 0.5); /* Round */
2159 assert(flo <= 16777216);
2160 if (flo >> 24) {
2161 /* The carry propagated out of a string of 24 1 bits. */
2162 flo = 0;
2163 ++fhi;
2164 if (fhi >> 28) {
2165 /* And it also progagated out of the next 28 bits. */
2166 fhi = 0;
2167 ++e;
2168 if (e >= 2047)
2169 goto Overflow;
2170 }
2171 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002172
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002173 /* First byte */
2174 *p = (sign << 7) | (e >> 4);
2175 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002176
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002177 /* Second byte */
2178 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2179 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002180
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002181 /* Third byte */
2182 *p = (fhi >> 16) & 0xFF;
2183 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002184
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002185 /* Fourth byte */
2186 *p = (fhi >> 8) & 0xFF;
2187 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002189 /* Fifth byte */
2190 *p = fhi & 0xFF;
2191 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002192
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002193 /* Sixth byte */
2194 *p = (flo >> 16) & 0xFF;
2195 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002197 /* Seventh byte */
2198 *p = (flo >> 8) & 0xFF;
2199 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002201 /* Eighth byte */
2202 *p = flo & 0xFF;
2203 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002205 /* Done */
2206 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002207
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002208 Overflow:
2209 PyErr_SetString(PyExc_OverflowError,
2210 "float too large to pack with d format");
2211 return -1;
2212 }
2213 else {
2214 const char *s = (char*)&x;
2215 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002216
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002217 if ((double_format == ieee_little_endian_format && !le)
2218 || (double_format == ieee_big_endian_format && le)) {
2219 p += 7;
2220 incr = -1;
2221 }
2222
2223 for (i = 0; i < 8; i++) {
2224 *p = *s++;
2225 p += incr;
2226 }
2227 return 0;
2228 }
Tim Peters9905b942003-03-20 20:53:32 +00002229}
2230
2231double
2232_PyFloat_Unpack4(const unsigned char *p, int le)
2233{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002234 if (float_format == unknown_format) {
2235 unsigned char sign;
2236 int e;
2237 unsigned int f;
2238 double x;
2239 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002240
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002241 if (le) {
2242 p += 3;
2243 incr = -1;
2244 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002246 /* First byte */
2247 sign = (*p >> 7) & 1;
2248 e = (*p & 0x7F) << 1;
2249 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002251 /* Second byte */
2252 e |= (*p >> 7) & 1;
2253 f = (*p & 0x7F) << 16;
2254 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002255
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002256 if (e == 255) {
2257 PyErr_SetString(
2258 PyExc_ValueError,
2259 "can't unpack IEEE 754 special value "
2260 "on non-IEEE platform");
2261 return -1;
2262 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002263
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002264 /* Third byte */
2265 f |= *p << 8;
2266 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002267
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002268 /* Fourth byte */
2269 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002270
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002271 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002272
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002273 /* XXX This sadly ignores Inf/NaN issues */
2274 if (e == 0)
2275 e = -126;
2276 else {
2277 x += 1.0;
2278 e -= 127;
2279 }
2280 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002281
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002282 if (sign)
2283 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002284
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002285 return x;
2286 }
2287 else {
2288 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002289
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002290 if ((float_format == ieee_little_endian_format && !le)
2291 || (float_format == ieee_big_endian_format && le)) {
2292 char buf[4];
2293 char *d = &buf[3];
2294 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002295
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002296 for (i = 0; i < 4; i++) {
2297 *d-- = *p++;
2298 }
2299 memcpy(&x, buf, 4);
2300 }
2301 else {
2302 memcpy(&x, p, 4);
2303 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002304
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002305 return x;
2306 }
Tim Peters9905b942003-03-20 20:53:32 +00002307}
2308
2309double
2310_PyFloat_Unpack8(const unsigned char *p, int le)
2311{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002312 if (double_format == unknown_format) {
2313 unsigned char sign;
2314 int e;
2315 unsigned int fhi, flo;
2316 double x;
2317 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002318
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002319 if (le) {
2320 p += 7;
2321 incr = -1;
2322 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002324 /* First byte */
2325 sign = (*p >> 7) & 1;
2326 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002328 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002330 /* Second byte */
2331 e |= (*p >> 4) & 0xF;
2332 fhi = (*p & 0xF) << 24;
2333 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002334
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002335 if (e == 2047) {
2336 PyErr_SetString(
2337 PyExc_ValueError,
2338 "can't unpack IEEE 754 special value "
2339 "on non-IEEE platform");
2340 return -1.0;
2341 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002342
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002343 /* Third byte */
2344 fhi |= *p << 16;
2345 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002346
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002347 /* Fourth byte */
2348 fhi |= *p << 8;
2349 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002350
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002351 /* Fifth byte */
2352 fhi |= *p;
2353 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002355 /* Sixth byte */
2356 flo = *p << 16;
2357 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002358
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002359 /* Seventh byte */
2360 flo |= *p << 8;
2361 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002363 /* Eighth byte */
2364 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002365
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002366 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2367 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002368
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002369 if (e == 0)
2370 e = -1022;
2371 else {
2372 x += 1.0;
2373 e -= 1023;
2374 }
2375 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002376
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002377 if (sign)
2378 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002379
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002380 return x;
2381 }
2382 else {
2383 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002384
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002385 if ((double_format == ieee_little_endian_format && !le)
2386 || (double_format == ieee_big_endian_format && le)) {
2387 char buf[8];
2388 char *d = &buf[7];
2389 int i;
2390
2391 for (i = 0; i < 8; i++) {
2392 *d-- = *p++;
2393 }
2394 memcpy(&x, buf, 8);
2395 }
2396 else {
2397 memcpy(&x, p, 8);
2398 }
2399
2400 return x;
2401 }
Tim Peters9905b942003-03-20 20:53:32 +00002402}