blob: 2fbe810f15b0d3dfe704cea94428d00ce6d1cc65 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Christian Heimesbbe741d2008-03-28 10:53:29 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Guido van Rossum6923e131990-11-02 17:50:43 +000022
Christian Heimes969fe572008-01-25 11:23:10 +000023#ifdef _OSF_SOURCE
24/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
25extern int finite(double);
26#endif
27
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000029#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000030#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000031#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000032
Guido van Rossum3fce8831999-03-12 19:43:17 +000033struct _floatblock {
34 struct _floatblock *next;
35 PyFloatObject objects[N_FLOATOBJECTS];
36};
37
38typedef struct _floatblock PyFloatBlock;
39
40static PyFloatBlock *block_list = NULL;
41static PyFloatObject *free_list = NULL;
42
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000044fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045{
46 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
48 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000050 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000051 ((PyFloatBlock *)p)->next = block_list;
52 block_list = (PyFloatBlock *)p;
53 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 q = p + N_FLOATOBJECTS;
55 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000056 Py_TYPE(q) = (struct _typeobject *)(q-1);
57 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 return p + N_FLOATOBJECTS - 1;
59}
60
Christian Heimes93852662007-12-01 12:22:32 +000061double
62PyFloat_GetMax(void)
63{
64 return DBL_MAX;
65}
66
67double
68PyFloat_GetMin(void)
69{
70 return DBL_MIN;
71}
72
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073static PyTypeObject FloatInfoType;
74
75PyDoc_STRVAR(floatinfo__doc__,
76"sys.floatinfo\n\
77\n\
78A structseq holding information about the float type. It contains low level\n\
79information about the precision and internal representation. Please study\n\
80your system's :file:`float.h` for more information.");
81
82static PyStructSequence_Field floatinfo_fields[] = {
83 {"max", "DBL_MAX -- maximum representable finite float"},
84 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
85 "is representable"},
86 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
87 "is representable"},
88 {"min", "DBL_MIN -- Minimum positive normalizer float"},
89 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
90 "is a normalized float"},
91 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
92 "a normalized"},
93 {"dig", "DBL_DIG -- digits"},
94 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
95 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
96 "representable float"},
97 {"radix", "FLT_RADIX -- radix of exponent"},
98 {"rounds", "FLT_ROUNDS -- addition rounds"},
99 {0}
100};
101
102static PyStructSequence_Desc floatinfo_desc = {
103 "sys.floatinfo", /* name */
104 floatinfo__doc__, /* doc */
105 floatinfo_fields, /* fields */
106 11
107};
108
Christian Heimes93852662007-12-01 12:22:32 +0000109PyObject *
110PyFloat_GetInfo(void)
111{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000112 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000113 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000114
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000115 floatinfo = PyStructSequence_New(&FloatInfoType);
116 if (floatinfo == NULL) {
117 return NULL;
118 }
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120#define SetIntFlag(flag) \
121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
122#define SetDblFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125 SetDblFlag(DBL_MAX);
126 SetIntFlag(DBL_MAX_EXP);
127 SetIntFlag(DBL_MAX_10_EXP);
128 SetDblFlag(DBL_MIN);
129 SetIntFlag(DBL_MIN_EXP);
130 SetIntFlag(DBL_MIN_10_EXP);
131 SetIntFlag(DBL_DIG);
132 SetIntFlag(DBL_MANT_DIG);
133 SetDblFlag(DBL_EPSILON);
134 SetIntFlag(FLT_RADIX);
135 SetIntFlag(FLT_ROUNDS);
136#undef SetIntFlag
137#undef SetDblFlag
138
139 if (PyErr_Occurred()) {
140 Py_CLEAR(floatinfo);
141 return NULL;
142 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000143 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000144}
145
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000154 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000155 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000163PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164{
Christian Heimes99170a52007-12-19 02:07:34 +0000165 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000167 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000172 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000178 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000180 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000181 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000183 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000186 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000189
Guido van Rossum4c08d552000-03-10 22:55:18 +0000190 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191 while (*s && isspace(Py_CHARMASK(*s)))
192 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000193 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000194 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000195 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 }
Christian Heimes99170a52007-12-19 02:07:34 +0000197 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000198 /* We don't care about overflow or underflow. If the platform supports
199 * them, infinities and signed zeroes (on underflow) are fine.
Eric Smith0923d1d2009-04-16 20:16:10 +0000200 * However, strtod can return 0 for denormalized numbers. Note that
Tim Petersef14d732000-09-23 03:39:17 +0000201 * whether strtod sets errno on underflow is not defined, so we can't
202 * key off errno.
203 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000204 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000205 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000206 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000207 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000209 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210 if (end > last)
211 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000212 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000213 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000214 char *p = (char*)sp;
215 int sign = 1;
216
217 if (*p == '-') {
218 sign = -1;
219 p++;
220 }
221 if (*p == '+') {
222 p++;
223 }
224 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000225 if (s_buffer != NULL)
226 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000227 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000228 }
Georg Brandl2ee470f2008-07-16 12:55:28 +0000229 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000230 if (s_buffer != NULL)
231 PyMem_FREE(s_buffer);
Georg Brandl2ee470f2008-07-16 12:55:28 +0000232 Py_RETURN_INF(sign);
233 }
Christian Heimes99170a52007-12-19 02:07:34 +0000234#ifdef Py_NAN
235 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Mark Dickinson943f3392008-07-21 22:49:36 +0000236 if (s_buffer != NULL)
237 PyMem_FREE(s_buffer);
Christian Heimes53876d92008-04-19 00:31:39 +0000238 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000239 }
240#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000241 PyOS_snprintf(buffer, sizeof(buffer),
242 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000243 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000244 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000245 }
246 /* Since end != s, the platform made *some* kind of sense out
247 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000248 while (*end && isspace(Py_CHARMASK(*end)))
249 end++;
250 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000251 PyOS_snprintf(buffer, sizeof(buffer),
252 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000253 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000254 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000255 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000256 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000257 PyErr_SetString(PyExc_ValueError,
258 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000259 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000261 result = PyFloat_FromDouble(x);
262 error:
263 if (s_buffer)
264 PyMem_FREE(s_buffer);
265 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266}
267
Guido van Rossum234f9421993-06-17 12:35:49 +0000268static void
Fred Drakefd99de62000-07-09 05:02:18 +0000269float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000270{
Guido van Rossum9475a232001-10-05 20:51:39 +0000271 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000272 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000273 free_list = op;
274 }
275 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000276 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000277}
278
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279double
Fred Drakefd99de62000-07-09 05:02:18 +0000280PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 PyNumberMethods *nb;
283 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000286 if (op && PyFloat_Check(op))
287 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000289 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 return -1;
292 }
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Christian Heimes90aa7642007-12-19 02:45:37 +0000294 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000295 PyErr_SetString(PyExc_TypeError, "a float is required");
296 return -1;
297 }
298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300 if (fo == NULL)
301 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 if (!PyFloat_Check(fo)) {
303 PyErr_SetString(PyExc_TypeError,
304 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 return -1;
306 }
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 val = PyFloat_AS_DOUBLE(fo);
309 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312}
313
Neil Schemenauer32117e52001-01-04 01:44:34 +0000314/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000315 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000316 set to NULL, and the function invoking this macro returns NULL. If
317 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
318 stored in obj, and returned from the function invoking this macro.
319*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000320#define CONVERT_TO_DOUBLE(obj, dbl) \
321 if (PyFloat_Check(obj)) \
322 dbl = PyFloat_AS_DOUBLE(obj); \
323 else if (convert_to_double(&(obj), &(dbl)) < 0) \
324 return obj;
325
Eric Smith0923d1d2009-04-16 20:16:10 +0000326/* Methods */
327
Neil Schemenauer32117e52001-01-04 01:44:34 +0000328static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000329convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000330{
331 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000332
Guido van Rossumddefaf32007-01-14 03:31:43 +0000333 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000334 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000335 if (*dbl == -1.0 && PyErr_Occurred()) {
336 *v = NULL;
337 return -1;
338 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000339 }
340 else {
341 Py_INCREF(Py_NotImplemented);
342 *v = Py_NotImplemented;
343 return -1;
344 }
345 return 0;
346}
347
Eric Smith0923d1d2009-04-16 20:16:10 +0000348static PyObject *
349float_str_or_repr(PyFloatObject *v, char format_code)
350{
351 PyObject *result;
352 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
353 format_code, 0, Py_DTSF_ADD_DOT_0,
354 NULL);
355 if (!buf)
356 return PyErr_NoMemory();
357 result = PyUnicode_FromString(buf);
358 PyMem_Free(buf);
359 return result;
360}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000361
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000362static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000363float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364{
Eric Smith0923d1d2009-04-16 20:16:10 +0000365 return float_str_or_repr(v, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000366}
367
368static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000369float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000370{
Eric Smith0923d1d2009-04-16 20:16:10 +0000371 return float_str_or_repr(v, 's');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372}
373
Tim Peters307fa782004-09-23 08:06:40 +0000374/* Comparison is pretty much a nightmare. When comparing float to float,
375 * we do it as straightforwardly (and long-windedly) as conceivable, so
376 * that, e.g., Python x == y delivers the same result as the platform
377 * C x == y when x and/or y is a NaN.
378 * When mixing float with an integer type, there's no good *uniform* approach.
379 * Converting the double to an integer obviously doesn't work, since we
380 * may lose info from fractional bits. Converting the integer to a double
381 * also has two failure modes: (1) a long int may trigger overflow (too
382 * large to fit in the dynamic range of a C double); (2) even a C long may have
383 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
384 * 63 bits of precision, but a C double probably has only 53), and then
385 * we can falsely claim equality when low-order integer bits are lost by
386 * coercion to double. So this part is painful too.
387 */
388
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000389static PyObject*
390float_richcompare(PyObject *v, PyObject *w, int op)
391{
392 double i, j;
393 int r = 0;
394
Tim Peters307fa782004-09-23 08:06:40 +0000395 assert(PyFloat_Check(v));
396 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000397
Tim Peters307fa782004-09-23 08:06:40 +0000398 /* Switch on the type of w. Set i and j to doubles to be compared,
399 * and op to the richcomp to use.
400 */
401 if (PyFloat_Check(w))
402 j = PyFloat_AS_DOUBLE(w);
403
Thomas Wouters477c8d52006-05-27 19:21:47 +0000404 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000405 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000406 /* If i is an infinity, its magnitude exceeds any
407 * finite integer, so it doesn't matter which int we
408 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000409 */
410 j = 0.0;
411 else
412 goto Unimplemented;
413 }
414
Tim Peters307fa782004-09-23 08:06:40 +0000415 else if (PyLong_Check(w)) {
416 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
417 int wsign = _PyLong_Sign(w);
418 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000419 int exponent;
420
421 if (vsign != wsign) {
422 /* Magnitudes are irrelevant -- the signs alone
423 * determine the outcome.
424 */
425 i = (double)vsign;
426 j = (double)wsign;
427 goto Compare;
428 }
429 /* The signs are the same. */
430 /* Convert w to a double if it fits. In particular, 0 fits. */
431 nbits = _PyLong_NumBits(w);
432 if (nbits == (size_t)-1 && PyErr_Occurred()) {
433 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000434 * to hold the # of bits. Replace with little doubles
435 * that give the same outcome -- w is so large that
436 * its magnitude must exceed the magnitude of any
437 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000438 */
439 PyErr_Clear();
440 i = (double)vsign;
441 assert(wsign != 0);
442 j = wsign * 2.0;
443 goto Compare;
444 }
445 if (nbits <= 48) {
446 j = PyLong_AsDouble(w);
447 /* It's impossible that <= 48 bits overflowed. */
448 assert(j != -1.0 || ! PyErr_Occurred());
449 goto Compare;
450 }
451 assert(wsign != 0); /* else nbits was 0 */
452 assert(vsign != 0); /* if vsign were 0, then since wsign is
453 * not 0, we would have taken the
454 * vsign != wsign branch at the start */
455 /* We want to work with non-negative numbers. */
456 if (vsign < 0) {
457 /* "Multiply both sides" by -1; this also swaps the
458 * comparator.
459 */
460 i = -i;
461 op = _Py_SwappedOp[op];
462 }
463 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000464 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000465 /* exponent is the # of bits in v before the radix point;
466 * we know that nbits (the # of bits in w) > 48 at this point
467 */
468 if (exponent < 0 || (size_t)exponent < nbits) {
469 i = 1.0;
470 j = 2.0;
471 goto Compare;
472 }
473 if ((size_t)exponent > nbits) {
474 i = 2.0;
475 j = 1.0;
476 goto Compare;
477 }
478 /* v and w have the same number of bits before the radix
479 * point. Construct two longs that have the same comparison
480 * outcome.
481 */
482 {
483 double fracpart;
484 double intpart;
485 PyObject *result = NULL;
486 PyObject *one = NULL;
487 PyObject *vv = NULL;
488 PyObject *ww = w;
489
490 if (wsign < 0) {
491 ww = PyNumber_Negative(w);
492 if (ww == NULL)
493 goto Error;
494 }
495 else
496 Py_INCREF(ww);
497
498 fracpart = modf(i, &intpart);
499 vv = PyLong_FromDouble(intpart);
500 if (vv == NULL)
501 goto Error;
502
503 if (fracpart != 0.0) {
504 /* Shift left, and or a 1 bit into vv
505 * to represent the lost fraction.
506 */
507 PyObject *temp;
508
Christian Heimes217cfd12007-12-02 14:31:20 +0000509 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000510 if (one == NULL)
511 goto Error;
512
513 temp = PyNumber_Lshift(ww, one);
514 if (temp == NULL)
515 goto Error;
516 Py_DECREF(ww);
517 ww = temp;
518
519 temp = PyNumber_Lshift(vv, one);
520 if (temp == NULL)
521 goto Error;
522 Py_DECREF(vv);
523 vv = temp;
524
525 temp = PyNumber_Or(vv, one);
526 if (temp == NULL)
527 goto Error;
528 Py_DECREF(vv);
529 vv = temp;
530 }
531
532 r = PyObject_RichCompareBool(vv, ww, op);
533 if (r < 0)
534 goto Error;
535 result = PyBool_FromLong(r);
536 Error:
537 Py_XDECREF(vv);
538 Py_XDECREF(ww);
539 Py_XDECREF(one);
540 return result;
541 }
542 } /* else if (PyLong_Check(w)) */
543
544 else /* w isn't float, int, or long */
545 goto Unimplemented;
546
547 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000548 PyFPE_START_PROTECT("richcompare", return NULL)
549 switch (op) {
550 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000551 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000552 break;
553 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000554 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000555 break;
556 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000557 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000558 break;
559 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000560 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000561 break;
562 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000563 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000564 break;
565 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000566 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000567 break;
568 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000569 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000570 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000571
572 Unimplemented:
573 Py_INCREF(Py_NotImplemented);
574 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000575}
576
Guido van Rossum9bfef441993-03-29 10:43:31 +0000577static long
Fred Drakefd99de62000-07-09 05:02:18 +0000578float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000579{
Tim Peters39dce292000-08-15 03:34:48 +0000580 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000586 double a,b;
587 CONVERT_TO_DOUBLE(v, a);
588 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000589 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590 a = a + b;
591 PyFPE_END_PROTECT(a)
592 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593}
594
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000595static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000596float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000598 double a,b;
599 CONVERT_TO_DOUBLE(v, a);
600 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000601 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000602 a = a - b;
603 PyFPE_END_PROTECT(a)
604 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605}
606
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000608float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000610 double a,b;
611 CONVERT_TO_DOUBLE(v, a);
612 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000613 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000614 a = a * b;
615 PyFPE_END_PROTECT(a)
616 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000622 double a,b;
623 CONVERT_TO_DOUBLE(v, a);
624 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000625#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000626 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000627 PyErr_SetString(PyExc_ZeroDivisionError,
628 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629 return NULL;
630 }
Christian Heimes53876d92008-04-19 00:31:39 +0000631#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000632 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000633 a = a / b;
634 PyFPE_END_PROTECT(a)
635 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636}
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000639float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000641 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000642 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000643 CONVERT_TO_DOUBLE(v, vx);
644 CONVERT_TO_DOUBLE(w, wx);
645#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000647 PyErr_SetString(PyExc_ZeroDivisionError,
648 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649 return NULL;
650 }
Christian Heimes53876d92008-04-19 00:31:39 +0000651#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000652 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000653 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000654 /* note: checking mod*wx < 0 is incorrect -- underflows to
655 0 if wx < sqrt(smallest nonzero double) */
656 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000657 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000658 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000659 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661}
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000664float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000665{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000666 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000667 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000668 CONVERT_TO_DOUBLE(v, vx);
669 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000670 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000672 return NULL;
673 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000674 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000675 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000676 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000677 exact multiple of wx. But this is fp arithmetic, and fp
678 vx - mod is an approximation; the result is that div may
679 not be an exact integral value after the division, although
680 it will always be very close to one.
681 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000682 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000683 if (mod) {
684 /* ensure the remainder has the same sign as the denominator */
685 if ((wx < 0) != (mod < 0)) {
686 mod += wx;
687 div -= 1.0;
688 }
689 }
690 else {
691 /* the remainder is zero, and in the presence of signed zeroes
692 fmod returns different results across platforms; ensure
693 it has the same sign as the denominator; we'd like to do
694 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000695 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000696 if (wx < 0.0)
697 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000698 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000699 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000700 if (div) {
701 floordiv = floor(div);
702 if (div - floordiv > 0.5)
703 floordiv += 1.0;
704 }
705 else {
706 /* div is zero - get the same sign as the true quotient */
707 div *= div; /* hide "div = +0" from optimizers */
708 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
709 }
710 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000711 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000712}
713
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000715float_floor_div(PyObject *v, PyObject *w)
716{
717 PyObject *t, *r;
718
719 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000720 if (t == NULL || t == Py_NotImplemented)
721 return t;
722 assert(PyTuple_CheckExact(t));
723 r = PyTuple_GET_ITEM(t, 0);
724 Py_INCREF(r);
725 Py_DECREF(t);
726 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000727}
728
729static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000730float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731{
732 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000733
734 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000735 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000736 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000737 return NULL;
738 }
739
Neil Schemenauer32117e52001-01-04 01:44:34 +0000740 CONVERT_TO_DOUBLE(v, iv);
741 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000742
743 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000744 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000745 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000746 }
Tim Peters96685bf2001-08-23 22:31:37 +0000747 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000748 if (iw < 0.0) {
749 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000750 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000751 return NULL;
752 }
753 return PyFloat_FromDouble(0.0);
754 }
Christian Heimes53876d92008-04-19 00:31:39 +0000755 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
756 return PyFloat_FromDouble(1.0);
757 }
Tim Peterse87568d2003-05-24 20:18:24 +0000758 if (iv < 0.0) {
759 /* Whether this is an error is a mess, and bumps into libm
760 * bugs so we have to figure it out ourselves.
761 */
762 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000763 /* Negative numbers raised to fractional powers
764 * become complex.
765 */
766 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000767 }
768 /* iw is an exact integer, albeit perhaps a very large one.
769 * -1 raised to an exact integer should never be exceptional.
770 * Alas, some libms (chiefly glibc as of early 2003) return
771 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
772 * happen to be representable in a *C* integer. That's a
773 * bug; we let that slide in math.pow() (which currently
774 * reflects all platform accidents), but not for Python's **.
775 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000777 /* Return 1 if iw is even, -1 if iw is odd; there's
778 * no guarantee that any C integral type is big
779 * enough to hold iw, so we have to check this
780 * indirectly.
781 */
782 ix = floor(iw * 0.5) * 2.0;
783 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
784 }
785 /* Else iv != -1.0, and overflow or underflow are possible.
786 * Unless we're to write pow() ourselves, we have to trust
787 * the platform to do this correctly.
788 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000789 }
Tim Peters96685bf2001-08-23 22:31:37 +0000790 errno = 0;
791 PyFPE_START_PROTECT("pow", return NULL)
792 ix = pow(iv, iw);
793 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000794 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000795 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000796 /* We don't expect any errno value other than ERANGE, but
797 * the range of libm bugs appears unbounded.
798 */
799 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
800 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000802 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804}
805
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000807float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810}
811
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000813float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000814{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000815 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816}
817
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000818static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000819float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000820{
821 return v->ob_fval != 0.0;
822}
823
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000825float_is_integer(PyObject *v)
826{
827 double x = PyFloat_AsDouble(v);
828 PyObject *o;
829
830 if (x == -1.0 && PyErr_Occurred())
831 return NULL;
832 if (!Py_IS_FINITE(x))
833 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000834 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000835 PyFPE_START_PROTECT("is_integer", return NULL)
836 o = (floor(x) == x) ? Py_True : Py_False;
837 PyFPE_END_PROTECT(x)
838 if (errno != 0) {
839 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
840 PyExc_ValueError);
841 return NULL;
842 }
843 Py_INCREF(o);
844 return o;
845}
846
847#if 0
848static PyObject *
849float_is_inf(PyObject *v)
850{
851 double x = PyFloat_AsDouble(v);
852 if (x == -1.0 && PyErr_Occurred())
853 return NULL;
854 return PyBool_FromLong((long)Py_IS_INFINITY(x));
855}
856
857static PyObject *
858float_is_nan(PyObject *v)
859{
860 double x = PyFloat_AsDouble(v);
861 if (x == -1.0 && PyErr_Occurred())
862 return NULL;
863 return PyBool_FromLong((long)Py_IS_NAN(x));
864}
865
866static PyObject *
867float_is_finite(PyObject *v)
868{
869 double x = PyFloat_AsDouble(v);
870 if (x == -1.0 && PyErr_Occurred())
871 return NULL;
872 return PyBool_FromLong((long)Py_IS_FINITE(x));
873}
874#endif
875
876static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000877float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000878{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000880 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000881
882 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000883 /* Try to get out cheap if this fits in a Python int. The attempt
884 * to cast to long must be protected, as C doesn't define what
885 * happens if the double is too big to fit in a long. Some rare
886 * systems raise an exception then (RISCOS was mentioned as one,
887 * and someone using a non-default option on Sun also bumped into
888 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
889 * still be vulnerable: if a long has more bits of precision than
890 * a double, casting MIN/MAX to double may yield an approximation,
891 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
892 * yield true from the C expression wholepart<=LONG_MAX, despite
893 * that wholepart is actually greater than LONG_MAX.
894 */
895 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
896 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000897 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000898 }
899 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000900}
901
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000902static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000903float_round(PyObject *v, PyObject *args)
904{
905#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
906 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000907 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000908 double flr, cil;
909 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000910 int ndigits = UNDEF_NDIGITS;
911
912 if (!PyArg_ParseTuple(args, "|i", &ndigits))
913 return NULL;
914
915 x = PyFloat_AsDouble(v);
916
917 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000918 f = pow(10.0, ndigits);
919 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000920 }
921
922 flr = floor(x);
923 cil = ceil(x);
924
925 if (x-flr > 0.5)
926 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000927 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000928 rounded = fmod(flr, 2) == 0 ? flr : cil;
929 else
930 rounded = flr;
931
932 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000933 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000934 return PyFloat_FromDouble(rounded);
935 }
936
937 return PyLong_FromDouble(rounded);
938#undef UNDEF_NDIGITS
939}
940
941static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000942float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000943{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000944 if (PyFloat_CheckExact(v))
945 Py_INCREF(v);
946 else
947 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000948 return v;
949}
950
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000951/* turn ASCII hex characters into integer values and vice versa */
952
953static char
954char_from_hex(int x)
955{
956 assert(0 <= x && x < 16);
957 return "0123456789abcdef"[x];
958}
959
960static int
961hex_from_char(char c) {
962 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000963 switch(c) {
964 case '0':
965 x = 0;
966 break;
967 case '1':
968 x = 1;
969 break;
970 case '2':
971 x = 2;
972 break;
973 case '3':
974 x = 3;
975 break;
976 case '4':
977 x = 4;
978 break;
979 case '5':
980 x = 5;
981 break;
982 case '6':
983 x = 6;
984 break;
985 case '7':
986 x = 7;
987 break;
988 case '8':
989 x = 8;
990 break;
991 case '9':
992 x = 9;
993 break;
994 case 'a':
995 case 'A':
996 x = 10;
997 break;
998 case 'b':
999 case 'B':
1000 x = 11;
1001 break;
1002 case 'c':
1003 case 'C':
1004 x = 12;
1005 break;
1006 case 'd':
1007 case 'D':
1008 x = 13;
1009 break;
1010 case 'e':
1011 case 'E':
1012 x = 14;
1013 break;
1014 case 'f':
1015 case 'F':
1016 x = 15;
1017 break;
1018 default:
1019 x = -1;
1020 break;
1021 }
1022 return x;
1023}
1024
1025/* convert a float to a hexadecimal string */
1026
1027/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1028 of the form 4k+1. */
1029#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1030
1031static PyObject *
1032float_hex(PyObject *v)
1033{
1034 double x, m;
1035 int e, shift, i, si, esign;
1036 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1037 trailing NUL byte. */
1038 char s[(TOHEX_NBITS-1)/4+3];
1039
1040 CONVERT_TO_DOUBLE(v, x);
1041
1042 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1043 return float_str((PyFloatObject *)v);
1044
1045 if (x == 0.0) {
1046 if(copysign(1.0, x) == -1.0)
1047 return PyUnicode_FromString("-0x0.0p+0");
1048 else
1049 return PyUnicode_FromString("0x0.0p+0");
1050 }
1051
1052 m = frexp(fabs(x), &e);
1053 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1054 m = ldexp(m, shift);
1055 e -= shift;
1056
1057 si = 0;
1058 s[si] = char_from_hex((int)m);
1059 si++;
1060 m -= (int)m;
1061 s[si] = '.';
1062 si++;
1063 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1064 m *= 16.0;
1065 s[si] = char_from_hex((int)m);
1066 si++;
1067 m -= (int)m;
1068 }
1069 s[si] = '\0';
1070
1071 if (e < 0) {
1072 esign = (int)'-';
1073 e = -e;
1074 }
1075 else
1076 esign = (int)'+';
1077
1078 if (x < 0.0)
1079 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1080 else
1081 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1082}
1083
1084PyDoc_STRVAR(float_hex_doc,
1085"float.hex() -> string\n\
1086\n\
1087Return a hexadecimal representation of a floating-point number.\n\
1088>>> (-0.1).hex()\n\
1089'-0x1.999999999999ap-4'\n\
1090>>> 3.14159.hex()\n\
1091'0x1.921f9f01b866ep+1'");
1092
1093/* Convert a hexadecimal string to a float. */
1094
1095static PyObject *
1096float_fromhex(PyObject *cls, PyObject *arg)
1097{
1098 PyObject *result_as_float, *result;
1099 double x;
1100 long exp, top_exp, lsb, key_digit;
1101 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1102 int half_eps, digit, round_up, sign=1;
1103 Py_ssize_t length, ndigits, fdigits, i;
1104
1105 /*
1106 * For the sake of simplicity and correctness, we impose an artificial
1107 * limit on ndigits, the total number of hex digits in the coefficient
1108 * The limit is chosen to ensure that, writing exp for the exponent,
1109 *
1110 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1111 * guaranteed to overflow (provided it's nonzero)
1112 *
1113 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1114 * guaranteed to underflow to 0.
1115 *
1116 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1117 * overflow in the calculation of exp and top_exp below.
1118 *
1119 * More specifically, ndigits is assumed to satisfy the following
1120 * inequalities:
1121 *
1122 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1123 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1124 *
1125 * If either of these inequalities is not satisfied, a ValueError is
1126 * raised. Otherwise, write x for the value of the hex string, and
1127 * assume x is nonzero. Then
1128 *
1129 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1130 *
1131 * Now if exp > LONG_MAX/2 then:
1132 *
1133 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1134 * = DBL_MAX_EXP
1135 *
1136 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1137 * double, so overflows. If exp < LONG_MIN/2, then
1138 *
1139 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1140 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1141 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1142 *
1143 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1144 * when converted to a C double.
1145 *
1146 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1147 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1148 */
1149
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001150 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001151 if (s == NULL)
1152 return NULL;
1153 s_end = s + length;
1154
1155 /********************
1156 * Parse the string *
1157 ********************/
1158
1159 /* leading whitespace and optional sign */
Kristján Valur Jónssonbaa45462008-12-18 17:08:57 +00001160 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001161 s++;
1162 if (*s == '-') {
1163 s++;
1164 sign = -1;
1165 }
1166 else if (*s == '+')
1167 s++;
1168
1169 /* infinities and nans */
Andrew MacIntyre45612572008-09-22 14:49:01 +00001170 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001171 x = Py_NAN;
1172 goto finished;
1173 }
Andrew MacIntyre45612572008-09-22 14:49:01 +00001174 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1175 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001176 x = sign*Py_HUGE_VAL;
1177 goto finished;
1178 }
1179
1180 /* [0x] */
1181 s_store = s;
1182 if (*s == '0') {
1183 s++;
1184 if (tolower(*s) == (int)'x')
1185 s++;
1186 else
1187 s = s_store;
1188 }
1189
1190 /* coefficient: <integer> [. <fraction>] */
1191 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001192 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001193 s++;
1194 s_store = s;
1195 if (*s == '.') {
1196 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001197 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001198 s++;
1199 coeff_end = s-1;
1200 }
1201 else
1202 coeff_end = s;
1203
1204 /* ndigits = total # of hex digits; fdigits = # after point */
1205 ndigits = coeff_end - coeff_start;
1206 fdigits = coeff_end - s_store;
1207 if (ndigits == 0)
1208 goto parse_error;
1209 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1210 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1211 goto insane_length_error;
1212
1213 /* [p <exponent>] */
1214 if (tolower(*s) == (int)'p') {
1215 s++;
1216 exp_start = s;
1217 if (*s == '-' || *s == '+')
1218 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001219 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001220 goto parse_error;
1221 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001222 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001223 s++;
1224 exp = strtol(exp_start, NULL, 10);
1225 }
1226 else
1227 exp = 0;
1228
1229 /* optional trailing whitespace leading to the end of the string */
Kristján Valur Jónssonbaa45462008-12-18 17:08:57 +00001230 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001231 s++;
1232 if (s != s_end)
1233 goto parse_error;
1234
1235/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1236#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1237 coeff_end-(j) : \
1238 coeff_end-1-(j)))
1239
1240 /*******************************************
1241 * Compute rounded value of the hex string *
1242 *******************************************/
1243
1244 /* Discard leading zeros, and catch extreme overflow and underflow */
1245 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1246 ndigits--;
1247 if (ndigits == 0 || exp < LONG_MIN/2) {
1248 x = sign * 0.0;
1249 goto finished;
1250 }
1251 if (exp > LONG_MAX/2)
1252 goto overflow_error;
1253
1254 /* Adjust exponent for fractional part. */
1255 exp = exp - 4*((long)fdigits);
1256
1257 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1258 top_exp = exp + 4*((long)ndigits - 1);
1259 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1260 top_exp++;
1261
1262 /* catch almost all nonextreme cases of overflow and underflow here */
1263 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1264 x = sign * 0.0;
1265 goto finished;
1266 }
1267 if (top_exp > DBL_MAX_EXP)
1268 goto overflow_error;
1269
1270 /* lsb = exponent of least significant bit of the *rounded* value.
1271 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1272 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1273
1274 x = 0.0;
1275 if (exp >= lsb) {
1276 /* no rounding required */
1277 for (i = ndigits-1; i >= 0; i--)
1278 x = 16.0*x + HEX_DIGIT(i);
1279 x = sign * ldexp(x, (int)(exp));
1280 goto finished;
1281 }
1282 /* rounding required. key_digit is the index of the hex digit
1283 containing the first bit to be rounded away. */
1284 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1285 key_digit = (lsb - exp - 1) / 4;
1286 for (i = ndigits-1; i > key_digit; i--)
1287 x = 16.0*x + HEX_DIGIT(i);
1288 digit = HEX_DIGIT(key_digit);
1289 x = 16.0*x + (double)(digit & (16-2*half_eps));
1290
1291 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1292 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1293 if ((digit & half_eps) != 0) {
1294 round_up = 0;
1295 if ((digit & (3*half_eps-1)) != 0 ||
1296 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1297 round_up = 1;
1298 else
1299 for (i = key_digit-1; i >= 0; i--)
1300 if (HEX_DIGIT(i) != 0) {
1301 round_up = 1;
1302 break;
1303 }
1304 if (round_up == 1) {
1305 x += 2*half_eps;
1306 if (top_exp == DBL_MAX_EXP &&
1307 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1308 /* overflow corner case: pre-rounded value <
1309 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1310 goto overflow_error;
1311 }
1312 }
1313 x = sign * ldexp(x, (int)(exp+4*key_digit));
1314
1315 finished:
1316 result_as_float = Py_BuildValue("(d)", x);
1317 if (result_as_float == NULL)
1318 return NULL;
1319 result = PyObject_CallObject(cls, result_as_float);
1320 Py_DECREF(result_as_float);
1321 return result;
1322
1323 overflow_error:
1324 PyErr_SetString(PyExc_OverflowError,
1325 "hexadecimal value too large to represent as a float");
1326 return NULL;
1327
1328 parse_error:
1329 PyErr_SetString(PyExc_ValueError,
1330 "invalid hexadecimal floating-point string");
1331 return NULL;
1332
1333 insane_length_error:
1334 PyErr_SetString(PyExc_ValueError,
1335 "hexadecimal string too long to convert");
1336 return NULL;
1337}
1338
1339PyDoc_STRVAR(float_fromhex_doc,
1340"float.fromhex(string) -> float\n\
1341\n\
1342Create a floating-point number from a hexadecimal string.\n\
1343>>> float.fromhex('0x1.ffffp10')\n\
13442047.984375\n\
1345>>> float.fromhex('-0x1p-1074')\n\
1346-4.9406564584124654e-324");
1347
1348
Christian Heimes26855632008-01-27 23:50:43 +00001349static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001350float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001351{
1352 double self;
1353 double float_part;
1354 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001355 int i;
1356
Christian Heimes26855632008-01-27 23:50:43 +00001357 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001358 PyObject *py_exponent = NULL;
1359 PyObject *numerator = NULL;
1360 PyObject *denominator = NULL;
1361 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001362 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001363
1364#define INPLACE_UPDATE(obj, call) \
1365 prev = obj; \
1366 obj = call; \
1367 Py_DECREF(prev); \
1368
1369 CONVERT_TO_DOUBLE(v, self);
1370
1371 if (Py_IS_INFINITY(self)) {
1372 PyErr_SetString(PyExc_OverflowError,
1373 "Cannot pass infinity to float.as_integer_ratio.");
1374 return NULL;
1375 }
1376#ifdef Py_NAN
1377 if (Py_IS_NAN(self)) {
1378 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001379 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001380 return NULL;
1381 }
1382#endif
1383
Christian Heimes26855632008-01-27 23:50:43 +00001384 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001385 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001386 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001387
1388 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1389 float_part *= 2.0;
1390 exponent--;
1391 }
1392 /* self == float_part * 2**exponent exactly and float_part is integral.
1393 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1394 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001395
Christian Heimes292d3512008-02-03 16:51:08 +00001396 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001397 if (numerator == NULL) goto error;
1398
Christian Heimes292d3512008-02-03 16:51:08 +00001399 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001400 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001401 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001402 if (py_exponent == NULL) goto error;
1403 INPLACE_UPDATE(py_exponent,
1404 long_methods->nb_lshift(denominator, py_exponent));
1405 if (py_exponent == NULL) goto error;
1406 if (exponent > 0) {
1407 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001408 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001409 if (numerator == NULL) goto error;
1410 }
1411 else {
1412 Py_DECREF(denominator);
1413 denominator = py_exponent;
1414 py_exponent = NULL;
1415 }
1416
1417 result_pair = PyTuple_Pack(2, numerator, denominator);
1418
1419#undef INPLACE_UPDATE
1420error:
1421 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001422 Py_XDECREF(denominator);
1423 Py_XDECREF(numerator);
1424 return result_pair;
1425}
1426
1427PyDoc_STRVAR(float_as_integer_ratio_doc,
1428"float.as_integer_ratio() -> (int, int)\n"
1429"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001430"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1431"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001432"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001433"\n"
1434">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001435"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001436">>> (0.0).as_integer_ratio()\n"
1437"(0, 1)\n"
1438">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001439"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001440
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001441
Jeremy Hylton938ace62002-07-17 16:30:39 +00001442static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001443float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1444
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445static PyObject *
1446float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1447{
1448 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001449 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450
Guido van Rossumbef14172001-08-29 15:47:46 +00001451 if (type != &PyFloat_Type)
1452 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1454 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001455 /* If it's a string, but not a string subclass, use
1456 PyFloat_FromString. */
1457 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001458 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459 return PyNumber_Float(x);
1460}
1461
Guido van Rossumbef14172001-08-29 15:47:46 +00001462/* Wimpy, slow approach to tp_new calls for subtypes of float:
1463 first create a regular float from whatever arguments we got,
1464 then allocate a subtype instance and initialize its ob_fval
1465 from the regular float. The regular float is then thrown away.
1466*/
1467static PyObject *
1468float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1469{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001470 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001471
1472 assert(PyType_IsSubtype(type, &PyFloat_Type));
1473 tmp = float_new(&PyFloat_Type, args, kwds);
1474 if (tmp == NULL)
1475 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001476 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001477 newobj = type->tp_alloc(type, 0);
1478 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001479 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001480 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001481 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001482 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001483 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001484 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001485}
1486
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001487static PyObject *
1488float_getnewargs(PyFloatObject *v)
1489{
1490 return Py_BuildValue("(d)", v->ob_fval);
1491}
1492
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001493/* this is for the benefit of the pack/unpack routines below */
1494
1495typedef enum {
1496 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1497} float_format_type;
1498
1499static float_format_type double_format, float_format;
1500static float_format_type detected_double_format, detected_float_format;
1501
1502static PyObject *
1503float_getformat(PyTypeObject *v, PyObject* arg)
1504{
1505 char* s;
1506 float_format_type r;
1507
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001508 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001509 PyErr_Format(PyExc_TypeError,
1510 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001511 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001512 return NULL;
1513 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001514 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001515 if (s == NULL)
1516 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001517 if (strcmp(s, "double") == 0) {
1518 r = double_format;
1519 }
1520 else if (strcmp(s, "float") == 0) {
1521 r = float_format;
1522 }
1523 else {
1524 PyErr_SetString(PyExc_ValueError,
1525 "__getformat__() argument 1 must be "
1526 "'double' or 'float'");
1527 return NULL;
1528 }
1529
1530 switch (r) {
1531 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001532 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001533 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001534 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001535 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001536 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001537 default:
1538 Py_FatalError("insane float_format or double_format");
1539 return NULL;
1540 }
1541}
1542
1543PyDoc_STRVAR(float_getformat_doc,
1544"float.__getformat__(typestr) -> string\n"
1545"\n"
1546"You probably don't want to use this function. It exists mainly to be\n"
1547"used in Python's test suite.\n"
1548"\n"
1549"typestr must be 'double' or 'float'. This function returns whichever of\n"
1550"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1551"format of floating point numbers used by the C type named by typestr.");
1552
1553static PyObject *
1554float_setformat(PyTypeObject *v, PyObject* args)
1555{
1556 char* typestr;
1557 char* format;
1558 float_format_type f;
1559 float_format_type detected;
1560 float_format_type *p;
1561
1562 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1563 return NULL;
1564
1565 if (strcmp(typestr, "double") == 0) {
1566 p = &double_format;
1567 detected = detected_double_format;
1568 }
1569 else if (strcmp(typestr, "float") == 0) {
1570 p = &float_format;
1571 detected = detected_float_format;
1572 }
1573 else {
1574 PyErr_SetString(PyExc_ValueError,
1575 "__setformat__() argument 1 must "
1576 "be 'double' or 'float'");
1577 return NULL;
1578 }
1579
1580 if (strcmp(format, "unknown") == 0) {
1581 f = unknown_format;
1582 }
1583 else if (strcmp(format, "IEEE, little-endian") == 0) {
1584 f = ieee_little_endian_format;
1585 }
1586 else if (strcmp(format, "IEEE, big-endian") == 0) {
1587 f = ieee_big_endian_format;
1588 }
1589 else {
1590 PyErr_SetString(PyExc_ValueError,
1591 "__setformat__() argument 2 must be "
1592 "'unknown', 'IEEE, little-endian' or "
1593 "'IEEE, big-endian'");
1594 return NULL;
1595
1596 }
1597
1598 if (f != unknown_format && f != detected) {
1599 PyErr_Format(PyExc_ValueError,
1600 "can only set %s format to 'unknown' or the "
1601 "detected platform value", typestr);
1602 return NULL;
1603 }
1604
1605 *p = f;
1606 Py_RETURN_NONE;
1607}
1608
1609PyDoc_STRVAR(float_setformat_doc,
1610"float.__setformat__(typestr, fmt) -> None\n"
1611"\n"
1612"You probably don't want to use this function. It exists mainly to be\n"
1613"used in Python's test suite.\n"
1614"\n"
1615"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1616"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1617"one of the latter two if it appears to match the underlying C reality.\n"
1618"\n"
1619"Overrides the automatic determination of C-level floating point type.\n"
1620"This affects how floats are converted to and from binary strings.");
1621
Guido van Rossumb43daf72007-08-01 18:08:08 +00001622static PyObject *
1623float_getzero(PyObject *v, void *closure)
1624{
1625 return PyFloat_FromDouble(0.0);
1626}
1627
Eric Smith8c663262007-08-25 02:26:07 +00001628static PyObject *
1629float__format__(PyObject *self, PyObject *args)
1630{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001631 PyObject *format_spec;
1632
1633 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1634 return NULL;
1635 return _PyFloat_FormatAdvanced(self,
1636 PyUnicode_AS_UNICODE(format_spec),
1637 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001638}
1639
1640PyDoc_STRVAR(float__format__doc,
1641"float.__format__(format_spec) -> string\n"
1642"\n"
1643"Formats the float according to format_spec.");
1644
1645
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001646static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001647 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001648 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001649 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1650 "Returns the Integral closest to x between 0 and x."},
1651 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1652 "Returns the Integral closest to x, rounding half toward even.\n"
1653 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001654 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1655 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001656 {"fromhex", (PyCFunction)float_fromhex,
1657 METH_O|METH_CLASS, float_fromhex_doc},
1658 {"hex", (PyCFunction)float_hex,
1659 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001660 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1661 "Returns True if the float is an integer."},
1662#if 0
1663 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1664 "Returns True if the float is positive or negative infinite."},
1665 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1666 "Returns True if the float is finite, neither infinite nor NaN."},
1667 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1668 "Returns True if the float is not a number (NaN)."},
1669#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001670 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671 {"__getformat__", (PyCFunction)float_getformat,
1672 METH_O|METH_CLASS, float_getformat_doc},
1673 {"__setformat__", (PyCFunction)float_setformat,
1674 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001675 {"__format__", (PyCFunction)float__format__,
1676 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001677 {NULL, NULL} /* sentinel */
1678};
1679
Guido van Rossumb43daf72007-08-01 18:08:08 +00001680static PyGetSetDef float_getset[] = {
1681 {"real",
1682 (getter)float_float, (setter)NULL,
1683 "the real part of a complex number",
1684 NULL},
1685 {"imag",
1686 (getter)float_getzero, (setter)NULL,
1687 "the imaginary part of a complex number",
1688 NULL},
1689 {NULL} /* Sentinel */
1690};
1691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001692PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693"float(x) -> floating point number\n\
1694\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001695Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696
1697
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001698static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001699 float_add, /*nb_add*/
1700 float_sub, /*nb_subtract*/
1701 float_mul, /*nb_multiply*/
1702 float_rem, /*nb_remainder*/
1703 float_divmod, /*nb_divmod*/
1704 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001705 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001706 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001707 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001708 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001709 0, /*nb_invert*/
1710 0, /*nb_lshift*/
1711 0, /*nb_rshift*/
1712 0, /*nb_and*/
1713 0, /*nb_xor*/
1714 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001715 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001716 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001717 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001718 0, /* nb_inplace_add */
1719 0, /* nb_inplace_subtract */
1720 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001721 0, /* nb_inplace_remainder */
1722 0, /* nb_inplace_power */
1723 0, /* nb_inplace_lshift */
1724 0, /* nb_inplace_rshift */
1725 0, /* nb_inplace_and */
1726 0, /* nb_inplace_xor */
1727 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001728 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001729 float_div, /* nb_true_divide */
1730 0, /* nb_inplace_floor_divide */
1731 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001732};
1733
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001735 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001737 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001738 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001740 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741 0, /* tp_getattr */
1742 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001743 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001744 (reprfunc)float_repr, /* tp_repr */
1745 &float_as_number, /* tp_as_number */
1746 0, /* tp_as_sequence */
1747 0, /* tp_as_mapping */
1748 (hashfunc)float_hash, /* tp_hash */
1749 0, /* tp_call */
1750 (reprfunc)float_str, /* tp_str */
1751 PyObject_GenericGetAttr, /* tp_getattro */
1752 0, /* tp_setattro */
1753 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001754 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755 float_doc, /* tp_doc */
1756 0, /* tp_traverse */
1757 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001758 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759 0, /* tp_weaklistoffset */
1760 0, /* tp_iter */
1761 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001762 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001764 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 0, /* tp_base */
1766 0, /* tp_dict */
1767 0, /* tp_descr_get */
1768 0, /* tp_descr_set */
1769 0, /* tp_dictoffset */
1770 0, /* tp_init */
1771 0, /* tp_alloc */
1772 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001773};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001774
1775void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001776_PyFloat_Init(void)
1777{
1778 /* We attempt to determine if this machine is using IEEE
1779 floating point formats by peering at the bits of some
1780 carefully chosen values. If it looks like we are on an
1781 IEEE platform, the float packing/unpacking routines can
1782 just copy bits, if not they resort to arithmetic & shifts
1783 and masks. The shifts & masks approach works on all finite
1784 values, but what happens to infinities, NaNs and signed
1785 zeroes on packing is an accident, and attempting to unpack
1786 a NaN or an infinity will raise an exception.
1787
1788 Note that if we're on some whacked-out platform which uses
1789 IEEE formats but isn't strictly little-endian or big-
1790 endian, we will fall back to the portable shifts & masks
1791 method. */
1792
1793#if SIZEOF_DOUBLE == 8
1794 {
1795 double x = 9006104071832581.0;
1796 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1797 detected_double_format = ieee_big_endian_format;
1798 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1799 detected_double_format = ieee_little_endian_format;
1800 else
1801 detected_double_format = unknown_format;
1802 }
1803#else
1804 detected_double_format = unknown_format;
1805#endif
1806
1807#if SIZEOF_FLOAT == 4
1808 {
1809 float y = 16711938.0;
1810 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1811 detected_float_format = ieee_big_endian_format;
1812 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1813 detected_float_format = ieee_little_endian_format;
1814 else
1815 detected_float_format = unknown_format;
1816 }
1817#else
1818 detected_float_format = unknown_format;
1819#endif
1820
1821 double_format = detected_double_format;
1822 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001823
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001824 /* Init float info */
1825 if (FloatInfoType.tp_name == 0)
1826 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001827}
1828
Georg Brandl2ee470f2008-07-16 12:55:28 +00001829int
1830PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001831{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001832 PyFloatObject *p;
1833 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001834 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001835 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001836 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001837
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001838 list = block_list;
1839 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001840 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001841 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001842 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001843 for (i = 0, p = &list->objects[0];
1844 i < N_FLOATOBJECTS;
1845 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001846 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001847 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001848 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001849 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001850 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001851 list->next = block_list;
1852 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001853 for (i = 0, p = &list->objects[0];
1854 i < N_FLOATOBJECTS;
1855 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001856 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001857 Py_REFCNT(p) == 0) {
1858 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001859 free_list;
1860 free_list = p;
1861 }
1862 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001863 }
1864 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001865 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001866 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001867 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001868 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001869 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001870 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001871}
1872
1873void
1874PyFloat_Fini(void)
1875{
1876 PyFloatObject *p;
1877 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001878 int i;
1879 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001880
Georg Brandl2ee470f2008-07-16 12:55:28 +00001881 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001882
Guido van Rossum3fce8831999-03-12 19:43:17 +00001883 if (!Py_VerboseFlag)
1884 return;
1885 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001886 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001887 fprintf(stderr, "\n");
1888 }
1889 else {
1890 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001891 ": %d unfreed float%s\n",
1892 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001893 }
1894 if (Py_VerboseFlag > 1) {
1895 list = block_list;
1896 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001897 for (i = 0, p = &list->objects[0];
1898 i < N_FLOATOBJECTS;
1899 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001900 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001901 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00001902 char *buf = PyOS_double_to_string(
1903 PyFloat_AS_DOUBLE(p), 'r',
1904 0, 0, NULL);
1905 if (buf) {
1906 /* XXX(twouters) cast
1907 refcount to long
1908 until %zd is
1909 universally
1910 available
1911 */
1912 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001913 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001914 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00001915 PyMem_Free(buf);
1916 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001917 }
1918 }
1919 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001920 }
1921 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001922}
Tim Peters9905b942003-03-20 20:53:32 +00001923
1924/*----------------------------------------------------------------------------
1925 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001926 */
1927int
1928_PyFloat_Pack4(double x, unsigned char *p, int le)
1929{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930 if (float_format == unknown_format) {
1931 unsigned char sign;
1932 int e;
1933 double f;
1934 unsigned int fbits;
1935 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001936
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001937 if (le) {
1938 p += 3;
1939 incr = -1;
1940 }
Tim Peters9905b942003-03-20 20:53:32 +00001941
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001942 if (x < 0) {
1943 sign = 1;
1944 x = -x;
1945 }
1946 else
1947 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001948
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001949 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001950
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001951 /* Normalize f to be in the range [1.0, 2.0) */
1952 if (0.5 <= f && f < 1.0) {
1953 f *= 2.0;
1954 e--;
1955 }
1956 else if (f == 0.0)
1957 e = 0;
1958 else {
1959 PyErr_SetString(PyExc_SystemError,
1960 "frexp() result out of range");
1961 return -1;
1962 }
1963
1964 if (e >= 128)
1965 goto Overflow;
1966 else if (e < -126) {
1967 /* Gradual underflow */
1968 f = ldexp(f, 126 + e);
1969 e = 0;
1970 }
1971 else if (!(e == 0 && f == 0.0)) {
1972 e += 127;
1973 f -= 1.0; /* Get rid of leading 1 */
1974 }
1975
1976 f *= 8388608.0; /* 2**23 */
1977 fbits = (unsigned int)(f + 0.5); /* Round */
1978 assert(fbits <= 8388608);
1979 if (fbits >> 23) {
1980 /* The carry propagated out of a string of 23 1 bits. */
1981 fbits = 0;
1982 ++e;
1983 if (e >= 255)
1984 goto Overflow;
1985 }
1986
1987 /* First byte */
1988 *p = (sign << 7) | (e >> 1);
1989 p += incr;
1990
1991 /* Second byte */
1992 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1993 p += incr;
1994
1995 /* Third byte */
1996 *p = (fbits >> 8) & 0xFF;
1997 p += incr;
1998
1999 /* Fourth byte */
2000 *p = fbits & 0xFF;
2001
2002 /* Done */
2003 return 0;
2004
Tim Peters9905b942003-03-20 20:53:32 +00002005 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002006 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002007 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002008 const char *s = (char*)&y;
2009 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002010
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002011 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2012 goto Overflow;
2013
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002014 if ((float_format == ieee_little_endian_format && !le)
2015 || (float_format == ieee_big_endian_format && le)) {
2016 p += 3;
2017 incr = -1;
2018 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002019
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002020 for (i = 0; i < 4; i++) {
2021 *p = *s++;
2022 p += incr;
2023 }
2024 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002025 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002026 Overflow:
2027 PyErr_SetString(PyExc_OverflowError,
2028 "float too large to pack with f format");
2029 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002030}
2031
2032int
2033_PyFloat_Pack8(double x, unsigned char *p, int le)
2034{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002035 if (double_format == unknown_format) {
2036 unsigned char sign;
2037 int e;
2038 double f;
2039 unsigned int fhi, flo;
2040 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002041
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002042 if (le) {
2043 p += 7;
2044 incr = -1;
2045 }
Tim Peters9905b942003-03-20 20:53:32 +00002046
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002047 if (x < 0) {
2048 sign = 1;
2049 x = -x;
2050 }
2051 else
2052 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002053
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002054 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002055
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002056 /* Normalize f to be in the range [1.0, 2.0) */
2057 if (0.5 <= f && f < 1.0) {
2058 f *= 2.0;
2059 e--;
2060 }
2061 else if (f == 0.0)
2062 e = 0;
2063 else {
2064 PyErr_SetString(PyExc_SystemError,
2065 "frexp() result out of range");
2066 return -1;
2067 }
2068
2069 if (e >= 1024)
2070 goto Overflow;
2071 else if (e < -1022) {
2072 /* Gradual underflow */
2073 f = ldexp(f, 1022 + e);
2074 e = 0;
2075 }
2076 else if (!(e == 0 && f == 0.0)) {
2077 e += 1023;
2078 f -= 1.0; /* Get rid of leading 1 */
2079 }
2080
2081 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2082 f *= 268435456.0; /* 2**28 */
2083 fhi = (unsigned int)f; /* Truncate */
2084 assert(fhi < 268435456);
2085
2086 f -= (double)fhi;
2087 f *= 16777216.0; /* 2**24 */
2088 flo = (unsigned int)(f + 0.5); /* Round */
2089 assert(flo <= 16777216);
2090 if (flo >> 24) {
2091 /* The carry propagated out of a string of 24 1 bits. */
2092 flo = 0;
2093 ++fhi;
2094 if (fhi >> 28) {
2095 /* And it also progagated out of the next 28 bits. */
2096 fhi = 0;
2097 ++e;
2098 if (e >= 2047)
2099 goto Overflow;
2100 }
2101 }
2102
2103 /* First byte */
2104 *p = (sign << 7) | (e >> 4);
2105 p += incr;
2106
2107 /* Second byte */
2108 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2109 p += incr;
2110
2111 /* Third byte */
2112 *p = (fhi >> 16) & 0xFF;
2113 p += incr;
2114
2115 /* Fourth byte */
2116 *p = (fhi >> 8) & 0xFF;
2117 p += incr;
2118
2119 /* Fifth byte */
2120 *p = fhi & 0xFF;
2121 p += incr;
2122
2123 /* Sixth byte */
2124 *p = (flo >> 16) & 0xFF;
2125 p += incr;
2126
2127 /* Seventh byte */
2128 *p = (flo >> 8) & 0xFF;
2129 p += incr;
2130
2131 /* Eighth byte */
2132 *p = flo & 0xFF;
2133 p += incr;
2134
2135 /* Done */
2136 return 0;
2137
2138 Overflow:
2139 PyErr_SetString(PyExc_OverflowError,
2140 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002141 return -1;
2142 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002143 else {
2144 const char *s = (char*)&x;
2145 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002146
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002147 if ((double_format == ieee_little_endian_format && !le)
2148 || (double_format == ieee_big_endian_format && le)) {
2149 p += 7;
2150 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002151 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002152
2153 for (i = 0; i < 8; i++) {
2154 *p = *s++;
2155 p += incr;
2156 }
2157 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002158 }
Tim Peters9905b942003-03-20 20:53:32 +00002159}
2160
2161double
2162_PyFloat_Unpack4(const unsigned char *p, int le)
2163{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002164 if (float_format == unknown_format) {
2165 unsigned char sign;
2166 int e;
2167 unsigned int f;
2168 double x;
2169 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002170
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171 if (le) {
2172 p += 3;
2173 incr = -1;
2174 }
2175
2176 /* First byte */
2177 sign = (*p >> 7) & 1;
2178 e = (*p & 0x7F) << 1;
2179 p += incr;
2180
2181 /* Second byte */
2182 e |= (*p >> 7) & 1;
2183 f = (*p & 0x7F) << 16;
2184 p += incr;
2185
2186 if (e == 255) {
2187 PyErr_SetString(
2188 PyExc_ValueError,
2189 "can't unpack IEEE 754 special value "
2190 "on non-IEEE platform");
2191 return -1;
2192 }
2193
2194 /* Third byte */
2195 f |= *p << 8;
2196 p += incr;
2197
2198 /* Fourth byte */
2199 f |= *p;
2200
2201 x = (double)f / 8388608.0;
2202
2203 /* XXX This sadly ignores Inf/NaN issues */
2204 if (e == 0)
2205 e = -126;
2206 else {
2207 x += 1.0;
2208 e -= 127;
2209 }
2210 x = ldexp(x, e);
2211
2212 if (sign)
2213 x = -x;
2214
2215 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002216 }
Tim Peters9905b942003-03-20 20:53:32 +00002217 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002218 float x;
2219
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220 if ((float_format == ieee_little_endian_format && !le)
2221 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002222 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223 char *d = &buf[3];
2224 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002225
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226 for (i = 0; i < 4; i++) {
2227 *d-- = *p++;
2228 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002229 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230 }
2231 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002232 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002234
2235 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236 }
Tim Peters9905b942003-03-20 20:53:32 +00002237}
2238
2239double
2240_PyFloat_Unpack8(const unsigned char *p, int le)
2241{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002242 if (double_format == unknown_format) {
2243 unsigned char sign;
2244 int e;
2245 unsigned int fhi, flo;
2246 double x;
2247 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002248
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002249 if (le) {
2250 p += 7;
2251 incr = -1;
2252 }
2253
2254 /* First byte */
2255 sign = (*p >> 7) & 1;
2256 e = (*p & 0x7F) << 4;
2257
2258 p += incr;
2259
2260 /* Second byte */
2261 e |= (*p >> 4) & 0xF;
2262 fhi = (*p & 0xF) << 24;
2263 p += incr;
2264
2265 if (e == 2047) {
2266 PyErr_SetString(
2267 PyExc_ValueError,
2268 "can't unpack IEEE 754 special value "
2269 "on non-IEEE platform");
2270 return -1.0;
2271 }
2272
2273 /* Third byte */
2274 fhi |= *p << 16;
2275 p += incr;
2276
2277 /* Fourth byte */
2278 fhi |= *p << 8;
2279 p += incr;
2280
2281 /* Fifth byte */
2282 fhi |= *p;
2283 p += incr;
2284
2285 /* Sixth byte */
2286 flo = *p << 16;
2287 p += incr;
2288
2289 /* Seventh byte */
2290 flo |= *p << 8;
2291 p += incr;
2292
2293 /* Eighth byte */
2294 flo |= *p;
2295
2296 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2297 x /= 268435456.0; /* 2**28 */
2298
2299 if (e == 0)
2300 e = -1022;
2301 else {
2302 x += 1.0;
2303 e -= 1023;
2304 }
2305 x = ldexp(x, e);
2306
2307 if (sign)
2308 x = -x;
2309
2310 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002311 }
Tim Peters9905b942003-03-20 20:53:32 +00002312 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002313 double x;
2314
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315 if ((double_format == ieee_little_endian_format && !le)
2316 || (double_format == ieee_big_endian_format && le)) {
2317 char buf[8];
2318 char *d = &buf[7];
2319 int i;
2320
2321 for (i = 0; i < 8; i++) {
2322 *d-- = *p++;
2323 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002324 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002325 }
2326 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002327 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002329
2330 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002331 }
Tim Peters9905b942003-03-20 20:53:32 +00002332}