blob: cd8c14fb2d5174c87ea74487c9287d848d54c470 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Christian Heimesbbe741d2008-03-28 10:53:29 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Guido van Rossum6923e131990-11-02 17:50:43 +000022
Christian Heimes969fe572008-01-25 11:23:10 +000023#ifdef _OSF_SOURCE
24/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
25extern int finite(double);
26#endif
27
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000029#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000030#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000031#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000032
Guido van Rossum3fce8831999-03-12 19:43:17 +000033struct _floatblock {
34 struct _floatblock *next;
35 PyFloatObject objects[N_FLOATOBJECTS];
36};
37
38typedef struct _floatblock PyFloatBlock;
39
40static PyFloatBlock *block_list = NULL;
41static PyFloatObject *free_list = NULL;
42
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000044fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045{
46 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
48 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000050 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000051 ((PyFloatBlock *)p)->next = block_list;
52 block_list = (PyFloatBlock *)p;
53 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 q = p + N_FLOATOBJECTS;
55 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000056 Py_TYPE(q) = (struct _typeobject *)(q-1);
57 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 return p + N_FLOATOBJECTS - 1;
59}
60
Christian Heimes93852662007-12-01 12:22:32 +000061double
62PyFloat_GetMax(void)
63{
64 return DBL_MAX;
65}
66
67double
68PyFloat_GetMin(void)
69{
70 return DBL_MIN;
71}
72
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073static PyTypeObject FloatInfoType;
74
75PyDoc_STRVAR(floatinfo__doc__,
76"sys.floatinfo\n\
77\n\
78A structseq holding information about the float type. It contains low level\n\
79information about the precision and internal representation. Please study\n\
80your system's :file:`float.h` for more information.");
81
82static PyStructSequence_Field floatinfo_fields[] = {
83 {"max", "DBL_MAX -- maximum representable finite float"},
84 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
85 "is representable"},
86 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
87 "is representable"},
88 {"min", "DBL_MIN -- Minimum positive normalizer float"},
89 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
90 "is a normalized float"},
91 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
92 "a normalized"},
93 {"dig", "DBL_DIG -- digits"},
94 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
95 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
96 "representable float"},
97 {"radix", "FLT_RADIX -- radix of exponent"},
98 {"rounds", "FLT_ROUNDS -- addition rounds"},
99 {0}
100};
101
102static PyStructSequence_Desc floatinfo_desc = {
103 "sys.floatinfo", /* name */
104 floatinfo__doc__, /* doc */
105 floatinfo_fields, /* fields */
106 11
107};
108
Christian Heimes93852662007-12-01 12:22:32 +0000109PyObject *
110PyFloat_GetInfo(void)
111{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000112 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000113 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000114
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000115 floatinfo = PyStructSequence_New(&FloatInfoType);
116 if (floatinfo == NULL) {
117 return NULL;
118 }
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120#define SetIntFlag(flag) \
121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
122#define SetDblFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125 SetDblFlag(DBL_MAX);
126 SetIntFlag(DBL_MAX_EXP);
127 SetIntFlag(DBL_MAX_10_EXP);
128 SetDblFlag(DBL_MIN);
129 SetIntFlag(DBL_MIN_EXP);
130 SetIntFlag(DBL_MIN_10_EXP);
131 SetIntFlag(DBL_DIG);
132 SetIntFlag(DBL_MANT_DIG);
133 SetDblFlag(DBL_EPSILON);
134 SetIntFlag(FLT_RADIX);
135 SetIntFlag(FLT_ROUNDS);
136#undef SetIntFlag
137#undef SetDblFlag
138
139 if (PyErr_Occurred()) {
140 Py_CLEAR(floatinfo);
141 return NULL;
142 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000143 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000144}
145
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000154 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000155 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000163PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164{
Mark Dickinson6d65df12009-04-26 15:30:47 +0000165 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000167 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000172 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000178 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000180 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000181 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000183 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000186 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000189 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000190
Mark Dickinsonaa77d262009-05-03 21:07:13 +0000191 while (Py_ISSPACE(*s))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 s++;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000193 /* We don't care about overflow or underflow. If the platform
194 * supports them, infinities and signed zeroes (on underflow) are
195 * fine. */
Mark Dickinson725bfd82009-05-03 20:33:40 +0000196 x = PyOS_string_to_double(s, (char **)&end, NULL);
197 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum2be161d2007-05-15 20:43:51 +0000198 goto error;
Mark Dickinsonaa77d262009-05-03 21:07:13 +0000199 while (Py_ISSPACE(*end))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000200 end++;
Mark Dickinson725bfd82009-05-03 20:33:40 +0000201 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;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000209
Guido van Rossum2be161d2007-05-15 20:43:51 +0000210 error:
211 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{
Guido van Rossum9475a232001-10-05 20:51:39 +0000219 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000220 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000221 free_list = op;
222 }
223 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000224 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{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230 PyNumberMethods *nb;
231 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000233
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (op && PyFloat_Check(op))
235 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000236
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000237 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239 return -1;
240 }
Tim Petersd2364e82001-11-01 20:09:42 +0000241
Christian Heimes90aa7642007-12-19 02:45:37 +0000242 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000243 PyErr_SetString(PyExc_TypeError, "a float is required");
244 return -1;
245 }
246
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000248 if (fo == NULL)
249 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250 if (!PyFloat_Check(fo)) {
251 PyErr_SetString(PyExc_TypeError,
252 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000253 return -1;
254 }
Tim Petersd2364e82001-11-01 20:09:42 +0000255
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000256 val = PyFloat_AS_DOUBLE(fo);
257 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Guido van Rossumb6775db1994-08-01 11:34:53 +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*/
Neil Schemenauer32117e52001-01-04 01:44:34 +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;
273
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{
279 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000280
Guido van Rossumddefaf32007-01-14 03:31:43 +0000281 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000282 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000283 if (*dbl == -1.0 && PyErr_Occurred()) {
284 *v = NULL;
285 return -1;
286 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000287 }
288 else {
289 Py_INCREF(Py_NotImplemented);
290 *v = Py_NotImplemented;
291 return -1;
292 }
293 return 0;
294}
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)
305 return PyErr_NoMemory();
306 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{
341 double i, j;
342 int r = 0;
343
Tim Peters307fa782004-09-23 08:06:40 +0000344 assert(PyFloat_Check(v));
345 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000346
Tim Peters307fa782004-09-23 08:06:40 +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);
352
Thomas Wouters477c8d52006-05-27 19:21:47 +0000353 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000354 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000355 /* 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.
Tim Peters307fa782004-09-23 08:06:40 +0000358 */
359 j = 0.0;
360 else
361 goto Unimplemented;
362 }
363
Tim Peters307fa782004-09-23 08:06:40 +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;
Tim Peters307fa782004-09-23 08:06:40 +0000368 int exponent;
369
370 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
Tim Peterse1c69b32004-09-23 19:22:41 +0000383 * 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.
Tim Peters307fa782004-09-23 08:06:40 +0000387 */
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);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000413 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000414 /* 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;
438
439 if (wsign < 0) {
440 ww = PyNumber_Negative(w);
441 if (ww == NULL)
442 goto Error;
443 }
444 else
445 Py_INCREF(ww);
446
447 fracpart = modf(i, &intpart);
448 vv = PyLong_FromDouble(intpart);
449 if (vv == NULL)
450 goto Error;
451
452 if (fracpart != 0.0) {
453 /* Shift left, and or a 1 bit into vv
454 * to represent the lost fraction.
455 */
456 PyObject *temp;
457
Christian Heimes217cfd12007-12-02 14:31:20 +0000458 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000459 if (one == NULL)
460 goto Error;
461
462 temp = PyNumber_Lshift(ww, one);
463 if (temp == NULL)
464 goto Error;
465 Py_DECREF(ww);
466 ww = temp;
467
468 temp = PyNumber_Lshift(vv, one);
469 if (temp == NULL)
470 goto Error;
471 Py_DECREF(vv);
472 vv = temp;
473
474 temp = PyNumber_Or(vv, one);
475 if (temp == NULL)
476 goto Error;
477 Py_DECREF(vv);
478 vv = temp;
479 }
480
481 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)) */
492
493 else /* w isn't float, int, or long */
494 goto Unimplemented;
495
496 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000497 PyFPE_START_PROTECT("richcompare", return NULL)
498 switch (op) {
499 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000500 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000501 break;
502 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000503 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000504 break;
505 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000506 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000507 break;
508 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000509 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000510 break;
511 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000512 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000513 break;
514 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000515 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000516 break;
517 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000518 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000519 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000520
521 Unimplemented:
522 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{
Tim Peters39dce292000-08-15 03:34:48 +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{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000535 double a,b;
536 CONVERT_TO_DOUBLE(v, a);
537 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000538 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000539 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{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000547 double a,b;
548 CONVERT_TO_DOUBLE(v, a);
549 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000550 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000551 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{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000559 double a,b;
560 CONVERT_TO_DOUBLE(v, a);
561 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000562 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563 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{
Neil Schemenauer32117e52001-01-04 01:44:34 +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
Neil Schemenauer32117e52001-01-04 01:44:34 +0000575 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000576 PyErr_SetString(PyExc_ZeroDivisionError,
577 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578 return NULL;
579 }
Christian Heimes53876d92008-04-19 00:31:39 +0000580#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000581 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000582 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{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000590 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000591 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000592 CONVERT_TO_DOUBLE(v, vx);
593 CONVERT_TO_DOUBLE(w, wx);
594#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000596 PyErr_SetString(PyExc_ZeroDivisionError,
597 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598 return NULL;
599 }
Christian Heimes53876d92008-04-19 00:31:39 +0000600#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000601 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000602 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000603 /* note: checking mod*wx < 0 is incorrect -- underflows to
604 0 if wx < sqrt(smallest nonzero double) */
605 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000606 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000607 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000608 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000609 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610}
611
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000613float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000614{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000615 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000616 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000617 CONVERT_TO_DOUBLE(v, vx);
618 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000619 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000620 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000621 return NULL;
622 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000623 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000624 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000625 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000626 exact multiple of wx. But this is fp arithmetic, and fp
627 vx - mod is an approximation; the result is that div may
628 not be an exact integral value after the division, although
629 it will always be very close to one.
630 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000631 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000632 if (mod) {
633 /* ensure the remainder has the same sign as the denominator */
634 if ((wx < 0) != (mod < 0)) {
635 mod += wx;
636 div -= 1.0;
637 }
638 }
639 else {
640 /* the remainder is zero, and in the presence of signed zeroes
641 fmod returns different results across platforms; ensure
642 it has the same sign as the denominator; we'd like to do
643 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000644 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000645 if (wx < 0.0)
646 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000647 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000648 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000649 if (div) {
650 floordiv = floor(div);
651 if (div - floordiv > 0.5)
652 floordiv += 1.0;
653 }
654 else {
655 /* div is zero - get the same sign as the true quotient */
656 div *= div; /* hide "div = +0" from optimizers */
657 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
658 }
659 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000660 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000661}
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000664float_floor_div(PyObject *v, PyObject *w)
665{
666 PyObject *t, *r;
667
668 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000669 if (t == NULL || t == Py_NotImplemented)
670 return t;
671 assert(PyTuple_CheckExact(t));
672 r = PyTuple_GET_ITEM(t, 0);
673 Py_INCREF(r);
674 Py_DECREF(t);
675 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000676}
677
678static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680{
681 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000682
683 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000684 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000685 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000686 return NULL;
687 }
688
Neil Schemenauer32117e52001-01-04 01:44:34 +0000689 CONVERT_TO_DOUBLE(v, iv);
690 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000691
692 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000693 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000694 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000695 }
Tim Peters96685bf2001-08-23 22:31:37 +0000696 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000697 if (iw < 0.0) {
698 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000699 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000700 return NULL;
701 }
702 return PyFloat_FromDouble(0.0);
703 }
Christian Heimes53876d92008-04-19 00:31:39 +0000704 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
705 return PyFloat_FromDouble(1.0);
706 }
Tim Peterse87568d2003-05-24 20:18:24 +0000707 if (iv < 0.0) {
708 /* Whether this is an error is a mess, and bumps into libm
709 * bugs so we have to figure it out ourselves.
710 */
711 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000712 /* Negative numbers raised to fractional powers
713 * become complex.
714 */
715 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000716 }
717 /* iw is an exact integer, albeit perhaps a very large one.
718 * -1 raised to an exact integer should never be exceptional.
719 * Alas, some libms (chiefly glibc as of early 2003) return
720 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
721 * happen to be representable in a *C* integer. That's a
722 * bug; we let that slide in math.pow() (which currently
723 * reflects all platform accidents), but not for Python's **.
724 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000726 /* Return 1 if iw is even, -1 if iw is odd; there's
727 * no guarantee that any C integral type is big
728 * enough to hold iw, so we have to check this
729 * indirectly.
730 */
731 ix = floor(iw * 0.5) * 2.0;
732 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
733 }
734 /* Else iv != -1.0, and overflow or underflow are possible.
735 * Unless we're to write pow() ourselves, we have to trust
736 * the platform to do this correctly.
737 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000738 }
Tim Peters96685bf2001-08-23 22:31:37 +0000739 errno = 0;
740 PyFPE_START_PROTECT("pow", return NULL)
741 ix = pow(iv, iw);
742 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000743 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000744 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000745 /* We don't expect any errno value other than ERANGE, but
746 * the range of libm bugs appears unbounded.
747 */
748 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
749 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000750 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000751 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000753}
754
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000756float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000757{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000758 return PyFloat_FromDouble(-v->ob_fval);
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_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000763{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000764 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000765}
766
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000767static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000768float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000769{
770 return v->ob_fval != 0.0;
771}
772
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000774float_is_integer(PyObject *v)
775{
776 double x = PyFloat_AsDouble(v);
777 PyObject *o;
778
779 if (x == -1.0 && PyErr_Occurred())
780 return NULL;
781 if (!Py_IS_FINITE(x))
782 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000783 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000784 PyFPE_START_PROTECT("is_integer", return NULL)
785 o = (floor(x) == x) ? Py_True : Py_False;
786 PyFPE_END_PROTECT(x)
787 if (errno != 0) {
788 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
789 PyExc_ValueError);
790 return NULL;
791 }
792 Py_INCREF(o);
793 return o;
794}
795
796#if 0
797static PyObject *
798float_is_inf(PyObject *v)
799{
800 double x = PyFloat_AsDouble(v);
801 if (x == -1.0 && PyErr_Occurred())
802 return NULL;
803 return PyBool_FromLong((long)Py_IS_INFINITY(x));
804}
805
806static PyObject *
807float_is_nan(PyObject *v)
808{
809 double x = PyFloat_AsDouble(v);
810 if (x == -1.0 && PyErr_Occurred())
811 return NULL;
812 return PyBool_FromLong((long)Py_IS_NAN(x));
813}
814
815static PyObject *
816float_is_finite(PyObject *v)
817{
818 double x = PyFloat_AsDouble(v);
819 if (x == -1.0 && PyErr_Occurred())
820 return NULL;
821 return PyBool_FromLong((long)Py_IS_FINITE(x));
822}
823#endif
824
825static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000826float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000827{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000828 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000829 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000830
831 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000832 /* Try to get out cheap if this fits in a Python int. The attempt
833 * to cast to long must be protected, as C doesn't define what
834 * happens if the double is too big to fit in a long. Some rare
835 * systems raise an exception then (RISCOS was mentioned as one,
836 * and someone using a non-default option on Sun also bumped into
837 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
838 * still be vulnerable: if a long has more bits of precision than
839 * a double, casting MIN/MAX to double may yield an approximation,
840 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
841 * yield true from the C expression wholepart<=LONG_MAX, despite
842 * that wholepart is actually greater than LONG_MAX.
843 */
844 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
845 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000846 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000847 }
848 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000849}
850
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000851/* double_round: rounds a finite double to the closest multiple of
852 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
853 ndigits <= 323). Returns a Python float, or sets a Python error and
854 returns NULL on failure (OverflowError and memory errors are possible). */
855
856#ifndef PY_NO_SHORT_FLOAT_REPR
857/* version of double_round that uses the correctly-rounded string<->double
858 conversions from Python/dtoa.c */
859
860static PyObject *
861double_round(double x, int ndigits) {
862
863 double rounded;
864 Py_ssize_t buflen, mybuflen=100;
865 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
866 int decpt, sign;
867 PyObject *result = NULL;
868
869 /* round to a decimal string */
870 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
871 if (buf == NULL) {
872 PyErr_NoMemory();
873 return NULL;
874 }
875
876 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
877 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
878 buflen = buf_end - buf;
879 if (buflen + 8 > mybuflen) {
880 mybuflen = buflen+8;
881 mybuf = (char *)PyMem_Malloc(mybuflen);
882 if (mybuf == NULL) {
883 PyErr_NoMemory();
884 goto exit;
885 }
886 }
887 /* copy buf to mybuf, adding exponent, sign and leading 0 */
888 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
889 buf, decpt - (int)buflen);
890
891 /* and convert the resulting string back to a double */
892 errno = 0;
893 rounded = _Py_dg_strtod(mybuf, NULL);
894 if (errno == ERANGE && fabs(rounded) >= 1.)
895 PyErr_SetString(PyExc_OverflowError,
896 "rounded value too large to represent");
897 else
898 result = PyFloat_FromDouble(rounded);
899
900 /* done computing value; now clean up */
901 if (mybuf != shortbuf)
902 PyMem_Free(mybuf);
903 exit:
904 _Py_dg_freedtoa(buf);
905 return result;
906}
907
908#else /* PY_NO_SHORT_FLOAT_REPR */
909
910/* fallback version, to be used when correctly rounded binary<->decimal
911 conversions aren't available */
912
913static PyObject *
914double_round(double x, int ndigits) {
915 double pow1, pow2, y, z;
916 if (ndigits >= 0) {
917 if (ndigits > 22) {
918 /* pow1 and pow2 are each safe from overflow, but
919 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
920 pow1 = pow(10.0, (double)(ndigits-22));
921 pow2 = 1e22;
922 }
923 else {
924 pow1 = pow(10.0, (double)ndigits);
925 pow2 = 1.0;
926 }
927 y = (x*pow1)*pow2;
928 /* if y overflows, then rounded value is exactly x */
929 if (!Py_IS_FINITE(y))
930 return PyFloat_FromDouble(x);
931 }
932 else {
933 pow1 = pow(10.0, (double)-ndigits);
934 pow2 = 1.0; /* unused; silences a gcc compiler warning */
935 y = x / pow1;
936 }
937
938 z = round(y);
939 if (fabs(y-z) == 0.5)
940 /* halfway between two integers; use round-half-even */
941 z = 2.0*round(y/2.0);
942
943 if (ndigits >= 0)
944 z = (z / pow2) / pow1;
945 else
946 z *= pow1;
947
948 /* if computation resulted in overflow, raise OverflowError */
949 if (!Py_IS_FINITE(z)) {
950 PyErr_SetString(PyExc_OverflowError,
951 "overflow occurred during round");
952 return NULL;
953 }
954
955 return PyFloat_FromDouble(z);
956}
957
958#endif /* PY_NO_SHORT_FLOAT_REPR */
959
960/* round a Python float v to the closest multiple of 10**-ndigits */
961
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000962static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000963float_round(PyObject *v, PyObject *args)
964{
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000965 double x, rounded;
966 PyObject *o_ndigits = NULL;
967 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000968
969 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000970 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
971 return NULL;
972 if (o_ndigits == NULL) {
973 /* single-argument round: round to nearest integer */
974 rounded = round(x);
975 if (fabs(x-rounded) == 0.5)
976 /* halfway case: round to even */
977 rounded = 2.0*round(x/2.0);
978 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000979 }
980
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000981 /* interpret second argument as a Py_ssize_t; clips on overflow */
982 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
983 if (ndigits == -1 && PyErr_Occurred())
984 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000985
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000986 /* nans and infinities round to themselves */
987 if (!Py_IS_FINITE(x))
988 return PyFloat_FromDouble(x);
989
990 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
991 always rounds to itself. For ndigits < NDIGITS_MIN, x always
992 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
993#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
994#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
995 if (ndigits > NDIGITS_MAX)
996 /* return x */
997 return PyFloat_FromDouble(x);
998 else if (ndigits < NDIGITS_MIN)
999 /* return 0.0, but with sign of x */
1000 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001001 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001002 /* finite x, and ndigits is not unreasonably large */
1003 return double_round(x, (int)ndigits);
1004#undef NDIGITS_MAX
1005#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001006}
1007
1008static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001009float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001010{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001011 if (PyFloat_CheckExact(v))
1012 Py_INCREF(v);
1013 else
1014 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001015 return v;
1016}
1017
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001018/* turn ASCII hex characters into integer values and vice versa */
1019
1020static char
1021char_from_hex(int x)
1022{
1023 assert(0 <= x && x < 16);
1024 return "0123456789abcdef"[x];
1025}
1026
1027static int
1028hex_from_char(char c) {
1029 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001030 switch(c) {
1031 case '0':
1032 x = 0;
1033 break;
1034 case '1':
1035 x = 1;
1036 break;
1037 case '2':
1038 x = 2;
1039 break;
1040 case '3':
1041 x = 3;
1042 break;
1043 case '4':
1044 x = 4;
1045 break;
1046 case '5':
1047 x = 5;
1048 break;
1049 case '6':
1050 x = 6;
1051 break;
1052 case '7':
1053 x = 7;
1054 break;
1055 case '8':
1056 x = 8;
1057 break;
1058 case '9':
1059 x = 9;
1060 break;
1061 case 'a':
1062 case 'A':
1063 x = 10;
1064 break;
1065 case 'b':
1066 case 'B':
1067 x = 11;
1068 break;
1069 case 'c':
1070 case 'C':
1071 x = 12;
1072 break;
1073 case 'd':
1074 case 'D':
1075 x = 13;
1076 break;
1077 case 'e':
1078 case 'E':
1079 x = 14;
1080 break;
1081 case 'f':
1082 case 'F':
1083 x = 15;
1084 break;
1085 default:
1086 x = -1;
1087 break;
1088 }
1089 return x;
1090}
1091
1092/* convert a float to a hexadecimal string */
1093
1094/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1095 of the form 4k+1. */
1096#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1097
1098static PyObject *
1099float_hex(PyObject *v)
1100{
1101 double x, m;
1102 int e, shift, i, si, esign;
1103 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1104 trailing NUL byte. */
1105 char s[(TOHEX_NBITS-1)/4+3];
1106
1107 CONVERT_TO_DOUBLE(v, x);
1108
1109 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1110 return float_str((PyFloatObject *)v);
1111
1112 if (x == 0.0) {
1113 if(copysign(1.0, x) == -1.0)
1114 return PyUnicode_FromString("-0x0.0p+0");
1115 else
1116 return PyUnicode_FromString("0x0.0p+0");
1117 }
1118
1119 m = frexp(fabs(x), &e);
1120 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1121 m = ldexp(m, shift);
1122 e -= shift;
1123
1124 si = 0;
1125 s[si] = char_from_hex((int)m);
1126 si++;
1127 m -= (int)m;
1128 s[si] = '.';
1129 si++;
1130 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1131 m *= 16.0;
1132 s[si] = char_from_hex((int)m);
1133 si++;
1134 m -= (int)m;
1135 }
1136 s[si] = '\0';
1137
1138 if (e < 0) {
1139 esign = (int)'-';
1140 e = -e;
1141 }
1142 else
1143 esign = (int)'+';
1144
1145 if (x < 0.0)
1146 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1147 else
1148 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1149}
1150
1151PyDoc_STRVAR(float_hex_doc,
1152"float.hex() -> string\n\
1153\n\
1154Return a hexadecimal representation of a floating-point number.\n\
1155>>> (-0.1).hex()\n\
1156'-0x1.999999999999ap-4'\n\
1157>>> 3.14159.hex()\n\
1158'0x1.921f9f01b866ep+1'");
1159
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001160/* Case-insensitive locale-independent string match used for nan and inf
1161 detection. t should be lower-case and null-terminated. Return a nonzero
1162 result if the first strlen(t) characters of s match t and 0 otherwise. */
1163
1164static int
1165case_insensitive_match(const char *s, const char *t)
1166{
1167 while(*t && Py_TOLOWER(*s) == *t) {
1168 s++;
1169 t++;
1170 }
1171 return *t ? 0 : 1;
1172}
1173
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001174/* Convert a hexadecimal string to a float. */
1175
1176static PyObject *
1177float_fromhex(PyObject *cls, PyObject *arg)
1178{
1179 PyObject *result_as_float, *result;
1180 double x;
1181 long exp, top_exp, lsb, key_digit;
1182 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1183 int half_eps, digit, round_up, sign=1;
1184 Py_ssize_t length, ndigits, fdigits, i;
1185
1186 /*
1187 * For the sake of simplicity and correctness, we impose an artificial
1188 * limit on ndigits, the total number of hex digits in the coefficient
1189 * The limit is chosen to ensure that, writing exp for the exponent,
1190 *
1191 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1192 * guaranteed to overflow (provided it's nonzero)
1193 *
1194 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1195 * guaranteed to underflow to 0.
1196 *
1197 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1198 * overflow in the calculation of exp and top_exp below.
1199 *
1200 * More specifically, ndigits is assumed to satisfy the following
1201 * inequalities:
1202 *
1203 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1204 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1205 *
1206 * If either of these inequalities is not satisfied, a ValueError is
1207 * raised. Otherwise, write x for the value of the hex string, and
1208 * assume x is nonzero. Then
1209 *
1210 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1211 *
1212 * Now if exp > LONG_MAX/2 then:
1213 *
1214 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1215 * = DBL_MAX_EXP
1216 *
1217 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1218 * double, so overflows. If exp < LONG_MIN/2, then
1219 *
1220 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1221 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1222 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1223 *
1224 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1225 * when converted to a C double.
1226 *
1227 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1228 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1229 */
1230
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001231 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001232 if (s == NULL)
1233 return NULL;
1234 s_end = s + length;
1235
1236 /********************
1237 * Parse the string *
1238 ********************/
1239
1240 /* leading whitespace and optional sign */
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001241 while (Py_ISSPACE(*s))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001242 s++;
1243 if (*s == '-') {
1244 s++;
1245 sign = -1;
1246 }
1247 else if (*s == '+')
1248 s++;
1249
1250 /* infinities and nans */
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001251 if (*s == 'i' || *s == 'I') {
1252 if (!case_insensitive_match(s+1, "nf"))
1253 goto parse_error;
1254 s += 3;
1255 x = Py_HUGE_VAL;
1256 if (case_insensitive_match(s, "inity"))
1257 s += 5;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258 goto finished;
1259 }
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001260 if (*s == 'n' || *s == 'N') {
1261 if (!case_insensitive_match(s+1, "an"))
1262 goto parse_error;
1263 s += 3;
1264 x = Py_NAN;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001265 goto finished;
1266 }
1267
1268 /* [0x] */
1269 s_store = s;
1270 if (*s == '0') {
1271 s++;
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001272 if (*s == 'x' || *s == 'X')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001273 s++;
1274 else
1275 s = s_store;
1276 }
1277
1278 /* coefficient: <integer> [. <fraction>] */
1279 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001280 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001281 s++;
1282 s_store = s;
1283 if (*s == '.') {
1284 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001285 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286 s++;
1287 coeff_end = s-1;
1288 }
1289 else
1290 coeff_end = s;
1291
1292 /* ndigits = total # of hex digits; fdigits = # after point */
1293 ndigits = coeff_end - coeff_start;
1294 fdigits = coeff_end - s_store;
1295 if (ndigits == 0)
1296 goto parse_error;
1297 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1298 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1299 goto insane_length_error;
1300
1301 /* [p <exponent>] */
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001302 if (*s == 'p' || *s == 'P') {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303 s++;
1304 exp_start = s;
1305 if (*s == '-' || *s == '+')
1306 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001307 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308 goto parse_error;
1309 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001310 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001311 s++;
1312 exp = strtol(exp_start, NULL, 10);
1313 }
1314 else
1315 exp = 0;
1316
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001317/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1318#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1319 coeff_end-(j) : \
1320 coeff_end-1-(j)))
1321
1322 /*******************************************
1323 * Compute rounded value of the hex string *
1324 *******************************************/
1325
1326 /* Discard leading zeros, and catch extreme overflow and underflow */
1327 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1328 ndigits--;
1329 if (ndigits == 0 || exp < LONG_MIN/2) {
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001330 x = 0.0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001331 goto finished;
1332 }
1333 if (exp > LONG_MAX/2)
1334 goto overflow_error;
1335
1336 /* Adjust exponent for fractional part. */
1337 exp = exp - 4*((long)fdigits);
1338
1339 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1340 top_exp = exp + 4*((long)ndigits - 1);
1341 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1342 top_exp++;
1343
1344 /* catch almost all nonextreme cases of overflow and underflow here */
1345 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001346 x = 0.0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001347 goto finished;
1348 }
1349 if (top_exp > DBL_MAX_EXP)
1350 goto overflow_error;
1351
1352 /* lsb = exponent of least significant bit of the *rounded* value.
1353 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1354 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1355
1356 x = 0.0;
1357 if (exp >= lsb) {
1358 /* no rounding required */
1359 for (i = ndigits-1; i >= 0; i--)
1360 x = 16.0*x + HEX_DIGIT(i);
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001361 x = ldexp(x, (int)(exp));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001362 goto finished;
1363 }
1364 /* rounding required. key_digit is the index of the hex digit
1365 containing the first bit to be rounded away. */
1366 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1367 key_digit = (lsb - exp - 1) / 4;
1368 for (i = ndigits-1; i > key_digit; i--)
1369 x = 16.0*x + HEX_DIGIT(i);
1370 digit = HEX_DIGIT(key_digit);
1371 x = 16.0*x + (double)(digit & (16-2*half_eps));
1372
1373 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1374 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1375 if ((digit & half_eps) != 0) {
1376 round_up = 0;
1377 if ((digit & (3*half_eps-1)) != 0 ||
1378 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1379 round_up = 1;
1380 else
1381 for (i = key_digit-1; i >= 0; i--)
1382 if (HEX_DIGIT(i) != 0) {
1383 round_up = 1;
1384 break;
1385 }
1386 if (round_up == 1) {
1387 x += 2*half_eps;
1388 if (top_exp == DBL_MAX_EXP &&
1389 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1390 /* overflow corner case: pre-rounded value <
1391 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1392 goto overflow_error;
1393 }
1394 }
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001395 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001396
1397 finished:
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001398 /* optional trailing whitespace leading to the end of the string */
1399 while (Py_ISSPACE(*s))
1400 s++;
1401 if (s != s_end)
1402 goto parse_error;
1403 result_as_float = Py_BuildValue("(d)", sign * x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001404 if (result_as_float == NULL)
1405 return NULL;
1406 result = PyObject_CallObject(cls, result_as_float);
1407 Py_DECREF(result_as_float);
1408 return result;
1409
1410 overflow_error:
1411 PyErr_SetString(PyExc_OverflowError,
1412 "hexadecimal value too large to represent as a float");
1413 return NULL;
1414
1415 parse_error:
1416 PyErr_SetString(PyExc_ValueError,
1417 "invalid hexadecimal floating-point string");
1418 return NULL;
1419
1420 insane_length_error:
1421 PyErr_SetString(PyExc_ValueError,
1422 "hexadecimal string too long to convert");
1423 return NULL;
1424}
1425
1426PyDoc_STRVAR(float_fromhex_doc,
1427"float.fromhex(string) -> float\n\
1428\n\
1429Create a floating-point number from a hexadecimal string.\n\
1430>>> float.fromhex('0x1.ffffp10')\n\
14312047.984375\n\
1432>>> float.fromhex('-0x1p-1074')\n\
1433-4.9406564584124654e-324");
1434
1435
Christian Heimes26855632008-01-27 23:50:43 +00001436static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001437float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001438{
1439 double self;
1440 double float_part;
1441 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001442 int i;
1443
Christian Heimes26855632008-01-27 23:50:43 +00001444 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001445 PyObject *py_exponent = NULL;
1446 PyObject *numerator = NULL;
1447 PyObject *denominator = NULL;
1448 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001449 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001450
1451#define INPLACE_UPDATE(obj, call) \
1452 prev = obj; \
1453 obj = call; \
1454 Py_DECREF(prev); \
1455
1456 CONVERT_TO_DOUBLE(v, self);
1457
1458 if (Py_IS_INFINITY(self)) {
1459 PyErr_SetString(PyExc_OverflowError,
1460 "Cannot pass infinity to float.as_integer_ratio.");
1461 return NULL;
1462 }
1463#ifdef Py_NAN
1464 if (Py_IS_NAN(self)) {
1465 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001466 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001467 return NULL;
1468 }
1469#endif
1470
Christian Heimes26855632008-01-27 23:50:43 +00001471 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001472 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001473 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001474
1475 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1476 float_part *= 2.0;
1477 exponent--;
1478 }
1479 /* self == float_part * 2**exponent exactly and float_part is integral.
1480 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1481 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001482
Christian Heimes292d3512008-02-03 16:51:08 +00001483 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001484 if (numerator == NULL) goto error;
1485
Christian Heimes292d3512008-02-03 16:51:08 +00001486 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001487 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001488 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001489 if (py_exponent == NULL) goto error;
1490 INPLACE_UPDATE(py_exponent,
1491 long_methods->nb_lshift(denominator, py_exponent));
1492 if (py_exponent == NULL) goto error;
1493 if (exponent > 0) {
1494 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001495 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001496 if (numerator == NULL) goto error;
1497 }
1498 else {
1499 Py_DECREF(denominator);
1500 denominator = py_exponent;
1501 py_exponent = NULL;
1502 }
1503
1504 result_pair = PyTuple_Pack(2, numerator, denominator);
1505
1506#undef INPLACE_UPDATE
1507error:
1508 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001509 Py_XDECREF(denominator);
1510 Py_XDECREF(numerator);
1511 return result_pair;
1512}
1513
1514PyDoc_STRVAR(float_as_integer_ratio_doc,
1515"float.as_integer_ratio() -> (int, int)\n"
1516"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001517"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1518"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001519"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001520"\n"
1521">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001522"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001523">>> (0.0).as_integer_ratio()\n"
1524"(0, 1)\n"
1525">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001526"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001527
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001528
Jeremy Hylton938ace62002-07-17 16:30:39 +00001529static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001530float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1531
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532static PyObject *
1533float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1534{
1535 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001536 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537
Guido van Rossumbef14172001-08-29 15:47:46 +00001538 if (type != &PyFloat_Type)
1539 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1541 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001542 /* If it's a string, but not a string subclass, use
1543 PyFloat_FromString. */
1544 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001545 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546 return PyNumber_Float(x);
1547}
1548
Guido van Rossumbef14172001-08-29 15:47:46 +00001549/* Wimpy, slow approach to tp_new calls for subtypes of float:
1550 first create a regular float from whatever arguments we got,
1551 then allocate a subtype instance and initialize its ob_fval
1552 from the regular float. The regular float is then thrown away.
1553*/
1554static PyObject *
1555float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1556{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001557 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001558
1559 assert(PyType_IsSubtype(type, &PyFloat_Type));
1560 tmp = float_new(&PyFloat_Type, args, kwds);
1561 if (tmp == NULL)
1562 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001563 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001564 newobj = type->tp_alloc(type, 0);
1565 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001566 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001567 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001568 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001569 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001570 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001571 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001572}
1573
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001574static PyObject *
1575float_getnewargs(PyFloatObject *v)
1576{
1577 return Py_BuildValue("(d)", v->ob_fval);
1578}
1579
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001580/* this is for the benefit of the pack/unpack routines below */
1581
1582typedef enum {
1583 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1584} float_format_type;
1585
1586static float_format_type double_format, float_format;
1587static float_format_type detected_double_format, detected_float_format;
1588
1589static PyObject *
1590float_getformat(PyTypeObject *v, PyObject* arg)
1591{
1592 char* s;
1593 float_format_type r;
1594
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001595 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001596 PyErr_Format(PyExc_TypeError,
1597 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001598 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001599 return NULL;
1600 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001601 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001602 if (s == NULL)
1603 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001604 if (strcmp(s, "double") == 0) {
1605 r = double_format;
1606 }
1607 else if (strcmp(s, "float") == 0) {
1608 r = float_format;
1609 }
1610 else {
1611 PyErr_SetString(PyExc_ValueError,
1612 "__getformat__() argument 1 must be "
1613 "'double' or 'float'");
1614 return NULL;
1615 }
1616
1617 switch (r) {
1618 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001619 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001621 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001622 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001623 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 default:
1625 Py_FatalError("insane float_format or double_format");
1626 return NULL;
1627 }
1628}
1629
1630PyDoc_STRVAR(float_getformat_doc,
1631"float.__getformat__(typestr) -> string\n"
1632"\n"
1633"You probably don't want to use this function. It exists mainly to be\n"
1634"used in Python's test suite.\n"
1635"\n"
1636"typestr must be 'double' or 'float'. This function returns whichever of\n"
1637"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1638"format of floating point numbers used by the C type named by typestr.");
1639
1640static PyObject *
1641float_setformat(PyTypeObject *v, PyObject* args)
1642{
1643 char* typestr;
1644 char* format;
1645 float_format_type f;
1646 float_format_type detected;
1647 float_format_type *p;
1648
1649 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1650 return NULL;
1651
1652 if (strcmp(typestr, "double") == 0) {
1653 p = &double_format;
1654 detected = detected_double_format;
1655 }
1656 else if (strcmp(typestr, "float") == 0) {
1657 p = &float_format;
1658 detected = detected_float_format;
1659 }
1660 else {
1661 PyErr_SetString(PyExc_ValueError,
1662 "__setformat__() argument 1 must "
1663 "be 'double' or 'float'");
1664 return NULL;
1665 }
1666
1667 if (strcmp(format, "unknown") == 0) {
1668 f = unknown_format;
1669 }
1670 else if (strcmp(format, "IEEE, little-endian") == 0) {
1671 f = ieee_little_endian_format;
1672 }
1673 else if (strcmp(format, "IEEE, big-endian") == 0) {
1674 f = ieee_big_endian_format;
1675 }
1676 else {
1677 PyErr_SetString(PyExc_ValueError,
1678 "__setformat__() argument 2 must be "
1679 "'unknown', 'IEEE, little-endian' or "
1680 "'IEEE, big-endian'");
1681 return NULL;
1682
1683 }
1684
1685 if (f != unknown_format && f != detected) {
1686 PyErr_Format(PyExc_ValueError,
1687 "can only set %s format to 'unknown' or the "
1688 "detected platform value", typestr);
1689 return NULL;
1690 }
1691
1692 *p = f;
1693 Py_RETURN_NONE;
1694}
1695
1696PyDoc_STRVAR(float_setformat_doc,
1697"float.__setformat__(typestr, fmt) -> None\n"
1698"\n"
1699"You probably don't want to use this function. It exists mainly to be\n"
1700"used in Python's test suite.\n"
1701"\n"
1702"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1703"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1704"one of the latter two if it appears to match the underlying C reality.\n"
1705"\n"
1706"Overrides the automatic determination of C-level floating point type.\n"
1707"This affects how floats are converted to and from binary strings.");
1708
Guido van Rossumb43daf72007-08-01 18:08:08 +00001709static PyObject *
1710float_getzero(PyObject *v, void *closure)
1711{
1712 return PyFloat_FromDouble(0.0);
1713}
1714
Eric Smith8c663262007-08-25 02:26:07 +00001715static PyObject *
1716float__format__(PyObject *self, PyObject *args)
1717{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001718 PyObject *format_spec;
1719
1720 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1721 return NULL;
1722 return _PyFloat_FormatAdvanced(self,
1723 PyUnicode_AS_UNICODE(format_spec),
1724 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001725}
1726
1727PyDoc_STRVAR(float__format__doc,
1728"float.__format__(format_spec) -> string\n"
1729"\n"
1730"Formats the float according to format_spec.");
1731
1732
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001733static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001734 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001735 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001736 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1737 "Returns the Integral closest to x between 0 and x."},
1738 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1739 "Returns the Integral closest to x, rounding half toward even.\n"
1740 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001741 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1742 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001743 {"fromhex", (PyCFunction)float_fromhex,
1744 METH_O|METH_CLASS, float_fromhex_doc},
1745 {"hex", (PyCFunction)float_hex,
1746 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001747 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1748 "Returns True if the float is an integer."},
1749#if 0
1750 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1751 "Returns True if the float is positive or negative infinite."},
1752 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1753 "Returns True if the float is finite, neither infinite nor NaN."},
1754 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1755 "Returns True if the float is not a number (NaN)."},
1756#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001757 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001758 {"__getformat__", (PyCFunction)float_getformat,
1759 METH_O|METH_CLASS, float_getformat_doc},
1760 {"__setformat__", (PyCFunction)float_setformat,
1761 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001762 {"__format__", (PyCFunction)float__format__,
1763 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001764 {NULL, NULL} /* sentinel */
1765};
1766
Guido van Rossumb43daf72007-08-01 18:08:08 +00001767static PyGetSetDef float_getset[] = {
1768 {"real",
1769 (getter)float_float, (setter)NULL,
1770 "the real part of a complex number",
1771 NULL},
1772 {"imag",
1773 (getter)float_getzero, (setter)NULL,
1774 "the imaginary part of a complex number",
1775 NULL},
1776 {NULL} /* Sentinel */
1777};
1778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001779PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780"float(x) -> floating point number\n\
1781\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001782Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783
1784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001785static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001786 float_add, /*nb_add*/
1787 float_sub, /*nb_subtract*/
1788 float_mul, /*nb_multiply*/
1789 float_rem, /*nb_remainder*/
1790 float_divmod, /*nb_divmod*/
1791 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001792 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001793 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001794 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001795 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001796 0, /*nb_invert*/
1797 0, /*nb_lshift*/
1798 0, /*nb_rshift*/
1799 0, /*nb_and*/
1800 0, /*nb_xor*/
1801 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001802 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001803 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001804 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001805 0, /* nb_inplace_add */
1806 0, /* nb_inplace_subtract */
1807 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001808 0, /* nb_inplace_remainder */
1809 0, /* nb_inplace_power */
1810 0, /* nb_inplace_lshift */
1811 0, /* nb_inplace_rshift */
1812 0, /* nb_inplace_and */
1813 0, /* nb_inplace_xor */
1814 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001815 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001816 float_div, /* nb_true_divide */
1817 0, /* nb_inplace_floor_divide */
1818 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819};
1820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001821PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001822 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001825 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001827 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 0, /* tp_getattr */
1829 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001830 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 (reprfunc)float_repr, /* tp_repr */
1832 &float_as_number, /* tp_as_number */
1833 0, /* tp_as_sequence */
1834 0, /* tp_as_mapping */
1835 (hashfunc)float_hash, /* tp_hash */
1836 0, /* tp_call */
1837 (reprfunc)float_str, /* tp_str */
1838 PyObject_GenericGetAttr, /* tp_getattro */
1839 0, /* tp_setattro */
1840 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001841 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 float_doc, /* tp_doc */
1843 0, /* tp_traverse */
1844 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001845 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 0, /* tp_weaklistoffset */
1847 0, /* tp_iter */
1848 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001849 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001851 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 0, /* tp_base */
1853 0, /* tp_dict */
1854 0, /* tp_descr_get */
1855 0, /* tp_descr_set */
1856 0, /* tp_dictoffset */
1857 0, /* tp_init */
1858 0, /* tp_alloc */
1859 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001860};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001861
1862void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001863_PyFloat_Init(void)
1864{
1865 /* We attempt to determine if this machine is using IEEE
1866 floating point formats by peering at the bits of some
1867 carefully chosen values. If it looks like we are on an
1868 IEEE platform, the float packing/unpacking routines can
1869 just copy bits, if not they resort to arithmetic & shifts
1870 and masks. The shifts & masks approach works on all finite
1871 values, but what happens to infinities, NaNs and signed
1872 zeroes on packing is an accident, and attempting to unpack
1873 a NaN or an infinity will raise an exception.
1874
1875 Note that if we're on some whacked-out platform which uses
1876 IEEE formats but isn't strictly little-endian or big-
1877 endian, we will fall back to the portable shifts & masks
1878 method. */
1879
1880#if SIZEOF_DOUBLE == 8
1881 {
1882 double x = 9006104071832581.0;
1883 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1884 detected_double_format = ieee_big_endian_format;
1885 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1886 detected_double_format = ieee_little_endian_format;
1887 else
1888 detected_double_format = unknown_format;
1889 }
1890#else
1891 detected_double_format = unknown_format;
1892#endif
1893
1894#if SIZEOF_FLOAT == 4
1895 {
1896 float y = 16711938.0;
1897 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1898 detected_float_format = ieee_big_endian_format;
1899 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1900 detected_float_format = ieee_little_endian_format;
1901 else
1902 detected_float_format = unknown_format;
1903 }
1904#else
1905 detected_float_format = unknown_format;
1906#endif
1907
1908 double_format = detected_double_format;
1909 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001910
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001911 /* Init float info */
1912 if (FloatInfoType.tp_name == 0)
1913 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001914}
1915
Georg Brandl2ee470f2008-07-16 12:55:28 +00001916int
1917PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001918{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001919 PyFloatObject *p;
1920 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001921 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001922 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001923 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001924
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001925 list = block_list;
1926 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001927 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001928 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001929 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001930 for (i = 0, p = &list->objects[0];
1931 i < N_FLOATOBJECTS;
1932 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001933 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001934 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001935 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001936 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001937 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001938 list->next = block_list;
1939 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001940 for (i = 0, p = &list->objects[0];
1941 i < N_FLOATOBJECTS;
1942 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001943 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001944 Py_REFCNT(p) == 0) {
1945 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001946 free_list;
1947 free_list = p;
1948 }
1949 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001950 }
1951 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001952 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001953 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001954 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001955 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001956 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001957 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001958}
1959
1960void
1961PyFloat_Fini(void)
1962{
1963 PyFloatObject *p;
1964 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001965 int i;
1966 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001967
Georg Brandl2ee470f2008-07-16 12:55:28 +00001968 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001969
Guido van Rossum3fce8831999-03-12 19:43:17 +00001970 if (!Py_VerboseFlag)
1971 return;
1972 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001973 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001974 fprintf(stderr, "\n");
1975 }
1976 else {
1977 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001978 ": %d unfreed float%s\n",
1979 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001980 }
1981 if (Py_VerboseFlag > 1) {
1982 list = block_list;
1983 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001984 for (i = 0, p = &list->objects[0];
1985 i < N_FLOATOBJECTS;
1986 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001987 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001988 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00001989 char *buf = PyOS_double_to_string(
1990 PyFloat_AS_DOUBLE(p), 'r',
1991 0, 0, NULL);
1992 if (buf) {
1993 /* XXX(twouters) cast
1994 refcount to long
1995 until %zd is
1996 universally
1997 available
1998 */
1999 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002000 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00002001 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00002002 PyMem_Free(buf);
2003 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002004 }
2005 }
2006 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002007 }
2008 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002009}
Tim Peters9905b942003-03-20 20:53:32 +00002010
2011/*----------------------------------------------------------------------------
2012 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002013 */
2014int
2015_PyFloat_Pack4(double x, unsigned char *p, int le)
2016{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002017 if (float_format == unknown_format) {
2018 unsigned char sign;
2019 int e;
2020 double f;
2021 unsigned int fbits;
2022 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002023
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024 if (le) {
2025 p += 3;
2026 incr = -1;
2027 }
Tim Peters9905b942003-03-20 20:53:32 +00002028
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002029 if (x < 0) {
2030 sign = 1;
2031 x = -x;
2032 }
2033 else
2034 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002035
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002036 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002037
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002038 /* Normalize f to be in the range [1.0, 2.0) */
2039 if (0.5 <= f && f < 1.0) {
2040 f *= 2.0;
2041 e--;
2042 }
2043 else if (f == 0.0)
2044 e = 0;
2045 else {
2046 PyErr_SetString(PyExc_SystemError,
2047 "frexp() result out of range");
2048 return -1;
2049 }
2050
2051 if (e >= 128)
2052 goto Overflow;
2053 else if (e < -126) {
2054 /* Gradual underflow */
2055 f = ldexp(f, 126 + e);
2056 e = 0;
2057 }
2058 else if (!(e == 0 && f == 0.0)) {
2059 e += 127;
2060 f -= 1.0; /* Get rid of leading 1 */
2061 }
2062
2063 f *= 8388608.0; /* 2**23 */
2064 fbits = (unsigned int)(f + 0.5); /* Round */
2065 assert(fbits <= 8388608);
2066 if (fbits >> 23) {
2067 /* The carry propagated out of a string of 23 1 bits. */
2068 fbits = 0;
2069 ++e;
2070 if (e >= 255)
2071 goto Overflow;
2072 }
2073
2074 /* First byte */
2075 *p = (sign << 7) | (e >> 1);
2076 p += incr;
2077
2078 /* Second byte */
2079 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2080 p += incr;
2081
2082 /* Third byte */
2083 *p = (fbits >> 8) & 0xFF;
2084 p += incr;
2085
2086 /* Fourth byte */
2087 *p = fbits & 0xFF;
2088
2089 /* Done */
2090 return 0;
2091
Tim Peters9905b942003-03-20 20:53:32 +00002092 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002093 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002094 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002095 const char *s = (char*)&y;
2096 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002097
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002098 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2099 goto Overflow;
2100
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101 if ((float_format == ieee_little_endian_format && !le)
2102 || (float_format == ieee_big_endian_format && le)) {
2103 p += 3;
2104 incr = -1;
2105 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002106
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107 for (i = 0; i < 4; i++) {
2108 *p = *s++;
2109 p += incr;
2110 }
2111 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002112 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002113 Overflow:
2114 PyErr_SetString(PyExc_OverflowError,
2115 "float too large to pack with f format");
2116 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002117}
2118
2119int
2120_PyFloat_Pack8(double x, unsigned char *p, int le)
2121{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 if (double_format == unknown_format) {
2123 unsigned char sign;
2124 int e;
2125 double f;
2126 unsigned int fhi, flo;
2127 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002128
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129 if (le) {
2130 p += 7;
2131 incr = -1;
2132 }
Tim Peters9905b942003-03-20 20:53:32 +00002133
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002134 if (x < 0) {
2135 sign = 1;
2136 x = -x;
2137 }
2138 else
2139 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002140
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002141 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002142
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002143 /* Normalize f to be in the range [1.0, 2.0) */
2144 if (0.5 <= f && f < 1.0) {
2145 f *= 2.0;
2146 e--;
2147 }
2148 else if (f == 0.0)
2149 e = 0;
2150 else {
2151 PyErr_SetString(PyExc_SystemError,
2152 "frexp() result out of range");
2153 return -1;
2154 }
2155
2156 if (e >= 1024)
2157 goto Overflow;
2158 else if (e < -1022) {
2159 /* Gradual underflow */
2160 f = ldexp(f, 1022 + e);
2161 e = 0;
2162 }
2163 else if (!(e == 0 && f == 0.0)) {
2164 e += 1023;
2165 f -= 1.0; /* Get rid of leading 1 */
2166 }
2167
2168 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2169 f *= 268435456.0; /* 2**28 */
2170 fhi = (unsigned int)f; /* Truncate */
2171 assert(fhi < 268435456);
2172
2173 f -= (double)fhi;
2174 f *= 16777216.0; /* 2**24 */
2175 flo = (unsigned int)(f + 0.5); /* Round */
2176 assert(flo <= 16777216);
2177 if (flo >> 24) {
2178 /* The carry propagated out of a string of 24 1 bits. */
2179 flo = 0;
2180 ++fhi;
2181 if (fhi >> 28) {
2182 /* And it also progagated out of the next 28 bits. */
2183 fhi = 0;
2184 ++e;
2185 if (e >= 2047)
2186 goto Overflow;
2187 }
2188 }
2189
2190 /* First byte */
2191 *p = (sign << 7) | (e >> 4);
2192 p += incr;
2193
2194 /* Second byte */
2195 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2196 p += incr;
2197
2198 /* Third byte */
2199 *p = (fhi >> 16) & 0xFF;
2200 p += incr;
2201
2202 /* Fourth byte */
2203 *p = (fhi >> 8) & 0xFF;
2204 p += incr;
2205
2206 /* Fifth byte */
2207 *p = fhi & 0xFF;
2208 p += incr;
2209
2210 /* Sixth byte */
2211 *p = (flo >> 16) & 0xFF;
2212 p += incr;
2213
2214 /* Seventh byte */
2215 *p = (flo >> 8) & 0xFF;
2216 p += incr;
2217
2218 /* Eighth byte */
2219 *p = flo & 0xFF;
2220 p += incr;
2221
2222 /* Done */
2223 return 0;
2224
2225 Overflow:
2226 PyErr_SetString(PyExc_OverflowError,
2227 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002228 return -1;
2229 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230 else {
2231 const char *s = (char*)&x;
2232 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002233
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234 if ((double_format == ieee_little_endian_format && !le)
2235 || (double_format == ieee_big_endian_format && le)) {
2236 p += 7;
2237 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002238 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002239
2240 for (i = 0; i < 8; i++) {
2241 *p = *s++;
2242 p += incr;
2243 }
2244 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002245 }
Tim Peters9905b942003-03-20 20:53:32 +00002246}
2247
2248double
2249_PyFloat_Unpack4(const unsigned char *p, int le)
2250{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002251 if (float_format == unknown_format) {
2252 unsigned char sign;
2253 int e;
2254 unsigned int f;
2255 double x;
2256 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002257
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258 if (le) {
2259 p += 3;
2260 incr = -1;
2261 }
2262
2263 /* First byte */
2264 sign = (*p >> 7) & 1;
2265 e = (*p & 0x7F) << 1;
2266 p += incr;
2267
2268 /* Second byte */
2269 e |= (*p >> 7) & 1;
2270 f = (*p & 0x7F) << 16;
2271 p += incr;
2272
2273 if (e == 255) {
2274 PyErr_SetString(
2275 PyExc_ValueError,
2276 "can't unpack IEEE 754 special value "
2277 "on non-IEEE platform");
2278 return -1;
2279 }
2280
2281 /* Third byte */
2282 f |= *p << 8;
2283 p += incr;
2284
2285 /* Fourth byte */
2286 f |= *p;
2287
2288 x = (double)f / 8388608.0;
2289
2290 /* XXX This sadly ignores Inf/NaN issues */
2291 if (e == 0)
2292 e = -126;
2293 else {
2294 x += 1.0;
2295 e -= 127;
2296 }
2297 x = ldexp(x, e);
2298
2299 if (sign)
2300 x = -x;
2301
2302 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002303 }
Tim Peters9905b942003-03-20 20:53:32 +00002304 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002305 float x;
2306
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002307 if ((float_format == ieee_little_endian_format && !le)
2308 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002309 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310 char *d = &buf[3];
2311 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002312
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002313 for (i = 0; i < 4; i++) {
2314 *d-- = *p++;
2315 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002316 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317 }
2318 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002319 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002321
2322 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002323 }
Tim Peters9905b942003-03-20 20:53:32 +00002324}
2325
2326double
2327_PyFloat_Unpack8(const unsigned char *p, int le)
2328{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329 if (double_format == unknown_format) {
2330 unsigned char sign;
2331 int e;
2332 unsigned int fhi, flo;
2333 double x;
2334 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002335
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002336 if (le) {
2337 p += 7;
2338 incr = -1;
2339 }
2340
2341 /* First byte */
2342 sign = (*p >> 7) & 1;
2343 e = (*p & 0x7F) << 4;
2344
2345 p += incr;
2346
2347 /* Second byte */
2348 e |= (*p >> 4) & 0xF;
2349 fhi = (*p & 0xF) << 24;
2350 p += incr;
2351
2352 if (e == 2047) {
2353 PyErr_SetString(
2354 PyExc_ValueError,
2355 "can't unpack IEEE 754 special value "
2356 "on non-IEEE platform");
2357 return -1.0;
2358 }
2359
2360 /* Third byte */
2361 fhi |= *p << 16;
2362 p += incr;
2363
2364 /* Fourth byte */
2365 fhi |= *p << 8;
2366 p += incr;
2367
2368 /* Fifth byte */
2369 fhi |= *p;
2370 p += incr;
2371
2372 /* Sixth byte */
2373 flo = *p << 16;
2374 p += incr;
2375
2376 /* Seventh byte */
2377 flo |= *p << 8;
2378 p += incr;
2379
2380 /* Eighth byte */
2381 flo |= *p;
2382
2383 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2384 x /= 268435456.0; /* 2**28 */
2385
2386 if (e == 0)
2387 e = -1022;
2388 else {
2389 x += 1.0;
2390 e -= 1023;
2391 }
2392 x = ldexp(x, e);
2393
2394 if (sign)
2395 x = -x;
2396
2397 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002398 }
Tim Peters9905b942003-03-20 20:53:32 +00002399 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002400 double x;
2401
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002402 if ((double_format == ieee_little_endian_format && !le)
2403 || (double_format == ieee_big_endian_format && le)) {
2404 char buf[8];
2405 char *d = &buf[7];
2406 int i;
2407
2408 for (i = 0; i < 8; i++) {
2409 *d-- = *p++;
2410 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002411 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002412 }
2413 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002414 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002415 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002416
2417 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002418 }
Tim Peters9905b942003-03-20 20:53:32 +00002419}