blob: 6a2af743affd0abb9cb39c5026c08d64fe08108e [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. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000029#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
30#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
31#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 {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000034 struct _floatblock *next;
35 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000036};
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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000046 PyFloatObject *p, *q;
47 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
48 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
49 if (p == NULL)
50 return (PyFloatObject *) PyErr_NoMemory();
51 ((PyFloatBlock *)p)->next = block_list;
52 block_list = (PyFloatBlock *)p;
53 p = &((PyFloatBlock *)p)->objects[0];
54 q = p + N_FLOATOBJECTS;
55 while (--q > p)
56 Py_TYPE(q) = (struct _typeobject *)(q-1);
57 Py_TYPE(q) = NULL;
58 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000059}
60
Christian Heimes93852662007-12-01 12:22:32 +000061double
62PyFloat_GetMax(void)
63{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000064 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000065}
66
67double
68PyFloat_GetMin(void)
69{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000070 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000071}
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[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000083 {"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}
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000100};
101
102static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000103 "sys.floatinfo", /* name */
104 floatinfo__doc__, /* doc */
105 floatinfo_fields, /* fields */
106 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000107};
108
Christian Heimes93852662007-12-01 12:22:32 +0000109PyObject *
110PyFloat_GetInfo(void)
111{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000112 PyObject* floatinfo;
113 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000114
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +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) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000122#define SetDblFlag(flag) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000124
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +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);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000136#undef SetIntFlag
137#undef SetDblFlag
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000138
139 if (PyErr_Occurred()) {
140 Py_CLEAR(floatinfo);
141 return NULL;
142 }
143 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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
154 /* Inline PyObject_New */
155 op = free_list;
156 free_list = (PyFloatObject *)Py_TYPE(op);
157 PyObject_INIT(op, &PyFloat_Type);
158 op->ob_fval = fval;
159 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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000165 const char *s, *last, *end;
166 double x;
167 char buffer[256]; /* for errors */
168 char *s_buffer = NULL;
169 Py_ssize_t len;
170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000172 if (PyUnicode_Check(v)) {
173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
177 PyUnicode_GET_SIZE(v),
178 s_buffer,
179 NULL))
180 goto error;
181 s = s_buffer;
182 len = strlen(s);
183 }
184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
186 "float() argument must be a string or a number");
187 return NULL;
188 }
189 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000190
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000191 while (Py_ISSPACE(*s))
192 s++;
193 /* We don't care about overflow or underflow. If the platform
194 * supports them, infinities and signed zeroes (on underflow) are
195 * fine. */
196 x = PyOS_string_to_double(s, (char **)&end, NULL);
197 if (x == -1.0 && PyErr_Occurred())
198 goto error;
199 while (Py_ISSPACE(*end))
200 end++;
201 if (end == last)
202 result = PyFloat_FromDouble(x);
203 else {
204 PyOS_snprintf(buffer, sizeof(buffer),
205 "invalid literal for float(): %.200s", s);
206 PyErr_SetString(PyExc_ValueError, buffer);
207 result = NULL;
208 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000209
Guido van Rossum2be161d2007-05-15 20:43:51 +0000210 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000211 if (s_buffer)
212 PyMem_FREE(s_buffer);
213 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214}
215
Guido van Rossum234f9421993-06-17 12:35:49 +0000216static void
Fred Drakefd99de62000-07-09 05:02:18 +0000217float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000218{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000219 if (PyFloat_CheckExact(op)) {
220 Py_TYPE(op) = (struct _typeobject *)free_list;
221 free_list = op;
222 }
223 else
224 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000225}
226
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227double
Fred Drakefd99de62000-07-09 05:02:18 +0000228PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000230 PyNumberMethods *nb;
231 PyFloatObject *fo;
232 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000233
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000234 if (op && PyFloat_Check(op))
235 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000236
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000237 if (op == NULL) {
238 PyErr_BadArgument();
239 return -1;
240 }
Tim Petersd2364e82001-11-01 20:09:42 +0000241
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000242 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
243 PyErr_SetString(PyExc_TypeError, "a float is required");
244 return -1;
245 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000246
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000247 fo = (PyFloatObject*) (*nb->nb_float) (op);
248 if (fo == NULL)
249 return -1;
250 if (!PyFloat_Check(fo)) {
251 PyErr_SetString(PyExc_TypeError,
252 "nb_float should return float object");
253 return -1;
254 }
Tim Petersd2364e82001-11-01 20:09:42 +0000255
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000256 val = PyFloat_AS_DOUBLE(fo);
257 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000259 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Neil Schemenauer32117e52001-01-04 01:44:34 +0000262/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000263 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000264 set to NULL, and the function invoking this macro returns NULL. If
265 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
266 stored in obj, and returned from the function invoking this macro.
267*/
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000268#define CONVERT_TO_DOUBLE(obj, dbl) \
269 if (PyFloat_Check(obj)) \
270 dbl = PyFloat_AS_DOUBLE(obj); \
271 else if (convert_to_double(&(obj), &(dbl)) < 0) \
272 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000273
Eric Smith0923d1d2009-04-16 20:16:10 +0000274/* Methods */
275
Neil Schemenauer32117e52001-01-04 01:44:34 +0000276static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000277convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000279 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000280
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000281 if (PyLong_Check(obj)) {
282 *dbl = PyLong_AsDouble(obj);
283 if (*dbl == -1.0 && PyErr_Occurred()) {
284 *v = NULL;
285 return -1;
286 }
287 }
288 else {
289 Py_INCREF(Py_NotImplemented);
290 *v = Py_NotImplemented;
291 return -1;
292 }
293 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000294}
295
Eric Smith0923d1d2009-04-16 20:16:10 +0000296static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000297float_str_or_repr(PyFloatObject *v, int precision, char format_code)
Eric Smith0923d1d2009-04-16 20:16:10 +0000298{
299 PyObject *result;
300 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Eric Smith63376222009-05-05 14:04:18 +0000301 format_code, precision,
302 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000303 NULL);
304 if (!buf)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000305 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000306 result = PyUnicode_FromString(buf);
307 PyMem_Free(buf);
308 return result;
309}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000312float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Eric Smith63376222009-05-05 14:04:18 +0000314 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000315}
316
317static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000318float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000319{
Eric Smith63376222009-05-05 14:04:18 +0000320 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321}
322
Tim Peters307fa782004-09-23 08:06:40 +0000323/* Comparison is pretty much a nightmare. When comparing float to float,
324 * we do it as straightforwardly (and long-windedly) as conceivable, so
325 * that, e.g., Python x == y delivers the same result as the platform
326 * C x == y when x and/or y is a NaN.
327 * When mixing float with an integer type, there's no good *uniform* approach.
328 * Converting the double to an integer obviously doesn't work, since we
329 * may lose info from fractional bits. Converting the integer to a double
330 * also has two failure modes: (1) a long int may trigger overflow (too
331 * large to fit in the dynamic range of a C double); (2) even a C long may have
332 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
333 * 63 bits of precision, but a C double probably has only 53), and then
334 * we can falsely claim equality when low-order integer bits are lost by
335 * coercion to double. So this part is painful too.
336 */
337
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000338static PyObject*
339float_richcompare(PyObject *v, PyObject *w, int op)
340{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000341 double i, j;
342 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000343
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000344 assert(PyFloat_Check(v));
345 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000346
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000347 /* Switch on the type of w. Set i and j to doubles to be compared,
348 * and op to the richcomp to use.
349 */
350 if (PyFloat_Check(w))
351 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000352
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000353 else if (!Py_IS_FINITE(i)) {
354 if (PyLong_Check(w))
355 /* If i is an infinity, its magnitude exceeds any
356 * finite integer, so it doesn't matter which int we
357 * compare i with. If i is a NaN, similarly.
358 */
359 j = 0.0;
360 else
361 goto Unimplemented;
362 }
Tim Peters307fa782004-09-23 08:06:40 +0000363
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000364 else if (PyLong_Check(w)) {
365 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
366 int wsign = _PyLong_Sign(w);
367 size_t nbits;
368 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000369
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000370 if (vsign != wsign) {
371 /* Magnitudes are irrelevant -- the signs alone
372 * determine the outcome.
373 */
374 i = (double)vsign;
375 j = (double)wsign;
376 goto Compare;
377 }
378 /* The signs are the same. */
379 /* Convert w to a double if it fits. In particular, 0 fits. */
380 nbits = _PyLong_NumBits(w);
381 if (nbits == (size_t)-1 && PyErr_Occurred()) {
382 /* This long is so large that size_t isn't big enough
383 * to hold the # of bits. Replace with little doubles
384 * that give the same outcome -- w is so large that
385 * its magnitude must exceed the magnitude of any
386 * finite float.
387 */
388 PyErr_Clear();
389 i = (double)vsign;
390 assert(wsign != 0);
391 j = wsign * 2.0;
392 goto Compare;
393 }
394 if (nbits <= 48) {
395 j = PyLong_AsDouble(w);
396 /* It's impossible that <= 48 bits overflowed. */
397 assert(j != -1.0 || ! PyErr_Occurred());
398 goto Compare;
399 }
400 assert(wsign != 0); /* else nbits was 0 */
401 assert(vsign != 0); /* if vsign were 0, then since wsign is
402 * not 0, we would have taken the
403 * vsign != wsign branch at the start */
404 /* We want to work with non-negative numbers. */
405 if (vsign < 0) {
406 /* "Multiply both sides" by -1; this also swaps the
407 * comparator.
408 */
409 i = -i;
410 op = _Py_SwappedOp[op];
411 }
412 assert(i > 0.0);
413 (void) frexp(i, &exponent);
414 /* exponent is the # of bits in v before the radix point;
415 * we know that nbits (the # of bits in w) > 48 at this point
416 */
417 if (exponent < 0 || (size_t)exponent < nbits) {
418 i = 1.0;
419 j = 2.0;
420 goto Compare;
421 }
422 if ((size_t)exponent > nbits) {
423 i = 2.0;
424 j = 1.0;
425 goto Compare;
426 }
427 /* v and w have the same number of bits before the radix
428 * point. Construct two longs that have the same comparison
429 * outcome.
430 */
431 {
432 double fracpart;
433 double intpart;
434 PyObject *result = NULL;
435 PyObject *one = NULL;
436 PyObject *vv = NULL;
437 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000438
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000439 if (wsign < 0) {
440 ww = PyNumber_Negative(w);
441 if (ww == NULL)
442 goto Error;
443 }
444 else
445 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000446
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000447 fracpart = modf(i, &intpart);
448 vv = PyLong_FromDouble(intpart);
449 if (vv == NULL)
450 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000451
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000452 if (fracpart != 0.0) {
453 /* Shift left, and or a 1 bit into vv
454 * to represent the lost fraction.
455 */
456 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000458 one = PyLong_FromLong(1);
459 if (one == NULL)
460 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000461
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000462 temp = PyNumber_Lshift(ww, one);
463 if (temp == NULL)
464 goto Error;
465 Py_DECREF(ww);
466 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000467
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000468 temp = PyNumber_Lshift(vv, one);
469 if (temp == NULL)
470 goto Error;
471 Py_DECREF(vv);
472 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000473
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000474 temp = PyNumber_Or(vv, one);
475 if (temp == NULL)
476 goto Error;
477 Py_DECREF(vv);
478 vv = temp;
479 }
Tim Peters307fa782004-09-23 08:06:40 +0000480
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000481 r = PyObject_RichCompareBool(vv, ww, op);
482 if (r < 0)
483 goto Error;
484 result = PyBool_FromLong(r);
485 Error:
486 Py_XDECREF(vv);
487 Py_XDECREF(ww);
488 Py_XDECREF(one);
489 return result;
490 }
491 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000492
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000493 else /* w isn't float, int, or long */
494 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000495
496 Compare:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000497 PyFPE_START_PROTECT("richcompare", return NULL)
498 switch (op) {
499 case Py_EQ:
500 r = i == j;
501 break;
502 case Py_NE:
503 r = i != j;
504 break;
505 case Py_LE:
506 r = i <= j;
507 break;
508 case Py_GE:
509 r = i >= j;
510 break;
511 case Py_LT:
512 r = i < j;
513 break;
514 case Py_GT:
515 r = i > j;
516 break;
517 }
518 PyFPE_END_PROTECT(r)
519 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000520
521 Unimplemented:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000522 Py_INCREF(Py_NotImplemented);
523 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000524}
525
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526static long
Fred Drakefd99de62000-07-09 05:02:18 +0000527float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000528{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000529 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000530}
531
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000533float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000534{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000535 double a,b;
536 CONVERT_TO_DOUBLE(v, a);
537 CONVERT_TO_DOUBLE(w, b);
538 PyFPE_START_PROTECT("add", return 0)
539 a = a + b;
540 PyFPE_END_PROTECT(a)
541 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542}
543
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000545float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000547 double a,b;
548 CONVERT_TO_DOUBLE(v, a);
549 CONVERT_TO_DOUBLE(w, b);
550 PyFPE_START_PROTECT("subtract", return 0)
551 a = a - b;
552 PyFPE_END_PROTECT(a)
553 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554}
555
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000556static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000557float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000559 double a,b;
560 CONVERT_TO_DOUBLE(v, a);
561 CONVERT_TO_DOUBLE(w, b);
562 PyFPE_START_PROTECT("multiply", return 0)
563 a = a * b;
564 PyFPE_END_PROTECT(a)
565 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566}
567
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000568static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000569float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000571 double a,b;
572 CONVERT_TO_DOUBLE(v, a);
573 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000574#ifdef Py_NAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000575 if (b == 0.0) {
576 PyErr_SetString(PyExc_ZeroDivisionError,
577 "float division");
578 return NULL;
579 }
Christian Heimes53876d92008-04-19 00:31:39 +0000580#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000581 PyFPE_START_PROTECT("divide", return 0)
582 a = a / b;
583 PyFPE_END_PROTECT(a)
584 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585}
586
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000587static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000588float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000589{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000590 double vx, wx;
591 double mod;
592 CONVERT_TO_DOUBLE(v, vx);
593 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes53876d92008-04-19 00:31:39 +0000594#ifdef Py_NAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000595 if (wx == 0.0) {
596 PyErr_SetString(PyExc_ZeroDivisionError,
597 "float modulo");
598 return NULL;
599 }
Christian Heimes53876d92008-04-19 00:31:39 +0000600#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000601 PyFPE_START_PROTECT("modulo", return 0)
602 mod = fmod(vx, wx);
Mark Dickinson0169af12010-12-04 13:04:18 +0000603 if (mod) {
604 /* ensure the remainder has the same sign as the denominator */
605 if ((wx < 0) != (mod < 0)) {
606 mod += wx;
607 }
608 }
609 else {
610 /* the remainder is zero, and in the presence of signed zeroes
611 fmod returns different results across platforms; ensure
612 it has the same sign as the denominator; we'd like to do
613 "mod = wx * 0.0", but that may get optimized away */
614 mod *= mod; /* hide "mod = +0" from optimizer */
615 if (wx < 0.0)
616 mod = -mod;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000617 }
618 PyFPE_END_PROTECT(mod)
619 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000620}
621
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000623float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000624{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000625 double vx, wx;
626 double div, mod, floordiv;
627 CONVERT_TO_DOUBLE(v, vx);
628 CONVERT_TO_DOUBLE(w, wx);
629 if (wx == 0.0) {
630 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
631 return NULL;
632 }
633 PyFPE_START_PROTECT("divmod", return 0)
634 mod = fmod(vx, wx);
635 /* fmod is typically exact, so vx-mod is *mathematically* an
636 exact multiple of wx. But this is fp arithmetic, and fp
637 vx - mod is an approximation; the result is that div may
638 not be an exact integral value after the division, although
639 it will always be very close to one.
640 */
641 div = (vx - mod) / wx;
642 if (mod) {
643 /* ensure the remainder has the same sign as the denominator */
644 if ((wx < 0) != (mod < 0)) {
645 mod += wx;
646 div -= 1.0;
647 }
648 }
649 else {
650 /* the remainder is zero, and in the presence of signed zeroes
651 fmod returns different results across platforms; ensure
652 it has the same sign as the denominator; we'd like to do
653 "mod = wx * 0.0", but that may get optimized away */
654 mod *= mod; /* hide "mod = +0" from optimizer */
655 if (wx < 0.0)
656 mod = -mod;
657 }
658 /* snap quotient to nearest integral value */
659 if (div) {
660 floordiv = floor(div);
661 if (div - floordiv > 0.5)
662 floordiv += 1.0;
663 }
664 else {
665 /* div is zero - get the same sign as the true quotient */
666 div *= div; /* hide "div = +0" from optimizers */
667 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
668 }
669 PyFPE_END_PROTECT(floordiv)
670 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000671}
672
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000674float_floor_div(PyObject *v, PyObject *w)
675{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000676 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000677
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000678 t = float_divmod(v, w);
679 if (t == NULL || t == Py_NotImplemented)
680 return t;
681 assert(PyTuple_CheckExact(t));
682 r = PyTuple_GET_ITEM(t, 0);
683 Py_INCREF(r);
684 Py_DECREF(t);
685 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000686}
687
688static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000689float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000690{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000691 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000692
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000693 if ((PyObject *)z != Py_None) {
694 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
695 "allowed unless all arguments are integers");
696 return NULL;
697 }
Tim Peters32f453e2001-09-03 08:35:41 +0000698
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000699 CONVERT_TO_DOUBLE(v, iv);
700 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000701
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000702 /* Sort out special cases here instead of relying on pow() */
703 if (iw == 0) { /* v**0 is 1, even 0**0 */
704 return PyFloat_FromDouble(1.0);
705 }
706 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
707 if (iw < 0.0) {
708 PyErr_SetString(PyExc_ZeroDivisionError,
709 "0.0 cannot be raised to a negative power");
710 return NULL;
711 }
712 return PyFloat_FromDouble(0.0);
713 }
714 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
715 return PyFloat_FromDouble(1.0);
716 }
717 if (iv < 0.0) {
718 /* Whether this is an error is a mess, and bumps into libm
719 * bugs so we have to figure it out ourselves.
720 */
721 if (iw != floor(iw)) {
722 /* Negative numbers raised to fractional powers
723 * become complex.
724 */
725 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
726 }
727 /* iw is an exact integer, albeit perhaps a very large one.
728 * -1 raised to an exact integer should never be exceptional.
729 * Alas, some libms (chiefly glibc as of early 2003) return
730 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
731 * happen to be representable in a *C* integer. That's a
732 * bug; we let that slide in math.pow() (which currently
733 * reflects all platform accidents), but not for Python's **.
734 */
735 if (iv == -1.0 && Py_IS_FINITE(iw)) {
736 /* Return 1 if iw is even, -1 if iw is odd; there's
737 * no guarantee that any C integral type is big
738 * enough to hold iw, so we have to check this
739 * indirectly.
740 */
741 ix = floor(iw * 0.5) * 2.0;
742 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
743 }
744 /* Else iv != -1.0, and overflow or underflow are possible.
745 * Unless we're to write pow() ourselves, we have to trust
746 * the platform to do this correctly.
747 */
748 }
749 errno = 0;
750 PyFPE_START_PROTECT("pow", return NULL)
751 ix = pow(iv, iw);
752 PyFPE_END_PROTECT(ix)
753 Py_ADJUST_ERANGE1(ix);
754 if (errno != 0) {
755 /* We don't expect any errno value other than ERANGE, but
756 * the range of libm bugs appears unbounded.
757 */
758 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
759 PyExc_ValueError);
760 return NULL;
761 }
762 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763}
764
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000766float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000768 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000769}
770
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000772float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000773{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000774 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775}
776
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000777static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000778float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000779{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000780 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000781}
782
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000784float_is_integer(PyObject *v)
785{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000786 double x = PyFloat_AsDouble(v);
787 PyObject *o;
788
789 if (x == -1.0 && PyErr_Occurred())
790 return NULL;
791 if (!Py_IS_FINITE(x))
792 Py_RETURN_FALSE;
793 errno = 0;
794 PyFPE_START_PROTECT("is_integer", return NULL)
795 o = (floor(x) == x) ? Py_True : Py_False;
796 PyFPE_END_PROTECT(x)
797 if (errno != 0) {
798 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
799 PyExc_ValueError);
800 return NULL;
801 }
802 Py_INCREF(o);
803 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000804}
805
806#if 0
807static PyObject *
808float_is_inf(PyObject *v)
809{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000810 double x = PyFloat_AsDouble(v);
811 if (x == -1.0 && PyErr_Occurred())
812 return NULL;
813 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000814}
815
816static PyObject *
817float_is_nan(PyObject *v)
818{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000819 double x = PyFloat_AsDouble(v);
820 if (x == -1.0 && PyErr_Occurred())
821 return NULL;
822 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000823}
824
825static PyObject *
826float_is_finite(PyObject *v)
827{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000828 double x = PyFloat_AsDouble(v);
829 if (x == -1.0 && PyErr_Occurred())
830 return NULL;
831 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000832}
833#endif
834
835static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000836float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000837{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000838 double x = PyFloat_AsDouble(v);
839 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000840
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000841 (void)modf(x, &wholepart);
842 /* Try to get out cheap if this fits in a Python int. The attempt
843 * to cast to long must be protected, as C doesn't define what
844 * happens if the double is too big to fit in a long. Some rare
845 * systems raise an exception then (RISCOS was mentioned as one,
846 * and someone using a non-default option on Sun also bumped into
847 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
848 * still be vulnerable: if a long has more bits of precision than
849 * a double, casting MIN/MAX to double may yield an approximation,
850 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
851 * yield true from the C expression wholepart<=LONG_MAX, despite
852 * that wholepart is actually greater than LONG_MAX.
853 */
854 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
855 const long aslong = (long)wholepart;
856 return PyLong_FromLong(aslong);
857 }
858 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000859}
860
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000861/* double_round: rounds a finite double to the closest multiple of
862 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
863 ndigits <= 323). Returns a Python float, or sets a Python error and
864 returns NULL on failure (OverflowError and memory errors are possible). */
865
866#ifndef PY_NO_SHORT_FLOAT_REPR
867/* version of double_round that uses the correctly-rounded string<->double
868 conversions from Python/dtoa.c */
869
870static PyObject *
871double_round(double x, int ndigits) {
872
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000873 double rounded;
874 Py_ssize_t buflen, mybuflen=100;
875 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
876 int decpt, sign;
877 PyObject *result = NULL;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000878
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000879 /* round to a decimal string */
880 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
881 if (buf == NULL) {
882 PyErr_NoMemory();
883 return NULL;
884 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000885
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000886 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
887 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
888 buflen = buf_end - buf;
889 if (buflen + 8 > mybuflen) {
890 mybuflen = buflen+8;
891 mybuf = (char *)PyMem_Malloc(mybuflen);
892 if (mybuf == NULL) {
893 PyErr_NoMemory();
894 goto exit;
895 }
896 }
897 /* copy buf to mybuf, adding exponent, sign and leading 0 */
898 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
899 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000900
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000901 /* and convert the resulting string back to a double */
902 errno = 0;
903 rounded = _Py_dg_strtod(mybuf, NULL);
904 if (errno == ERANGE && fabs(rounded) >= 1.)
905 PyErr_SetString(PyExc_OverflowError,
906 "rounded value too large to represent");
907 else
908 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000909
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000910 /* done computing value; now clean up */
911 if (mybuf != shortbuf)
912 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000913 exit:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000914 _Py_dg_freedtoa(buf);
915 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000916}
917
918#else /* PY_NO_SHORT_FLOAT_REPR */
919
920/* fallback version, to be used when correctly rounded binary<->decimal
921 conversions aren't available */
922
923static PyObject *
924double_round(double x, int ndigits) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000925 double pow1, pow2, y, z;
926 if (ndigits >= 0) {
927 if (ndigits > 22) {
928 /* pow1 and pow2 are each safe from overflow, but
929 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
930 pow1 = pow(10.0, (double)(ndigits-22));
931 pow2 = 1e22;
932 }
933 else {
934 pow1 = pow(10.0, (double)ndigits);
935 pow2 = 1.0;
936 }
937 y = (x*pow1)*pow2;
938 /* if y overflows, then rounded value is exactly x */
939 if (!Py_IS_FINITE(y))
940 return PyFloat_FromDouble(x);
941 }
942 else {
943 pow1 = pow(10.0, (double)-ndigits);
944 pow2 = 1.0; /* unused; silences a gcc compiler warning */
945 y = x / pow1;
946 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000947
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000948 z = round(y);
949 if (fabs(y-z) == 0.5)
950 /* halfway between two integers; use round-half-even */
951 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000952
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000953 if (ndigits >= 0)
954 z = (z / pow2) / pow1;
955 else
956 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000957
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000958 /* if computation resulted in overflow, raise OverflowError */
959 if (!Py_IS_FINITE(z)) {
960 PyErr_SetString(PyExc_OverflowError,
961 "overflow occurred during round");
962 return NULL;
963 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000964
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000965 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000966}
967
968#endif /* PY_NO_SHORT_FLOAT_REPR */
969
970/* round a Python float v to the closest multiple of 10**-ndigits */
971
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000972static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000973float_round(PyObject *v, PyObject *args)
974{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000975 double x, rounded;
976 PyObject *o_ndigits = NULL;
977 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000978
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000979 x = PyFloat_AsDouble(v);
980 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
981 return NULL;
982 if (o_ndigits == NULL) {
983 /* single-argument round: round to nearest integer */
984 rounded = round(x);
985 if (fabs(x-rounded) == 0.5)
986 /* halfway case: round to even */
987 rounded = 2.0*round(x/2.0);
988 return PyLong_FromDouble(rounded);
989 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000991 /* interpret second argument as a Py_ssize_t; clips on overflow */
992 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
993 if (ndigits == -1 && PyErr_Occurred())
994 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000995
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000996 /* nans and infinities round to themselves */
997 if (!Py_IS_FINITE(x))
998 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001000 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1001 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1002 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1004#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001005 if (ndigits > NDIGITS_MAX)
1006 /* return x */
1007 return PyFloat_FromDouble(x);
1008 else if (ndigits < NDIGITS_MIN)
1009 /* return 0.0, but with sign of x */
1010 return PyFloat_FromDouble(0.0*x);
1011 else
1012 /* finite x, and ndigits is not unreasonably large */
1013 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001014#undef NDIGITS_MAX
1015#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001016}
1017
1018static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001019float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001020{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001021 if (PyFloat_CheckExact(v))
1022 Py_INCREF(v);
1023 else
1024 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1025 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001026}
1027
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001028/* turn ASCII hex characters into integer values and vice versa */
1029
1030static char
1031char_from_hex(int x)
1032{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001033 assert(0 <= x && x < 16);
1034 return "0123456789abcdef"[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001035}
1036
1037static int
1038hex_from_char(char c) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001039 int x;
1040 switch(c) {
1041 case '0':
1042 x = 0;
1043 break;
1044 case '1':
1045 x = 1;
1046 break;
1047 case '2':
1048 x = 2;
1049 break;
1050 case '3':
1051 x = 3;
1052 break;
1053 case '4':
1054 x = 4;
1055 break;
1056 case '5':
1057 x = 5;
1058 break;
1059 case '6':
1060 x = 6;
1061 break;
1062 case '7':
1063 x = 7;
1064 break;
1065 case '8':
1066 x = 8;
1067 break;
1068 case '9':
1069 x = 9;
1070 break;
1071 case 'a':
1072 case 'A':
1073 x = 10;
1074 break;
1075 case 'b':
1076 case 'B':
1077 x = 11;
1078 break;
1079 case 'c':
1080 case 'C':
1081 x = 12;
1082 break;
1083 case 'd':
1084 case 'D':
1085 x = 13;
1086 break;
1087 case 'e':
1088 case 'E':
1089 x = 14;
1090 break;
1091 case 'f':
1092 case 'F':
1093 x = 15;
1094 break;
1095 default:
1096 x = -1;
1097 break;
1098 }
1099 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001100}
1101
1102/* convert a float to a hexadecimal string */
1103
1104/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1105 of the form 4k+1. */
1106#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1107
1108static PyObject *
1109float_hex(PyObject *v)
1110{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001111 double x, m;
1112 int e, shift, i, si, esign;
1113 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1114 trailing NUL byte. */
1115 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001116
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001117 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001118
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001119 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1120 return float_str((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001121
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001122 if (x == 0.0) {
Benjamin Peterson1ed66702010-07-02 19:50:16 +00001123 if (copysign(1.0, x) == -1.0)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001124 return PyUnicode_FromString("-0x0.0p+0");
1125 else
1126 return PyUnicode_FromString("0x0.0p+0");
1127 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001128
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001129 m = frexp(fabs(x), &e);
1130 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1131 m = ldexp(m, shift);
1132 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001133
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001134 si = 0;
1135 s[si] = char_from_hex((int)m);
1136 si++;
1137 m -= (int)m;
1138 s[si] = '.';
1139 si++;
1140 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1141 m *= 16.0;
1142 s[si] = char_from_hex((int)m);
1143 si++;
1144 m -= (int)m;
1145 }
1146 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001147
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001148 if (e < 0) {
1149 esign = (int)'-';
1150 e = -e;
1151 }
1152 else
1153 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001154
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001155 if (x < 0.0)
1156 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1157 else
1158 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001159}
1160
1161PyDoc_STRVAR(float_hex_doc,
1162"float.hex() -> string\n\
1163\n\
1164Return a hexadecimal representation of a floating-point number.\n\
1165>>> (-0.1).hex()\n\
1166'-0x1.999999999999ap-4'\n\
1167>>> 3.14159.hex()\n\
1168'0x1.921f9f01b866ep+1'");
1169
1170/* Convert a hexadecimal string to a float. */
1171
1172static PyObject *
1173float_fromhex(PyObject *cls, PyObject *arg)
1174{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001175 PyObject *result_as_float, *result;
1176 double x;
1177 long exp, top_exp, lsb, key_digit;
1178 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1179 int half_eps, digit, round_up, negate=0;
1180 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001181
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001182 /*
1183 * For the sake of simplicity and correctness, we impose an artificial
1184 * limit on ndigits, the total number of hex digits in the coefficient
1185 * The limit is chosen to ensure that, writing exp for the exponent,
1186 *
1187 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1188 * guaranteed to overflow (provided it's nonzero)
1189 *
1190 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1191 * guaranteed to underflow to 0.
1192 *
1193 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1194 * overflow in the calculation of exp and top_exp below.
1195 *
1196 * More specifically, ndigits is assumed to satisfy the following
1197 * inequalities:
1198 *
1199 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1200 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1201 *
1202 * If either of these inequalities is not satisfied, a ValueError is
1203 * raised. Otherwise, write x for the value of the hex string, and
1204 * assume x is nonzero. Then
1205 *
1206 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1207 *
1208 * Now if exp > LONG_MAX/2 then:
1209 *
1210 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1211 * = DBL_MAX_EXP
1212 *
1213 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1214 * double, so overflows. If exp < LONG_MIN/2, then
1215 *
1216 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1217 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1218 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1219 *
1220 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1221 * when converted to a C double.
1222 *
1223 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1224 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1225 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001226
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001227 s = _PyUnicode_AsStringAndSize(arg, &length);
1228 if (s == NULL)
1229 return NULL;
1230 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001232 /********************
1233 * Parse the string *
1234 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001235
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001236 /* leading whitespace */
1237 while (Py_ISSPACE(*s))
1238 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001239
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001240 /* infinities and nans */
1241 x = _Py_parse_inf_or_nan(s, &coeff_end);
1242 if (coeff_end != s) {
1243 s = coeff_end;
1244 goto finished;
1245 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001246
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001247 /* optional sign */
1248 if (*s == '-') {
1249 s++;
1250 negate = 1;
1251 }
1252 else if (*s == '+')
1253 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001255 /* [0x] */
1256 s_store = s;
1257 if (*s == '0') {
1258 s++;
1259 if (*s == 'x' || *s == 'X')
1260 s++;
1261 else
1262 s = s_store;
1263 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001265 /* coefficient: <integer> [. <fraction>] */
1266 coeff_start = s;
1267 while (hex_from_char(*s) >= 0)
1268 s++;
1269 s_store = s;
1270 if (*s == '.') {
1271 s++;
1272 while (hex_from_char(*s) >= 0)
1273 s++;
1274 coeff_end = s-1;
1275 }
1276 else
1277 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001278
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001279 /* ndigits = total # of hex digits; fdigits = # after point */
1280 ndigits = coeff_end - coeff_start;
1281 fdigits = coeff_end - s_store;
1282 if (ndigits == 0)
1283 goto parse_error;
1284 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1285 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1286 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001287
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001288 /* [p <exponent>] */
1289 if (*s == 'p' || *s == 'P') {
1290 s++;
1291 exp_start = s;
1292 if (*s == '-' || *s == '+')
1293 s++;
1294 if (!('0' <= *s && *s <= '9'))
1295 goto parse_error;
1296 s++;
1297 while ('0' <= *s && *s <= '9')
1298 s++;
1299 exp = strtol(exp_start, NULL, 10);
1300 }
1301 else
1302 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001305#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1306 coeff_end-(j) : \
1307 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001309 /*******************************************
1310 * Compute rounded value of the hex string *
1311 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001312
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001313 /* Discard leading zeros, and catch extreme overflow and underflow */
1314 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1315 ndigits--;
1316 if (ndigits == 0 || exp < LONG_MIN/2) {
1317 x = 0.0;
1318 goto finished;
1319 }
1320 if (exp > LONG_MAX/2)
1321 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001322
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001323 /* Adjust exponent for fractional part. */
1324 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001325
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001326 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1327 top_exp = exp + 4*((long)ndigits - 1);
1328 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1329 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001330
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001331 /* catch almost all nonextreme cases of overflow and underflow here */
1332 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1333 x = 0.0;
1334 goto finished;
1335 }
1336 if (top_exp > DBL_MAX_EXP)
1337 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001338
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001339 /* lsb = exponent of least significant bit of the *rounded* value.
1340 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1341 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001342
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001343 x = 0.0;
1344 if (exp >= lsb) {
1345 /* no rounding required */
1346 for (i = ndigits-1; i >= 0; i--)
1347 x = 16.0*x + HEX_DIGIT(i);
1348 x = ldexp(x, (int)(exp));
1349 goto finished;
1350 }
1351 /* rounding required. key_digit is the index of the hex digit
1352 containing the first bit to be rounded away. */
1353 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1354 key_digit = (lsb - exp - 1) / 4;
1355 for (i = ndigits-1; i > key_digit; i--)
1356 x = 16.0*x + HEX_DIGIT(i);
1357 digit = HEX_DIGIT(key_digit);
1358 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001359
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001360 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1361 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1362 if ((digit & half_eps) != 0) {
1363 round_up = 0;
1364 if ((digit & (3*half_eps-1)) != 0 ||
1365 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1366 round_up = 1;
1367 else
1368 for (i = key_digit-1; i >= 0; i--)
1369 if (HEX_DIGIT(i) != 0) {
1370 round_up = 1;
1371 break;
1372 }
1373 if (round_up == 1) {
1374 x += 2*half_eps;
1375 if (top_exp == DBL_MAX_EXP &&
1376 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1377 /* overflow corner case: pre-rounded value <
1378 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1379 goto overflow_error;
1380 }
1381 }
1382 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001383
1384 finished:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001385 /* optional trailing whitespace leading to the end of the string */
1386 while (Py_ISSPACE(*s))
1387 s++;
1388 if (s != s_end)
1389 goto parse_error;
1390 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1391 if (result_as_float == NULL)
1392 return NULL;
1393 result = PyObject_CallObject(cls, result_as_float);
1394 Py_DECREF(result_as_float);
1395 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
1397 overflow_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001398 PyErr_SetString(PyExc_OverflowError,
1399 "hexadecimal value too large to represent as a float");
1400 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001401
1402 parse_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001403 PyErr_SetString(PyExc_ValueError,
1404 "invalid hexadecimal floating-point string");
1405 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001406
1407 insane_length_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001408 PyErr_SetString(PyExc_ValueError,
1409 "hexadecimal string too long to convert");
1410 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001411}
1412
1413PyDoc_STRVAR(float_fromhex_doc,
1414"float.fromhex(string) -> float\n\
1415\n\
1416Create a floating-point number from a hexadecimal string.\n\
1417>>> float.fromhex('0x1.ffffp10')\n\
14182047.984375\n\
1419>>> float.fromhex('-0x1p-1074')\n\
1420-4.9406564584124654e-324");
1421
1422
Christian Heimes26855632008-01-27 23:50:43 +00001423static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001424float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001425{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001426 double self;
1427 double float_part;
1428 int exponent;
1429 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001430
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001431 PyObject *prev;
1432 PyObject *py_exponent = NULL;
1433 PyObject *numerator = NULL;
1434 PyObject *denominator = NULL;
1435 PyObject *result_pair = NULL;
1436 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001437
1438#define INPLACE_UPDATE(obj, call) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001439 prev = obj; \
1440 obj = call; \
1441 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001442
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001443 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001444
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001445 if (Py_IS_INFINITY(self)) {
1446 PyErr_SetString(PyExc_OverflowError,
1447 "Cannot pass infinity to float.as_integer_ratio.");
1448 return NULL;
1449 }
Christian Heimes26855632008-01-27 23:50:43 +00001450#ifdef Py_NAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001451 if (Py_IS_NAN(self)) {
1452 PyErr_SetString(PyExc_ValueError,
1453 "Cannot pass NaN to float.as_integer_ratio.");
1454 return NULL;
1455 }
Christian Heimes26855632008-01-27 23:50:43 +00001456#endif
1457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001458 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1459 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1460 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001461
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001462 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1463 float_part *= 2.0;
1464 exponent--;
1465 }
1466 /* self == float_part * 2**exponent exactly and float_part is integral.
1467 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1468 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001469
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001470 numerator = PyLong_FromDouble(float_part);
1471 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001472
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001473 /* fold in 2**exponent */
1474 denominator = PyLong_FromLong(1);
1475 py_exponent = PyLong_FromLong(labs((long)exponent));
1476 if (py_exponent == NULL) goto error;
1477 INPLACE_UPDATE(py_exponent,
1478 long_methods->nb_lshift(denominator, py_exponent));
1479 if (py_exponent == NULL) goto error;
1480 if (exponent > 0) {
1481 INPLACE_UPDATE(numerator,
1482 long_methods->nb_multiply(numerator, py_exponent));
1483 if (numerator == NULL) goto error;
1484 }
1485 else {
1486 Py_DECREF(denominator);
1487 denominator = py_exponent;
1488 py_exponent = NULL;
1489 }
1490
1491 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001492
1493#undef INPLACE_UPDATE
1494error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001495 Py_XDECREF(py_exponent);
1496 Py_XDECREF(denominator);
1497 Py_XDECREF(numerator);
1498 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001499}
1500
1501PyDoc_STRVAR(float_as_integer_ratio_doc,
1502"float.as_integer_ratio() -> (int, int)\n"
1503"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001504"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1505"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001506"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001507"\n"
1508">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001509"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001510">>> (0.0).as_integer_ratio()\n"
1511"(0, 1)\n"
1512">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001513"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001514
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001515
Jeremy Hylton938ace62002-07-17 16:30:39 +00001516static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001517float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1518
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519static PyObject *
1520float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1521{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001522 PyObject *x = Py_False; /* Integer zero */
1523 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001525 if (type != &PyFloat_Type)
1526 return float_subtype_new(type, args, kwds); /* Wimp out */
1527 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1528 return NULL;
1529 /* If it's a string, but not a string subclass, use
1530 PyFloat_FromString. */
1531 if (PyUnicode_CheckExact(x))
1532 return PyFloat_FromString(x);
1533 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534}
1535
Guido van Rossumbef14172001-08-29 15:47:46 +00001536/* Wimpy, slow approach to tp_new calls for subtypes of float:
1537 first create a regular float from whatever arguments we got,
1538 then allocate a subtype instance and initialize its ob_fval
1539 from the regular float. The regular float is then thrown away.
1540*/
1541static PyObject *
1542float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1543{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001544 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001545
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001546 assert(PyType_IsSubtype(type, &PyFloat_Type));
1547 tmp = float_new(&PyFloat_Type, args, kwds);
1548 if (tmp == NULL)
1549 return NULL;
1550 assert(PyFloat_CheckExact(tmp));
1551 newobj = type->tp_alloc(type, 0);
1552 if (newobj == NULL) {
1553 Py_DECREF(tmp);
1554 return NULL;
1555 }
1556 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1557 Py_DECREF(tmp);
1558 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001559}
1560
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001561static PyObject *
1562float_getnewargs(PyFloatObject *v)
1563{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001564 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001565}
1566
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001567/* this is for the benefit of the pack/unpack routines below */
1568
1569typedef enum {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001570 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001571} float_format_type;
1572
1573static float_format_type double_format, float_format;
1574static float_format_type detected_double_format, detected_float_format;
1575
1576static PyObject *
1577float_getformat(PyTypeObject *v, PyObject* arg)
1578{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001579 char* s;
1580 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001582 if (!PyUnicode_Check(arg)) {
1583 PyErr_Format(PyExc_TypeError,
1584 "__getformat__() argument must be string, not %.500s",
1585 Py_TYPE(arg)->tp_name);
1586 return NULL;
1587 }
1588 s = _PyUnicode_AsString(arg);
1589 if (s == NULL)
1590 return NULL;
1591 if (strcmp(s, "double") == 0) {
1592 r = double_format;
1593 }
1594 else if (strcmp(s, "float") == 0) {
1595 r = float_format;
1596 }
1597 else {
1598 PyErr_SetString(PyExc_ValueError,
1599 "__getformat__() argument 1 must be "
1600 "'double' or 'float'");
1601 return NULL;
1602 }
1603
1604 switch (r) {
1605 case unknown_format:
1606 return PyUnicode_FromString("unknown");
1607 case ieee_little_endian_format:
1608 return PyUnicode_FromString("IEEE, little-endian");
1609 case ieee_big_endian_format:
1610 return PyUnicode_FromString("IEEE, big-endian");
1611 default:
1612 Py_FatalError("insane float_format or double_format");
1613 return NULL;
1614 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615}
1616
1617PyDoc_STRVAR(float_getformat_doc,
1618"float.__getformat__(typestr) -> string\n"
1619"\n"
1620"You probably don't want to use this function. It exists mainly to be\n"
1621"used in Python's test suite.\n"
1622"\n"
1623"typestr must be 'double' or 'float'. This function returns whichever of\n"
1624"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1625"format of floating point numbers used by the C type named by typestr.");
1626
1627static PyObject *
1628float_setformat(PyTypeObject *v, PyObject* args)
1629{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001630 char* typestr;
1631 char* format;
1632 float_format_type f;
1633 float_format_type detected;
1634 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001635
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001636 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1637 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001638
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001639 if (strcmp(typestr, "double") == 0) {
1640 p = &double_format;
1641 detected = detected_double_format;
1642 }
1643 else if (strcmp(typestr, "float") == 0) {
1644 p = &float_format;
1645 detected = detected_float_format;
1646 }
1647 else {
1648 PyErr_SetString(PyExc_ValueError,
1649 "__setformat__() argument 1 must "
1650 "be 'double' or 'float'");
1651 return NULL;
1652 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001653
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001654 if (strcmp(format, "unknown") == 0) {
1655 f = unknown_format;
1656 }
1657 else if (strcmp(format, "IEEE, little-endian") == 0) {
1658 f = ieee_little_endian_format;
1659 }
1660 else if (strcmp(format, "IEEE, big-endian") == 0) {
1661 f = ieee_big_endian_format;
1662 }
1663 else {
1664 PyErr_SetString(PyExc_ValueError,
1665 "__setformat__() argument 2 must be "
1666 "'unknown', 'IEEE, little-endian' or "
1667 "'IEEE, big-endian'");
1668 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001669
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001670 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001672 if (f != unknown_format && f != detected) {
1673 PyErr_Format(PyExc_ValueError,
1674 "can only set %s format to 'unknown' or the "
1675 "detected platform value", typestr);
1676 return NULL;
1677 }
1678
1679 *p = f;
1680 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001681}
1682
1683PyDoc_STRVAR(float_setformat_doc,
1684"float.__setformat__(typestr, fmt) -> None\n"
1685"\n"
1686"You probably don't want to use this function. It exists mainly to be\n"
1687"used in Python's test suite.\n"
1688"\n"
1689"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1690"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1691"one of the latter two if it appears to match the underlying C reality.\n"
1692"\n"
1693"Overrides the automatic determination of C-level floating point type.\n"
1694"This affects how floats are converted to and from binary strings.");
1695
Guido van Rossumb43daf72007-08-01 18:08:08 +00001696static PyObject *
1697float_getzero(PyObject *v, void *closure)
1698{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001699 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001700}
1701
Eric Smith8c663262007-08-25 02:26:07 +00001702static PyObject *
1703float__format__(PyObject *self, PyObject *args)
1704{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001705 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001706
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001707 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1708 return NULL;
1709 return _PyFloat_FormatAdvanced(self,
1710 PyUnicode_AS_UNICODE(format_spec),
1711 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001712}
1713
1714PyDoc_STRVAR(float__format__doc,
1715"float.__format__(format_spec) -> string\n"
1716"\n"
1717"Formats the float according to format_spec.");
1718
1719
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001720static PyMethodDef float_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001721 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1722 "Returns self, the complex conjugate of any float."},
1723 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1724 "Returns the Integral closest to x between 0 and x."},
1725 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1726 "Returns the Integral closest to x, rounding half toward even.\n"
1727 "When an argument is passed, works like built-in round(x, ndigits)."},
1728 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1729 float_as_integer_ratio_doc},
1730 {"fromhex", (PyCFunction)float_fromhex,
1731 METH_O|METH_CLASS, float_fromhex_doc},
1732 {"hex", (PyCFunction)float_hex,
1733 METH_NOARGS, float_hex_doc},
1734 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1735 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001736#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001737 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1738 "Returns True if the float is positive or negative infinite."},
1739 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1740 "Returns True if the float is finite, neither infinite nor NaN."},
1741 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1742 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001743#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001744 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1745 {"__getformat__", (PyCFunction)float_getformat,
1746 METH_O|METH_CLASS, float_getformat_doc},
1747 {"__setformat__", (PyCFunction)float_setformat,
1748 METH_VARARGS|METH_CLASS, float_setformat_doc},
1749 {"__format__", (PyCFunction)float__format__,
1750 METH_VARARGS, float__format__doc},
1751 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001752};
1753
Guido van Rossumb43daf72007-08-01 18:08:08 +00001754static PyGetSetDef float_getset[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001755 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001756 (getter)float_float, (setter)NULL,
1757 "the real part of a complex number",
1758 NULL},
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001759 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001760 (getter)float_getzero, (setter)NULL,
1761 "the imaginary part of a complex number",
1762 NULL},
1763 {NULL} /* Sentinel */
1764};
1765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001766PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767"float(x) -> floating point number\n\
1768\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001769Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770
1771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772static PyNumberMethods float_as_number = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001773 float_add, /*nb_add*/
1774 float_sub, /*nb_subtract*/
1775 float_mul, /*nb_multiply*/
1776 float_rem, /*nb_remainder*/
1777 float_divmod, /*nb_divmod*/
1778 float_pow, /*nb_power*/
1779 (unaryfunc)float_neg, /*nb_negative*/
1780 (unaryfunc)float_float, /*nb_positive*/
1781 (unaryfunc)float_abs, /*nb_absolute*/
1782 (inquiry)float_bool, /*nb_bool*/
1783 0, /*nb_invert*/
1784 0, /*nb_lshift*/
1785 0, /*nb_rshift*/
1786 0, /*nb_and*/
1787 0, /*nb_xor*/
1788 0, /*nb_or*/
1789 float_trunc, /*nb_int*/
1790 0, /*nb_reserved*/
1791 float_float, /*nb_float*/
1792 0, /* nb_inplace_add */
1793 0, /* nb_inplace_subtract */
1794 0, /* nb_inplace_multiply */
1795 0, /* nb_inplace_remainder */
1796 0, /* nb_inplace_power */
1797 0, /* nb_inplace_lshift */
1798 0, /* nb_inplace_rshift */
1799 0, /* nb_inplace_and */
1800 0, /* nb_inplace_xor */
1801 0, /* nb_inplace_or */
1802 float_floor_div, /* nb_floor_divide */
1803 float_div, /* nb_true_divide */
1804 0, /* nb_inplace_floor_divide */
1805 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001806};
1807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001808PyTypeObject PyFloat_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001809 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1810 "float",
1811 sizeof(PyFloatObject),
1812 0,
1813 (destructor)float_dealloc, /* tp_dealloc */
1814 0, /* tp_print */
1815 0, /* tp_getattr */
1816 0, /* tp_setattr */
1817 0, /* tp_reserved */
1818 (reprfunc)float_repr, /* tp_repr */
1819 &float_as_number, /* tp_as_number */
1820 0, /* tp_as_sequence */
1821 0, /* tp_as_mapping */
1822 (hashfunc)float_hash, /* tp_hash */
1823 0, /* tp_call */
1824 (reprfunc)float_str, /* tp_str */
1825 PyObject_GenericGetAttr, /* tp_getattro */
1826 0, /* tp_setattro */
1827 0, /* tp_as_buffer */
1828 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1829 float_doc, /* tp_doc */
1830 0, /* tp_traverse */
1831 0, /* tp_clear */
1832 float_richcompare, /* tp_richcompare */
1833 0, /* tp_weaklistoffset */
1834 0, /* tp_iter */
1835 0, /* tp_iternext */
1836 float_methods, /* tp_methods */
1837 0, /* tp_members */
1838 float_getset, /* tp_getset */
1839 0, /* tp_base */
1840 0, /* tp_dict */
1841 0, /* tp_descr_get */
1842 0, /* tp_descr_set */
1843 0, /* tp_dictoffset */
1844 0, /* tp_init */
1845 0, /* tp_alloc */
1846 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001848
1849void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001850_PyFloat_Init(void)
1851{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001852 /* We attempt to determine if this machine is using IEEE
1853 floating point formats by peering at the bits of some
1854 carefully chosen values. If it looks like we are on an
1855 IEEE platform, the float packing/unpacking routines can
1856 just copy bits, if not they resort to arithmetic & shifts
1857 and masks. The shifts & masks approach works on all finite
1858 values, but what happens to infinities, NaNs and signed
1859 zeroes on packing is an accident, and attempting to unpack
1860 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001861
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001862 Note that if we're on some whacked-out platform which uses
1863 IEEE formats but isn't strictly little-endian or big-
1864 endian, we will fall back to the portable shifts & masks
1865 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001866
1867#if SIZEOF_DOUBLE == 8
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001868 {
1869 double x = 9006104071832581.0;
1870 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1871 detected_double_format = ieee_big_endian_format;
1872 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1873 detected_double_format = ieee_little_endian_format;
1874 else
1875 detected_double_format = unknown_format;
1876 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001877#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001878 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001879#endif
1880
1881#if SIZEOF_FLOAT == 4
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001882 {
1883 float y = 16711938.0;
1884 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1885 detected_float_format = ieee_big_endian_format;
1886 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1887 detected_float_format = ieee_little_endian_format;
1888 else
1889 detected_float_format = unknown_format;
1890 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001891#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001892 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001893#endif
1894
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001895 double_format = detected_double_format;
1896 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001897
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001898 /* Init float info */
1899 if (FloatInfoType.tp_name == 0)
1900 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901}
1902
Georg Brandl2ee470f2008-07-16 12:55:28 +00001903int
1904PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001905{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001906 PyFloatObject *p;
1907 PyFloatBlock *list, *next;
1908 int i;
1909 int u; /* remaining unfreed floats per block */
1910 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001911
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001912 list = block_list;
1913 block_list = NULL;
1914 free_list = NULL;
1915 while (list != NULL) {
1916 u = 0;
1917 for (i = 0, p = &list->objects[0];
1918 i < N_FLOATOBJECTS;
1919 i++, p++) {
1920 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
1921 u++;
1922 }
1923 next = list->next;
1924 if (u) {
1925 list->next = block_list;
1926 block_list = list;
1927 for (i = 0, p = &list->objects[0];
1928 i < N_FLOATOBJECTS;
1929 i++, p++) {
1930 if (!PyFloat_CheckExact(p) ||
1931 Py_REFCNT(p) == 0) {
1932 Py_TYPE(p) = (struct _typeobject *)
1933 free_list;
1934 free_list = p;
1935 }
1936 }
1937 }
1938 else {
1939 PyMem_FREE(list);
1940 }
1941 freelist_size += u;
1942 list = next;
1943 }
1944 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001945}
1946
1947void
1948PyFloat_Fini(void)
1949{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001950 PyFloatObject *p;
1951 PyFloatBlock *list;
1952 int i;
1953 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001954
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001955 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001956
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001957 if (!Py_VerboseFlag)
1958 return;
1959 fprintf(stderr, "# cleanup floats");
1960 if (!u) {
1961 fprintf(stderr, "\n");
1962 }
1963 else {
1964 fprintf(stderr,
1965 ": %d unfreed float%s\n",
1966 u, u == 1 ? "" : "s");
1967 }
1968 if (Py_VerboseFlag > 1) {
1969 list = block_list;
1970 while (list != NULL) {
1971 for (i = 0, p = &list->objects[0];
1972 i < N_FLOATOBJECTS;
1973 i++, p++) {
1974 if (PyFloat_CheckExact(p) &&
1975 Py_REFCNT(p) != 0) {
1976 char *buf = PyOS_double_to_string(
1977 PyFloat_AS_DOUBLE(p), 'r',
1978 0, 0, NULL);
1979 if (buf) {
1980 /* XXX(twouters) cast
1981 refcount to long
1982 until %zd is
1983 universally
1984 available
1985 */
1986 fprintf(stderr,
1987 "# <float at %p, refcnt=%ld, val=%s>\n",
1988 p, (long)Py_REFCNT(p), buf);
1989 PyMem_Free(buf);
1990 }
1991 }
1992 }
1993 list = list->next;
1994 }
1995 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001996}
Tim Peters9905b942003-03-20 20:53:32 +00001997
1998/*----------------------------------------------------------------------------
1999 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002000 */
2001int
2002_PyFloat_Pack4(double x, unsigned char *p, int le)
2003{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002004 if (float_format == unknown_format) {
2005 unsigned char sign;
2006 int e;
2007 double f;
2008 unsigned int fbits;
2009 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002010
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002011 if (le) {
2012 p += 3;
2013 incr = -1;
2014 }
Tim Peters9905b942003-03-20 20:53:32 +00002015
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002016 if (x < 0) {
2017 sign = 1;
2018 x = -x;
2019 }
2020 else
2021 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002022
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002023 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002024
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002025 /* Normalize f to be in the range [1.0, 2.0) */
2026 if (0.5 <= f && f < 1.0) {
2027 f *= 2.0;
2028 e--;
2029 }
2030 else if (f == 0.0)
2031 e = 0;
2032 else {
2033 PyErr_SetString(PyExc_SystemError,
2034 "frexp() result out of range");
2035 return -1;
2036 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002037
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002038 if (e >= 128)
2039 goto Overflow;
2040 else if (e < -126) {
2041 /* Gradual underflow */
2042 f = ldexp(f, 126 + e);
2043 e = 0;
2044 }
2045 else if (!(e == 0 && f == 0.0)) {
2046 e += 127;
2047 f -= 1.0; /* Get rid of leading 1 */
2048 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002049
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002050 f *= 8388608.0; /* 2**23 */
2051 fbits = (unsigned int)(f + 0.5); /* Round */
2052 assert(fbits <= 8388608);
2053 if (fbits >> 23) {
2054 /* The carry propagated out of a string of 23 1 bits. */
2055 fbits = 0;
2056 ++e;
2057 if (e >= 255)
2058 goto Overflow;
2059 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002061 /* First byte */
2062 *p = (sign << 7) | (e >> 1);
2063 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002064
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002065 /* Second byte */
2066 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2067 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002068
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002069 /* Third byte */
2070 *p = (fbits >> 8) & 0xFF;
2071 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002072
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002073 /* Fourth byte */
2074 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002075
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002076 /* Done */
2077 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002078
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002079 }
2080 else {
2081 float y = (float)x;
2082 const char *s = (char*)&y;
2083 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002084
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002085 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2086 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002087
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002088 if ((float_format == ieee_little_endian_format && !le)
2089 || (float_format == ieee_big_endian_format && le)) {
2090 p += 3;
2091 incr = -1;
2092 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002093
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002094 for (i = 0; i < 4; i++) {
2095 *p = *s++;
2096 p += incr;
2097 }
2098 return 0;
2099 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002100 Overflow:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002101 PyErr_SetString(PyExc_OverflowError,
2102 "float too large to pack with f format");
2103 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002104}
2105
2106int
2107_PyFloat_Pack8(double x, unsigned char *p, int le)
2108{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002109 if (double_format == unknown_format) {
2110 unsigned char sign;
2111 int e;
2112 double f;
2113 unsigned int fhi, flo;
2114 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002115
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002116 if (le) {
2117 p += 7;
2118 incr = -1;
2119 }
Tim Peters9905b942003-03-20 20:53:32 +00002120
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002121 if (x < 0) {
2122 sign = 1;
2123 x = -x;
2124 }
2125 else
2126 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002127
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002128 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002129
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002130 /* Normalize f to be in the range [1.0, 2.0) */
2131 if (0.5 <= f && f < 1.0) {
2132 f *= 2.0;
2133 e--;
2134 }
2135 else if (f == 0.0)
2136 e = 0;
2137 else {
2138 PyErr_SetString(PyExc_SystemError,
2139 "frexp() result out of range");
2140 return -1;
2141 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002142
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002143 if (e >= 1024)
2144 goto Overflow;
2145 else if (e < -1022) {
2146 /* Gradual underflow */
2147 f = ldexp(f, 1022 + e);
2148 e = 0;
2149 }
2150 else if (!(e == 0 && f == 0.0)) {
2151 e += 1023;
2152 f -= 1.0; /* Get rid of leading 1 */
2153 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002154
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002155 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2156 f *= 268435456.0; /* 2**28 */
2157 fhi = (unsigned int)f; /* Truncate */
2158 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002160 f -= (double)fhi;
2161 f *= 16777216.0; /* 2**24 */
2162 flo = (unsigned int)(f + 0.5); /* Round */
2163 assert(flo <= 16777216);
2164 if (flo >> 24) {
2165 /* The carry propagated out of a string of 24 1 bits. */
2166 flo = 0;
2167 ++fhi;
2168 if (fhi >> 28) {
2169 /* And it also progagated out of the next 28 bits. */
2170 fhi = 0;
2171 ++e;
2172 if (e >= 2047)
2173 goto Overflow;
2174 }
2175 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002176
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002177 /* First byte */
2178 *p = (sign << 7) | (e >> 4);
2179 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002180
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002181 /* Second byte */
2182 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2183 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002184
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002185 /* Third byte */
2186 *p = (fhi >> 16) & 0xFF;
2187 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002189 /* Fourth byte */
2190 *p = (fhi >> 8) & 0xFF;
2191 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002192
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002193 /* Fifth byte */
2194 *p = fhi & 0xFF;
2195 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002197 /* Sixth byte */
2198 *p = (flo >> 16) & 0xFF;
2199 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002201 /* Seventh byte */
2202 *p = (flo >> 8) & 0xFF;
2203 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002205 /* Eighth byte */
2206 *p = flo & 0xFF;
2207 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002208
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002209 /* Done */
2210 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002211
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002212 Overflow:
2213 PyErr_SetString(PyExc_OverflowError,
2214 "float too large to pack with d format");
2215 return -1;
2216 }
2217 else {
2218 const char *s = (char*)&x;
2219 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002221 if ((double_format == ieee_little_endian_format && !le)
2222 || (double_format == ieee_big_endian_format && le)) {
2223 p += 7;
2224 incr = -1;
2225 }
2226
2227 for (i = 0; i < 8; i++) {
2228 *p = *s++;
2229 p += incr;
2230 }
2231 return 0;
2232 }
Tim Peters9905b942003-03-20 20:53:32 +00002233}
2234
2235double
2236_PyFloat_Unpack4(const unsigned char *p, int le)
2237{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002238 if (float_format == unknown_format) {
2239 unsigned char sign;
2240 int e;
2241 unsigned int f;
2242 double x;
2243 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002244
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002245 if (le) {
2246 p += 3;
2247 incr = -1;
2248 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002249
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002250 /* First byte */
2251 sign = (*p >> 7) & 1;
2252 e = (*p & 0x7F) << 1;
2253 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002255 /* Second byte */
2256 e |= (*p >> 7) & 1;
2257 f = (*p & 0x7F) << 16;
2258 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002259
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002260 if (e == 255) {
2261 PyErr_SetString(
2262 PyExc_ValueError,
2263 "can't unpack IEEE 754 special value "
2264 "on non-IEEE platform");
2265 return -1;
2266 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002267
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002268 /* Third byte */
2269 f |= *p << 8;
2270 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002272 /* Fourth byte */
2273 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002275 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002276
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002277 /* XXX This sadly ignores Inf/NaN issues */
2278 if (e == 0)
2279 e = -126;
2280 else {
2281 x += 1.0;
2282 e -= 127;
2283 }
2284 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002285
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002286 if (sign)
2287 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002288
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002289 return x;
2290 }
2291 else {
2292 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002293
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002294 if ((float_format == ieee_little_endian_format && !le)
2295 || (float_format == ieee_big_endian_format && le)) {
2296 char buf[4];
2297 char *d = &buf[3];
2298 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002299
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002300 for (i = 0; i < 4; i++) {
2301 *d-- = *p++;
2302 }
2303 memcpy(&x, buf, 4);
2304 }
2305 else {
2306 memcpy(&x, p, 4);
2307 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002308
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002309 return x;
2310 }
Tim Peters9905b942003-03-20 20:53:32 +00002311}
2312
2313double
2314_PyFloat_Unpack8(const unsigned char *p, int le)
2315{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002316 if (double_format == unknown_format) {
2317 unsigned char sign;
2318 int e;
2319 unsigned int fhi, flo;
2320 double x;
2321 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002322
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002323 if (le) {
2324 p += 7;
2325 incr = -1;
2326 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002327
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002328 /* First byte */
2329 sign = (*p >> 7) & 1;
2330 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002332 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002333
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002334 /* Second byte */
2335 e |= (*p >> 4) & 0xF;
2336 fhi = (*p & 0xF) << 24;
2337 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002339 if (e == 2047) {
2340 PyErr_SetString(
2341 PyExc_ValueError,
2342 "can't unpack IEEE 754 special value "
2343 "on non-IEEE platform");
2344 return -1.0;
2345 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002346
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002347 /* Third byte */
2348 fhi |= *p << 16;
2349 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002350
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002351 /* Fourth byte */
2352 fhi |= *p << 8;
2353 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002355 /* Fifth byte */
2356 fhi |= *p;
2357 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002358
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002359 /* Sixth byte */
2360 flo = *p << 16;
2361 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002363 /* Seventh byte */
2364 flo |= *p << 8;
2365 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002366
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002367 /* Eighth byte */
2368 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002369
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002370 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2371 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002372
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002373 if (e == 0)
2374 e = -1022;
2375 else {
2376 x += 1.0;
2377 e -= 1023;
2378 }
2379 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002380
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002381 if (sign)
2382 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002383
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002384 return x;
2385 }
2386 else {
2387 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002388
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002389 if ((double_format == ieee_little_endian_format && !le)
2390 || (double_format == ieee_big_endian_format && le)) {
2391 char buf[8];
2392 char *d = &buf[7];
2393 int i;
2394
2395 for (i = 0; i < 8; i++) {
2396 *d-- = *p++;
2397 }
2398 memcpy(&x, buf, 8);
2399 }
2400 else {
2401 memcpy(&x, p, 8);
2402 }
2403
2404 return x;
2405 }
Tim Peters9905b942003-03-20 20:53:32 +00002406}