blob: b281f815dc750a755014b1b8c39ef3e5a13d3217 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Guido van Rossum6923e131990-11-02 17:50:43 +000018
Christian Heimes969fe572008-01-25 11:23:10 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000026#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000027#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
30 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
32};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
42 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000043 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000047 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 q = p + N_FLOATOBJECTS;
51 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000052 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 return p + N_FLOATOBJECTS - 1;
55}
56
Christian Heimes93852662007-12-01 12:22:32 +000057double
58PyFloat_GetMax(void)
59{
60 return DBL_MAX;
61}
62
63double
64PyFloat_GetMin(void)
65{
66 return DBL_MIN;
67}
68
Christian Heimesd32ed6f2008-01-14 18:49:24 +000069static PyTypeObject FloatInfoType;
70
71PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000072"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
79 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
96};
97
98static PyStructSequence_Desc floatinfo_desc = {
Benjamin Peterson78565b22009-06-28 19:19:51 +000099 "sys.float_info", /* name */
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
103};
104
Christian Heimes93852662007-12-01 12:22:32 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000108 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000109 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000110
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000111 floatinfo = PyStructSequence_New(&FloatInfoType);
112 if (floatinfo == NULL) {
113 return NULL;
114 }
Christian Heimes93852662007-12-01 12:22:32 +0000115
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000116#define SetIntFlag(flag) \
117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
118#define SetDblFlag(flag) \
119 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000120
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000121 SetDblFlag(DBL_MAX);
122 SetIntFlag(DBL_MAX_EXP);
123 SetIntFlag(DBL_MAX_10_EXP);
124 SetDblFlag(DBL_MIN);
125 SetIntFlag(DBL_MIN_EXP);
126 SetIntFlag(DBL_MIN_10_EXP);
127 SetIntFlag(DBL_DIG);
128 SetIntFlag(DBL_MANT_DIG);
129 SetDblFlag(DBL_EPSILON);
130 SetIntFlag(FLT_RADIX);
131 SetIntFlag(FLT_ROUNDS);
132#undef SetIntFlag
133#undef SetDblFlag
134
135 if (PyErr_Occurred()) {
136 Py_CLEAR(floatinfo);
137 return NULL;
138 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000139 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000140}
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000145 register PyFloatObject *op;
146 if (free_list == NULL) {
147 if ((free_list = fill_free_list()) == NULL)
148 return NULL;
149 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000150 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000151 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000152 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000153 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000154 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000158PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000159PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160{
Mark Dickinson6d65df12009-04-26 15:30:47 +0000161 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000163 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000164 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000166 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000168 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000169 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
170 if (s_buffer == NULL)
171 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000172 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000173 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000174 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000175 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000176 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000178 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000180 else if (PyObject_AsCharBuffer(v, &s, &len)) {
181 PyErr_SetString(PyExc_TypeError,
Mark Dickinsone0d6f602009-10-26 21:12:50 +0000182 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000183 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000185 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000186
Mark Dickinsonaa77d262009-05-03 21:07:13 +0000187 while (Py_ISSPACE(*s))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 s++;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000189 /* We don't care about overflow or underflow. If the platform
190 * supports them, infinities and signed zeroes (on underflow) are
191 * fine. */
Mark Dickinson725bfd82009-05-03 20:33:40 +0000192 x = PyOS_string_to_double(s, (char **)&end, NULL);
193 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum2be161d2007-05-15 20:43:51 +0000194 goto error;
Mark Dickinsonaa77d262009-05-03 21:07:13 +0000195 while (Py_ISSPACE(*end))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 end++;
Mark Dickinson725bfd82009-05-03 20:33:40 +0000197 if (end == last)
198 result = PyFloat_FromDouble(x);
199 else {
200 PyOS_snprintf(buffer, sizeof(buffer),
201 "invalid literal for float(): %.200s", s);
202 PyErr_SetString(PyExc_ValueError, buffer);
203 result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000204 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000205
Guido van Rossum2be161d2007-05-15 20:43:51 +0000206 error:
207 if (s_buffer)
208 PyMem_FREE(s_buffer);
209 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210}
211
Guido van Rossum234f9421993-06-17 12:35:49 +0000212static void
Fred Drakefd99de62000-07-09 05:02:18 +0000213float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000214{
Guido van Rossum9475a232001-10-05 20:51:39 +0000215 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000216 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000217 free_list = op;
218 }
219 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000220 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000221}
222
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223double
Fred Drakefd99de62000-07-09 05:02:18 +0000224PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226 PyNumberMethods *nb;
227 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000228 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000229
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230 if (op && PyFloat_Check(op))
231 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000232
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000233 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 return -1;
236 }
Tim Petersd2364e82001-11-01 20:09:42 +0000237
Christian Heimes90aa7642007-12-19 02:45:37 +0000238 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000239 PyErr_SetString(PyExc_TypeError, "a float is required");
240 return -1;
241 }
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000244 if (fo == NULL)
245 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 if (!PyFloat_Check(fo)) {
247 PyErr_SetString(PyExc_TypeError,
248 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000249 return -1;
250 }
Tim Petersd2364e82001-11-01 20:09:42 +0000251
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000252 val = PyFloat_AS_DOUBLE(fo);
253 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000254
Guido van Rossumb6775db1994-08-01 11:34:53 +0000255 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256}
257
Neil Schemenauer32117e52001-01-04 01:44:34 +0000258/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000259 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000260 set to NULL, and the function invoking this macro returns NULL. If
261 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
262 stored in obj, and returned from the function invoking this macro.
263*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264#define CONVERT_TO_DOUBLE(obj, dbl) \
265 if (PyFloat_Check(obj)) \
266 dbl = PyFloat_AS_DOUBLE(obj); \
267 else if (convert_to_double(&(obj), &(dbl)) < 0) \
268 return obj;
269
Eric Smith0923d1d2009-04-16 20:16:10 +0000270/* Methods */
271
Neil Schemenauer32117e52001-01-04 01:44:34 +0000272static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000273convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000274{
275 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000276
Guido van Rossumddefaf32007-01-14 03:31:43 +0000277 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000279 if (*dbl == -1.0 && PyErr_Occurred()) {
280 *v = NULL;
281 return -1;
282 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000283 }
284 else {
285 Py_INCREF(Py_NotImplemented);
286 *v = Py_NotImplemented;
287 return -1;
288 }
289 return 0;
290}
291
Eric Smith0923d1d2009-04-16 20:16:10 +0000292static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000293float_str_or_repr(PyFloatObject *v, int precision, char format_code)
Eric Smith0923d1d2009-04-16 20:16:10 +0000294{
295 PyObject *result;
296 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Eric Smith63376222009-05-05 14:04:18 +0000297 format_code, precision,
298 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000299 NULL);
300 if (!buf)
301 return PyErr_NoMemory();
302 result = PyUnicode_FromString(buf);
303 PyMem_Free(buf);
304 return result;
305}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000306
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000308float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Eric Smith63376222009-05-05 14:04:18 +0000310 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000311}
312
313static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000314float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000315{
Eric Smith63376222009-05-05 14:04:18 +0000316 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317}
318
Tim Peters307fa782004-09-23 08:06:40 +0000319/* Comparison is pretty much a nightmare. When comparing float to float,
320 * we do it as straightforwardly (and long-windedly) as conceivable, so
321 * that, e.g., Python x == y delivers the same result as the platform
322 * C x == y when x and/or y is a NaN.
323 * When mixing float with an integer type, there's no good *uniform* approach.
324 * Converting the double to an integer obviously doesn't work, since we
325 * may lose info from fractional bits. Converting the integer to a double
326 * also has two failure modes: (1) a long int may trigger overflow (too
327 * large to fit in the dynamic range of a C double); (2) even a C long may have
328 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
329 * 63 bits of precision, but a C double probably has only 53), and then
330 * we can falsely claim equality when low-order integer bits are lost by
331 * coercion to double. So this part is painful too.
332 */
333
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000334static PyObject*
335float_richcompare(PyObject *v, PyObject *w, int op)
336{
337 double i, j;
338 int r = 0;
339
Tim Peters307fa782004-09-23 08:06:40 +0000340 assert(PyFloat_Check(v));
341 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000342
Tim Peters307fa782004-09-23 08:06:40 +0000343 /* Switch on the type of w. Set i and j to doubles to be compared,
344 * and op to the richcomp to use.
345 */
346 if (PyFloat_Check(w))
347 j = PyFloat_AS_DOUBLE(w);
348
Thomas Wouters477c8d52006-05-27 19:21:47 +0000349 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000350 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000351 /* If i is an infinity, its magnitude exceeds any
352 * finite integer, so it doesn't matter which int we
353 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000354 */
355 j = 0.0;
356 else
357 goto Unimplemented;
358 }
359
Tim Peters307fa782004-09-23 08:06:40 +0000360 else if (PyLong_Check(w)) {
361 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
362 int wsign = _PyLong_Sign(w);
363 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000364 int exponent;
365
366 if (vsign != wsign) {
367 /* Magnitudes are irrelevant -- the signs alone
368 * determine the outcome.
369 */
370 i = (double)vsign;
371 j = (double)wsign;
372 goto Compare;
373 }
374 /* The signs are the same. */
375 /* Convert w to a double if it fits. In particular, 0 fits. */
376 nbits = _PyLong_NumBits(w);
377 if (nbits == (size_t)-1 && PyErr_Occurred()) {
378 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000379 * to hold the # of bits. Replace with little doubles
380 * that give the same outcome -- w is so large that
381 * its magnitude must exceed the magnitude of any
382 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000383 */
384 PyErr_Clear();
385 i = (double)vsign;
386 assert(wsign != 0);
387 j = wsign * 2.0;
388 goto Compare;
389 }
390 if (nbits <= 48) {
391 j = PyLong_AsDouble(w);
392 /* It's impossible that <= 48 bits overflowed. */
393 assert(j != -1.0 || ! PyErr_Occurred());
394 goto Compare;
395 }
396 assert(wsign != 0); /* else nbits was 0 */
397 assert(vsign != 0); /* if vsign were 0, then since wsign is
398 * not 0, we would have taken the
399 * vsign != wsign branch at the start */
400 /* We want to work with non-negative numbers. */
401 if (vsign < 0) {
402 /* "Multiply both sides" by -1; this also swaps the
403 * comparator.
404 */
405 i = -i;
406 op = _Py_SwappedOp[op];
407 }
408 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000409 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000410 /* exponent is the # of bits in v before the radix point;
411 * we know that nbits (the # of bits in w) > 48 at this point
412 */
413 if (exponent < 0 || (size_t)exponent < nbits) {
414 i = 1.0;
415 j = 2.0;
416 goto Compare;
417 }
418 if ((size_t)exponent > nbits) {
419 i = 2.0;
420 j = 1.0;
421 goto Compare;
422 }
423 /* v and w have the same number of bits before the radix
424 * point. Construct two longs that have the same comparison
425 * outcome.
426 */
427 {
428 double fracpart;
429 double intpart;
430 PyObject *result = NULL;
431 PyObject *one = NULL;
432 PyObject *vv = NULL;
433 PyObject *ww = w;
434
435 if (wsign < 0) {
436 ww = PyNumber_Negative(w);
437 if (ww == NULL)
438 goto Error;
439 }
440 else
441 Py_INCREF(ww);
442
443 fracpart = modf(i, &intpart);
444 vv = PyLong_FromDouble(intpart);
445 if (vv == NULL)
446 goto Error;
447
448 if (fracpart != 0.0) {
449 /* Shift left, and or a 1 bit into vv
450 * to represent the lost fraction.
451 */
452 PyObject *temp;
453
Christian Heimes217cfd12007-12-02 14:31:20 +0000454 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000455 if (one == NULL)
456 goto Error;
457
458 temp = PyNumber_Lshift(ww, one);
459 if (temp == NULL)
460 goto Error;
461 Py_DECREF(ww);
462 ww = temp;
463
464 temp = PyNumber_Lshift(vv, one);
465 if (temp == NULL)
466 goto Error;
467 Py_DECREF(vv);
468 vv = temp;
469
470 temp = PyNumber_Or(vv, one);
471 if (temp == NULL)
472 goto Error;
473 Py_DECREF(vv);
474 vv = temp;
475 }
476
477 r = PyObject_RichCompareBool(vv, ww, op);
478 if (r < 0)
479 goto Error;
480 result = PyBool_FromLong(r);
481 Error:
482 Py_XDECREF(vv);
483 Py_XDECREF(ww);
484 Py_XDECREF(one);
485 return result;
486 }
487 } /* else if (PyLong_Check(w)) */
488
489 else /* w isn't float, int, or long */
490 goto Unimplemented;
491
492 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000493 PyFPE_START_PROTECT("richcompare", return NULL)
494 switch (op) {
495 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000496 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000497 break;
498 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000499 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000500 break;
501 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000502 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000503 break;
504 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000505 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000506 break;
507 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000508 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000509 break;
510 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000511 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000512 break;
513 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000514 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000515 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000516
517 Unimplemented:
518 Py_INCREF(Py_NotImplemented);
519 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000520}
521
Guido van Rossum9bfef441993-03-29 10:43:31 +0000522static long
Fred Drakefd99de62000-07-09 05:02:18 +0000523float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000524{
Tim Peters39dce292000-08-15 03:34:48 +0000525 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000526}
527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000531 double a,b;
532 CONVERT_TO_DOUBLE(v, a);
533 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000534 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000535 a = a + b;
536 PyFPE_END_PROTECT(a)
537 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538}
539
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543 double a,b;
544 CONVERT_TO_DOUBLE(v, a);
545 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000546 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000547 a = a - b;
548 PyFPE_END_PROTECT(a)
549 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000555 double a,b;
556 CONVERT_TO_DOUBLE(v, a);
557 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000558 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000559 a = a * b;
560 PyFPE_END_PROTECT(a)
561 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000567 double a,b;
568 CONVERT_TO_DOUBLE(v, a);
569 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000570#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000571 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000572 PyErr_SetString(PyExc_ZeroDivisionError,
573 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000574 return NULL;
575 }
Christian Heimes53876d92008-04-19 00:31:39 +0000576#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000577 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000578 a = a / b;
579 PyFPE_END_PROTECT(a)
580 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000584float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000586 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000587 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000588 CONVERT_TO_DOUBLE(v, vx);
589 CONVERT_TO_DOUBLE(w, wx);
590#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000592 PyErr_SetString(PyExc_ZeroDivisionError,
593 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594 return NULL;
595 }
Christian Heimes53876d92008-04-19 00:31:39 +0000596#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000597 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000598 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000599 /* note: checking mod*wx < 0 is incorrect -- underflows to
600 0 if wx < sqrt(smallest nonzero double) */
601 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000602 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000603 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000604 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606}
607
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000609float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000610{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000611 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000612 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000613 CONVERT_TO_DOUBLE(v, vx);
614 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000615 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000617 return NULL;
618 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000619 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000620 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000621 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000622 exact multiple of wx. But this is fp arithmetic, and fp
623 vx - mod is an approximation; the result is that div may
624 not be an exact integral value after the division, although
625 it will always be very close to one.
626 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000627 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000628 if (mod) {
629 /* ensure the remainder has the same sign as the denominator */
630 if ((wx < 0) != (mod < 0)) {
631 mod += wx;
632 div -= 1.0;
633 }
634 }
635 else {
636 /* the remainder is zero, and in the presence of signed zeroes
637 fmod returns different results across platforms; ensure
638 it has the same sign as the denominator; we'd like to do
639 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000640 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000641 if (wx < 0.0)
642 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000643 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000644 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000645 if (div) {
646 floordiv = floor(div);
647 if (div - floordiv > 0.5)
648 floordiv += 1.0;
649 }
650 else {
651 /* div is zero - get the same sign as the true quotient */
652 div *= div; /* hide "div = +0" from optimizers */
653 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
654 }
655 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000656 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000660float_floor_div(PyObject *v, PyObject *w)
661{
662 PyObject *t, *r;
663
664 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000665 if (t == NULL || t == Py_NotImplemented)
666 return t;
667 assert(PyTuple_CheckExact(t));
668 r = PyTuple_GET_ITEM(t, 0);
669 Py_INCREF(r);
670 Py_DECREF(t);
671 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000672}
673
674static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000675float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676{
677 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000678
679 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000680 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000681 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000682 return NULL;
683 }
684
Neil Schemenauer32117e52001-01-04 01:44:34 +0000685 CONVERT_TO_DOUBLE(v, iv);
686 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000687
688 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000689 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000690 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000691 }
Tim Peters96685bf2001-08-23 22:31:37 +0000692 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000693 if (iw < 0.0) {
694 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000695 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000696 return NULL;
697 }
698 return PyFloat_FromDouble(0.0);
699 }
Christian Heimes53876d92008-04-19 00:31:39 +0000700 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
701 return PyFloat_FromDouble(1.0);
702 }
Tim Peterse87568d2003-05-24 20:18:24 +0000703 if (iv < 0.0) {
704 /* Whether this is an error is a mess, and bumps into libm
705 * bugs so we have to figure it out ourselves.
706 */
707 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000708 /* Negative numbers raised to fractional powers
709 * become complex.
710 */
711 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000712 }
713 /* iw is an exact integer, albeit perhaps a very large one.
714 * -1 raised to an exact integer should never be exceptional.
715 * Alas, some libms (chiefly glibc as of early 2003) return
716 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
717 * happen to be representable in a *C* integer. That's a
718 * bug; we let that slide in math.pow() (which currently
719 * reflects all platform accidents), but not for Python's **.
720 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000721 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000722 /* Return 1 if iw is even, -1 if iw is odd; there's
723 * no guarantee that any C integral type is big
724 * enough to hold iw, so we have to check this
725 * indirectly.
726 */
727 ix = floor(iw * 0.5) * 2.0;
728 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
729 }
730 /* Else iv != -1.0, and overflow or underflow are possible.
731 * Unless we're to write pow() ourselves, we have to trust
732 * the platform to do this correctly.
733 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000734 }
Tim Peters96685bf2001-08-23 22:31:37 +0000735 errno = 0;
736 PyFPE_START_PROTECT("pow", return NULL)
737 ix = pow(iv, iw);
738 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000739 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000740 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000741 /* We don't expect any errno value other than ERANGE, but
742 * the range of libm bugs appears unbounded.
743 */
744 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
745 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000746 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000747 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000749}
750
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000751static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000752float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000753{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755}
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000758float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000759{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000760 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000761}
762
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000763static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000764float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000765{
766 return v->ob_fval != 0.0;
767}
768
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000770float_is_integer(PyObject *v)
771{
772 double x = PyFloat_AsDouble(v);
773 PyObject *o;
774
775 if (x == -1.0 && PyErr_Occurred())
776 return NULL;
777 if (!Py_IS_FINITE(x))
778 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000779 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000780 PyFPE_START_PROTECT("is_integer", return NULL)
781 o = (floor(x) == x) ? Py_True : Py_False;
782 PyFPE_END_PROTECT(x)
783 if (errno != 0) {
784 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
785 PyExc_ValueError);
786 return NULL;
787 }
788 Py_INCREF(o);
789 return o;
790}
791
792#if 0
793static PyObject *
794float_is_inf(PyObject *v)
795{
796 double x = PyFloat_AsDouble(v);
797 if (x == -1.0 && PyErr_Occurred())
798 return NULL;
799 return PyBool_FromLong((long)Py_IS_INFINITY(x));
800}
801
802static PyObject *
803float_is_nan(PyObject *v)
804{
805 double x = PyFloat_AsDouble(v);
806 if (x == -1.0 && PyErr_Occurred())
807 return NULL;
808 return PyBool_FromLong((long)Py_IS_NAN(x));
809}
810
811static PyObject *
812float_is_finite(PyObject *v)
813{
814 double x = PyFloat_AsDouble(v);
815 if (x == -1.0 && PyErr_Occurred())
816 return NULL;
817 return PyBool_FromLong((long)Py_IS_FINITE(x));
818}
819#endif
820
821static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000822float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000823{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000825 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000826
827 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000828 /* Try to get out cheap if this fits in a Python int. The attempt
829 * to cast to long must be protected, as C doesn't define what
830 * happens if the double is too big to fit in a long. Some rare
831 * systems raise an exception then (RISCOS was mentioned as one,
832 * and someone using a non-default option on Sun also bumped into
833 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
834 * still be vulnerable: if a long has more bits of precision than
835 * a double, casting MIN/MAX to double may yield an approximation,
836 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
837 * yield true from the C expression wholepart<=LONG_MAX, despite
838 * that wholepart is actually greater than LONG_MAX.
839 */
840 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
841 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000842 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000843 }
844 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000845}
846
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000847/* double_round: rounds a finite double to the closest multiple of
848 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
849 ndigits <= 323). Returns a Python float, or sets a Python error and
850 returns NULL on failure (OverflowError and memory errors are possible). */
851
852#ifndef PY_NO_SHORT_FLOAT_REPR
853/* version of double_round that uses the correctly-rounded string<->double
854 conversions from Python/dtoa.c */
855
856static PyObject *
857double_round(double x, int ndigits) {
858
859 double rounded;
860 Py_ssize_t buflen, mybuflen=100;
861 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
862 int decpt, sign;
863 PyObject *result = NULL;
864
865 /* round to a decimal string */
866 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
867 if (buf == NULL) {
868 PyErr_NoMemory();
869 return NULL;
870 }
871
872 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
873 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
874 buflen = buf_end - buf;
875 if (buflen + 8 > mybuflen) {
876 mybuflen = buflen+8;
877 mybuf = (char *)PyMem_Malloc(mybuflen);
878 if (mybuf == NULL) {
879 PyErr_NoMemory();
880 goto exit;
881 }
882 }
883 /* copy buf to mybuf, adding exponent, sign and leading 0 */
884 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
885 buf, decpt - (int)buflen);
886
887 /* and convert the resulting string back to a double */
888 errno = 0;
889 rounded = _Py_dg_strtod(mybuf, NULL);
890 if (errno == ERANGE && fabs(rounded) >= 1.)
891 PyErr_SetString(PyExc_OverflowError,
892 "rounded value too large to represent");
893 else
894 result = PyFloat_FromDouble(rounded);
895
896 /* done computing value; now clean up */
897 if (mybuf != shortbuf)
898 PyMem_Free(mybuf);
899 exit:
900 _Py_dg_freedtoa(buf);
901 return result;
902}
903
904#else /* PY_NO_SHORT_FLOAT_REPR */
905
906/* fallback version, to be used when correctly rounded binary<->decimal
907 conversions aren't available */
908
909static PyObject *
910double_round(double x, int ndigits) {
911 double pow1, pow2, y, z;
912 if (ndigits >= 0) {
913 if (ndigits > 22) {
914 /* pow1 and pow2 are each safe from overflow, but
915 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
916 pow1 = pow(10.0, (double)(ndigits-22));
917 pow2 = 1e22;
918 }
919 else {
920 pow1 = pow(10.0, (double)ndigits);
921 pow2 = 1.0;
922 }
923 y = (x*pow1)*pow2;
924 /* if y overflows, then rounded value is exactly x */
925 if (!Py_IS_FINITE(y))
926 return PyFloat_FromDouble(x);
927 }
928 else {
929 pow1 = pow(10.0, (double)-ndigits);
930 pow2 = 1.0; /* unused; silences a gcc compiler warning */
931 y = x / pow1;
932 }
933
934 z = round(y);
935 if (fabs(y-z) == 0.5)
936 /* halfway between two integers; use round-half-even */
937 z = 2.0*round(y/2.0);
938
939 if (ndigits >= 0)
940 z = (z / pow2) / pow1;
941 else
942 z *= pow1;
943
944 /* if computation resulted in overflow, raise OverflowError */
945 if (!Py_IS_FINITE(z)) {
946 PyErr_SetString(PyExc_OverflowError,
947 "overflow occurred during round");
948 return NULL;
949 }
950
951 return PyFloat_FromDouble(z);
952}
953
954#endif /* PY_NO_SHORT_FLOAT_REPR */
955
956/* round a Python float v to the closest multiple of 10**-ndigits */
957
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000958static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000959float_round(PyObject *v, PyObject *args)
960{
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000961 double x, rounded;
962 PyObject *o_ndigits = NULL;
963 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000964
965 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000966 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
967 return NULL;
968 if (o_ndigits == NULL) {
969 /* single-argument round: round to nearest integer */
970 rounded = round(x);
971 if (fabs(x-rounded) == 0.5)
972 /* halfway case: round to even */
973 rounded = 2.0*round(x/2.0);
974 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000975 }
976
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000977 /* interpret second argument as a Py_ssize_t; clips on overflow */
978 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
979 if (ndigits == -1 && PyErr_Occurred())
980 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000981
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000982 /* nans and infinities round to themselves */
983 if (!Py_IS_FINITE(x))
984 return PyFloat_FromDouble(x);
985
986 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
987 always rounds to itself. For ndigits < NDIGITS_MIN, x always
988 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
989#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
990#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
991 if (ndigits > NDIGITS_MAX)
992 /* return x */
993 return PyFloat_FromDouble(x);
994 else if (ndigits < NDIGITS_MIN)
995 /* return 0.0, but with sign of x */
996 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000997 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000998 /* finite x, and ndigits is not unreasonably large */
999 return double_round(x, (int)ndigits);
1000#undef NDIGITS_MAX
1001#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001002}
1003
1004static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001005float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001006{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001007 if (PyFloat_CheckExact(v))
1008 Py_INCREF(v);
1009 else
1010 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001011 return v;
1012}
1013
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001014/* turn ASCII hex characters into integer values and vice versa */
1015
1016static char
1017char_from_hex(int x)
1018{
1019 assert(0 <= x && x < 16);
1020 return "0123456789abcdef"[x];
1021}
1022
1023static int
1024hex_from_char(char c) {
1025 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001026 switch(c) {
1027 case '0':
1028 x = 0;
1029 break;
1030 case '1':
1031 x = 1;
1032 break;
1033 case '2':
1034 x = 2;
1035 break;
1036 case '3':
1037 x = 3;
1038 break;
1039 case '4':
1040 x = 4;
1041 break;
1042 case '5':
1043 x = 5;
1044 break;
1045 case '6':
1046 x = 6;
1047 break;
1048 case '7':
1049 x = 7;
1050 break;
1051 case '8':
1052 x = 8;
1053 break;
1054 case '9':
1055 x = 9;
1056 break;
1057 case 'a':
1058 case 'A':
1059 x = 10;
1060 break;
1061 case 'b':
1062 case 'B':
1063 x = 11;
1064 break;
1065 case 'c':
1066 case 'C':
1067 x = 12;
1068 break;
1069 case 'd':
1070 case 'D':
1071 x = 13;
1072 break;
1073 case 'e':
1074 case 'E':
1075 x = 14;
1076 break;
1077 case 'f':
1078 case 'F':
1079 x = 15;
1080 break;
1081 default:
1082 x = -1;
1083 break;
1084 }
1085 return x;
1086}
1087
1088/* convert a float to a hexadecimal string */
1089
1090/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1091 of the form 4k+1. */
1092#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1093
1094static PyObject *
1095float_hex(PyObject *v)
1096{
1097 double x, m;
1098 int e, shift, i, si, esign;
1099 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1100 trailing NUL byte. */
1101 char s[(TOHEX_NBITS-1)/4+3];
1102
1103 CONVERT_TO_DOUBLE(v, x);
1104
1105 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1106 return float_str((PyFloatObject *)v);
1107
1108 if (x == 0.0) {
1109 if(copysign(1.0, x) == -1.0)
1110 return PyUnicode_FromString("-0x0.0p+0");
1111 else
1112 return PyUnicode_FromString("0x0.0p+0");
1113 }
1114
1115 m = frexp(fabs(x), &e);
1116 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1117 m = ldexp(m, shift);
1118 e -= shift;
1119
1120 si = 0;
1121 s[si] = char_from_hex((int)m);
1122 si++;
1123 m -= (int)m;
1124 s[si] = '.';
1125 si++;
1126 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1127 m *= 16.0;
1128 s[si] = char_from_hex((int)m);
1129 si++;
1130 m -= (int)m;
1131 }
1132 s[si] = '\0';
1133
1134 if (e < 0) {
1135 esign = (int)'-';
1136 e = -e;
1137 }
1138 else
1139 esign = (int)'+';
1140
1141 if (x < 0.0)
1142 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1143 else
1144 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1145}
1146
1147PyDoc_STRVAR(float_hex_doc,
1148"float.hex() -> string\n\
1149\n\
1150Return a hexadecimal representation of a floating-point number.\n\
1151>>> (-0.1).hex()\n\
1152'-0x1.999999999999ap-4'\n\
1153>>> 3.14159.hex()\n\
1154'0x1.921f9f01b866ep+1'");
1155
1156/* Convert a hexadecimal string to a float. */
1157
1158static PyObject *
1159float_fromhex(PyObject *cls, PyObject *arg)
1160{
1161 PyObject *result_as_float, *result;
1162 double x;
1163 long exp, top_exp, lsb, key_digit;
1164 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001165 int half_eps, digit, round_up, negate=0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001166 Py_ssize_t length, ndigits, fdigits, i;
1167
1168 /*
1169 * For the sake of simplicity and correctness, we impose an artificial
1170 * limit on ndigits, the total number of hex digits in the coefficient
1171 * The limit is chosen to ensure that, writing exp for the exponent,
1172 *
1173 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1174 * guaranteed to overflow (provided it's nonzero)
1175 *
1176 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1177 * guaranteed to underflow to 0.
1178 *
1179 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1180 * overflow in the calculation of exp and top_exp below.
1181 *
1182 * More specifically, ndigits is assumed to satisfy the following
1183 * inequalities:
1184 *
1185 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1186 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1187 *
1188 * If either of these inequalities is not satisfied, a ValueError is
1189 * raised. Otherwise, write x for the value of the hex string, and
1190 * assume x is nonzero. Then
1191 *
1192 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1193 *
1194 * Now if exp > LONG_MAX/2 then:
1195 *
1196 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1197 * = DBL_MAX_EXP
1198 *
1199 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1200 * double, so overflows. If exp < LONG_MIN/2, then
1201 *
1202 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1203 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1204 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1205 *
1206 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1207 * when converted to a C double.
1208 *
1209 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1210 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1211 */
1212
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001213 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001214 if (s == NULL)
1215 return NULL;
1216 s_end = s + length;
1217
1218 /********************
1219 * Parse the string *
1220 ********************/
1221
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001222 /* leading whitespace */
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001223 while (Py_ISSPACE(*s))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001224 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001225
1226 /* infinities and nans */
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001227 x = _Py_parse_inf_or_nan(s, &coeff_end);
1228 if (coeff_end != s) {
1229 s = coeff_end;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001230 goto finished;
1231 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001232
1233 /* optional sign */
1234 if (*s == '-') {
1235 s++;
1236 negate = 1;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001237 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001238 else if (*s == '+')
1239 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001240
1241 /* [0x] */
1242 s_store = s;
1243 if (*s == '0') {
1244 s++;
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001245 if (*s == 'x' || *s == 'X')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001246 s++;
1247 else
1248 s = s_store;
1249 }
1250
1251 /* coefficient: <integer> [. <fraction>] */
1252 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001253 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001254 s++;
1255 s_store = s;
1256 if (*s == '.') {
1257 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001258 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001259 s++;
1260 coeff_end = s-1;
1261 }
1262 else
1263 coeff_end = s;
1264
1265 /* ndigits = total # of hex digits; fdigits = # after point */
1266 ndigits = coeff_end - coeff_start;
1267 fdigits = coeff_end - s_store;
1268 if (ndigits == 0)
1269 goto parse_error;
1270 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1271 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1272 goto insane_length_error;
1273
1274 /* [p <exponent>] */
Mark Dickinsonaa77d262009-05-03 21:07:13 +00001275 if (*s == 'p' || *s == 'P') {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001276 s++;
1277 exp_start = s;
1278 if (*s == '-' || *s == '+')
1279 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001280 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001281 goto parse_error;
1282 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001283 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001284 s++;
1285 exp = strtol(exp_start, NULL, 10);
1286 }
1287 else
1288 exp = 0;
1289
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001290/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1291#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1292 coeff_end-(j) : \
1293 coeff_end-1-(j)))
1294
1295 /*******************************************
1296 * Compute rounded value of the hex string *
1297 *******************************************/
1298
1299 /* Discard leading zeros, and catch extreme overflow and underflow */
1300 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1301 ndigits--;
1302 if (ndigits == 0 || exp < LONG_MIN/2) {
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001303 x = 0.0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001304 goto finished;
1305 }
1306 if (exp > LONG_MAX/2)
1307 goto overflow_error;
1308
1309 /* Adjust exponent for fractional part. */
1310 exp = exp - 4*((long)fdigits);
1311
1312 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1313 top_exp = exp + 4*((long)ndigits - 1);
1314 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1315 top_exp++;
1316
1317 /* catch almost all nonextreme cases of overflow and underflow here */
1318 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001319 x = 0.0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001320 goto finished;
1321 }
1322 if (top_exp > DBL_MAX_EXP)
1323 goto overflow_error;
1324
1325 /* lsb = exponent of least significant bit of the *rounded* value.
1326 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1327 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1328
1329 x = 0.0;
1330 if (exp >= lsb) {
1331 /* no rounding required */
1332 for (i = ndigits-1; i >= 0; i--)
1333 x = 16.0*x + HEX_DIGIT(i);
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001334 x = ldexp(x, (int)(exp));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001335 goto finished;
1336 }
1337 /* rounding required. key_digit is the index of the hex digit
1338 containing the first bit to be rounded away. */
1339 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1340 key_digit = (lsb - exp - 1) / 4;
1341 for (i = ndigits-1; i > key_digit; i--)
1342 x = 16.0*x + HEX_DIGIT(i);
1343 digit = HEX_DIGIT(key_digit);
1344 x = 16.0*x + (double)(digit & (16-2*half_eps));
1345
1346 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1347 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1348 if ((digit & half_eps) != 0) {
1349 round_up = 0;
1350 if ((digit & (3*half_eps-1)) != 0 ||
1351 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1352 round_up = 1;
1353 else
1354 for (i = key_digit-1; i >= 0; i--)
1355 if (HEX_DIGIT(i) != 0) {
1356 round_up = 1;
1357 break;
1358 }
1359 if (round_up == 1) {
1360 x += 2*half_eps;
1361 if (top_exp == DBL_MAX_EXP &&
1362 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1363 /* overflow corner case: pre-rounded value <
1364 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1365 goto overflow_error;
1366 }
1367 }
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001368 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001369
1370 finished:
Mark Dickinsond1ec8b22009-05-11 15:45:15 +00001371 /* optional trailing whitespace leading to the end of the string */
1372 while (Py_ISSPACE(*s))
1373 s++;
1374 if (s != s_end)
1375 goto parse_error;
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001376 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001377 if (result_as_float == NULL)
1378 return NULL;
1379 result = PyObject_CallObject(cls, result_as_float);
1380 Py_DECREF(result_as_float);
1381 return result;
1382
1383 overflow_error:
1384 PyErr_SetString(PyExc_OverflowError,
1385 "hexadecimal value too large to represent as a float");
1386 return NULL;
1387
1388 parse_error:
1389 PyErr_SetString(PyExc_ValueError,
1390 "invalid hexadecimal floating-point string");
1391 return NULL;
1392
1393 insane_length_error:
1394 PyErr_SetString(PyExc_ValueError,
1395 "hexadecimal string too long to convert");
1396 return NULL;
1397}
1398
1399PyDoc_STRVAR(float_fromhex_doc,
1400"float.fromhex(string) -> float\n\
1401\n\
1402Create a floating-point number from a hexadecimal string.\n\
1403>>> float.fromhex('0x1.ffffp10')\n\
14042047.984375\n\
1405>>> float.fromhex('-0x1p-1074')\n\
1406-4.9406564584124654e-324");
1407
1408
Christian Heimes26855632008-01-27 23:50:43 +00001409static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001410float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001411{
1412 double self;
1413 double float_part;
1414 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001415 int i;
1416
Christian Heimes26855632008-01-27 23:50:43 +00001417 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001418 PyObject *py_exponent = NULL;
1419 PyObject *numerator = NULL;
1420 PyObject *denominator = NULL;
1421 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001422 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001423
1424#define INPLACE_UPDATE(obj, call) \
1425 prev = obj; \
1426 obj = call; \
1427 Py_DECREF(prev); \
1428
1429 CONVERT_TO_DOUBLE(v, self);
1430
1431 if (Py_IS_INFINITY(self)) {
1432 PyErr_SetString(PyExc_OverflowError,
1433 "Cannot pass infinity to float.as_integer_ratio.");
1434 return NULL;
1435 }
1436#ifdef Py_NAN
1437 if (Py_IS_NAN(self)) {
1438 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001439 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001440 return NULL;
1441 }
1442#endif
1443
Christian Heimes26855632008-01-27 23:50:43 +00001444 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001445 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001446 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001447
1448 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1449 float_part *= 2.0;
1450 exponent--;
1451 }
1452 /* self == float_part * 2**exponent exactly and float_part is integral.
1453 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1454 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001455
Christian Heimes292d3512008-02-03 16:51:08 +00001456 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001457 if (numerator == NULL) goto error;
1458
Christian Heimes292d3512008-02-03 16:51:08 +00001459 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001460 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001461 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001462 if (py_exponent == NULL) goto error;
1463 INPLACE_UPDATE(py_exponent,
1464 long_methods->nb_lshift(denominator, py_exponent));
1465 if (py_exponent == NULL) goto error;
1466 if (exponent > 0) {
1467 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001468 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001469 if (numerator == NULL) goto error;
1470 }
1471 else {
1472 Py_DECREF(denominator);
1473 denominator = py_exponent;
1474 py_exponent = NULL;
1475 }
1476
1477 result_pair = PyTuple_Pack(2, numerator, denominator);
1478
1479#undef INPLACE_UPDATE
1480error:
1481 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001482 Py_XDECREF(denominator);
1483 Py_XDECREF(numerator);
1484 return result_pair;
1485}
1486
1487PyDoc_STRVAR(float_as_integer_ratio_doc,
1488"float.as_integer_ratio() -> (int, int)\n"
1489"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001490"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1491"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001492"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001493"\n"
1494">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001495"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001496">>> (0.0).as_integer_ratio()\n"
1497"(0, 1)\n"
1498">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001499"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001500
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001501
Jeremy Hylton938ace62002-07-17 16:30:39 +00001502static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001503float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1504
Tim Peters6d6c1a32001-08-02 04:15:00 +00001505static PyObject *
1506float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1507{
1508 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001509 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510
Guido van Rossumbef14172001-08-29 15:47:46 +00001511 if (type != &PyFloat_Type)
1512 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1514 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001515 /* If it's a string, but not a string subclass, use
1516 PyFloat_FromString. */
1517 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001518 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 return PyNumber_Float(x);
1520}
1521
Guido van Rossumbef14172001-08-29 15:47:46 +00001522/* Wimpy, slow approach to tp_new calls for subtypes of float:
1523 first create a regular float from whatever arguments we got,
1524 then allocate a subtype instance and initialize its ob_fval
1525 from the regular float. The regular float is then thrown away.
1526*/
1527static PyObject *
1528float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1529{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001530 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001531
1532 assert(PyType_IsSubtype(type, &PyFloat_Type));
1533 tmp = float_new(&PyFloat_Type, args, kwds);
1534 if (tmp == NULL)
1535 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001536 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001537 newobj = type->tp_alloc(type, 0);
1538 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001539 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001540 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001541 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001542 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001543 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001544 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001545}
1546
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001547static PyObject *
1548float_getnewargs(PyFloatObject *v)
1549{
1550 return Py_BuildValue("(d)", v->ob_fval);
1551}
1552
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001553/* this is for the benefit of the pack/unpack routines below */
1554
1555typedef enum {
1556 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1557} float_format_type;
1558
1559static float_format_type double_format, float_format;
1560static float_format_type detected_double_format, detected_float_format;
1561
1562static PyObject *
1563float_getformat(PyTypeObject *v, PyObject* arg)
1564{
1565 char* s;
1566 float_format_type r;
1567
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001568 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001569 PyErr_Format(PyExc_TypeError,
1570 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001571 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001572 return NULL;
1573 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001574 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001575 if (s == NULL)
1576 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001577 if (strcmp(s, "double") == 0) {
1578 r = double_format;
1579 }
1580 else if (strcmp(s, "float") == 0) {
1581 r = float_format;
1582 }
1583 else {
1584 PyErr_SetString(PyExc_ValueError,
1585 "__getformat__() argument 1 must be "
1586 "'double' or 'float'");
1587 return NULL;
1588 }
1589
1590 switch (r) {
1591 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001592 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001593 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001594 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001595 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001596 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597 default:
1598 Py_FatalError("insane float_format or double_format");
1599 return NULL;
1600 }
1601}
1602
1603PyDoc_STRVAR(float_getformat_doc,
1604"float.__getformat__(typestr) -> string\n"
1605"\n"
1606"You probably don't want to use this function. It exists mainly to be\n"
1607"used in Python's test suite.\n"
1608"\n"
1609"typestr must be 'double' or 'float'. This function returns whichever of\n"
1610"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1611"format of floating point numbers used by the C type named by typestr.");
1612
1613static PyObject *
1614float_setformat(PyTypeObject *v, PyObject* args)
1615{
1616 char* typestr;
1617 char* format;
1618 float_format_type f;
1619 float_format_type detected;
1620 float_format_type *p;
1621
1622 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1623 return NULL;
1624
1625 if (strcmp(typestr, "double") == 0) {
1626 p = &double_format;
1627 detected = detected_double_format;
1628 }
1629 else if (strcmp(typestr, "float") == 0) {
1630 p = &float_format;
1631 detected = detected_float_format;
1632 }
1633 else {
1634 PyErr_SetString(PyExc_ValueError,
1635 "__setformat__() argument 1 must "
1636 "be 'double' or 'float'");
1637 return NULL;
1638 }
1639
1640 if (strcmp(format, "unknown") == 0) {
1641 f = unknown_format;
1642 }
1643 else if (strcmp(format, "IEEE, little-endian") == 0) {
1644 f = ieee_little_endian_format;
1645 }
1646 else if (strcmp(format, "IEEE, big-endian") == 0) {
1647 f = ieee_big_endian_format;
1648 }
1649 else {
1650 PyErr_SetString(PyExc_ValueError,
1651 "__setformat__() argument 2 must be "
1652 "'unknown', 'IEEE, little-endian' or "
1653 "'IEEE, big-endian'");
1654 return NULL;
1655
1656 }
1657
1658 if (f != unknown_format && f != detected) {
1659 PyErr_Format(PyExc_ValueError,
1660 "can only set %s format to 'unknown' or the "
1661 "detected platform value", typestr);
1662 return NULL;
1663 }
1664
1665 *p = f;
1666 Py_RETURN_NONE;
1667}
1668
1669PyDoc_STRVAR(float_setformat_doc,
1670"float.__setformat__(typestr, fmt) -> None\n"
1671"\n"
1672"You probably don't want to use this function. It exists mainly to be\n"
1673"used in Python's test suite.\n"
1674"\n"
1675"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1676"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1677"one of the latter two if it appears to match the underlying C reality.\n"
1678"\n"
1679"Overrides the automatic determination of C-level floating point type.\n"
1680"This affects how floats are converted to and from binary strings.");
1681
Guido van Rossumb43daf72007-08-01 18:08:08 +00001682static PyObject *
1683float_getzero(PyObject *v, void *closure)
1684{
1685 return PyFloat_FromDouble(0.0);
1686}
1687
Eric Smith8c663262007-08-25 02:26:07 +00001688static PyObject *
1689float__format__(PyObject *self, PyObject *args)
1690{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001691 PyObject *format_spec;
1692
1693 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1694 return NULL;
1695 return _PyFloat_FormatAdvanced(self,
1696 PyUnicode_AS_UNICODE(format_spec),
1697 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001698}
1699
1700PyDoc_STRVAR(float__format__doc,
1701"float.__format__(format_spec) -> string\n"
1702"\n"
1703"Formats the float according to format_spec.");
1704
1705
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001706static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001707 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001708 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001709 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1710 "Returns the Integral closest to x between 0 and x."},
1711 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1712 "Returns the Integral closest to x, rounding half toward even.\n"
1713 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001714 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1715 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001716 {"fromhex", (PyCFunction)float_fromhex,
1717 METH_O|METH_CLASS, float_fromhex_doc},
1718 {"hex", (PyCFunction)float_hex,
1719 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001720 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1721 "Returns True if the float is an integer."},
1722#if 0
1723 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1724 "Returns True if the float is positive or negative infinite."},
1725 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1726 "Returns True if the float is finite, neither infinite nor NaN."},
1727 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1728 "Returns True if the float is not a number (NaN)."},
1729#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001730 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731 {"__getformat__", (PyCFunction)float_getformat,
1732 METH_O|METH_CLASS, float_getformat_doc},
1733 {"__setformat__", (PyCFunction)float_setformat,
1734 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001735 {"__format__", (PyCFunction)float__format__,
1736 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001737 {NULL, NULL} /* sentinel */
1738};
1739
Guido van Rossumb43daf72007-08-01 18:08:08 +00001740static PyGetSetDef float_getset[] = {
1741 {"real",
1742 (getter)float_float, (setter)NULL,
1743 "the real part of a complex number",
1744 NULL},
1745 {"imag",
1746 (getter)float_getzero, (setter)NULL,
1747 "the imaginary part of a complex number",
1748 NULL},
1749 {NULL} /* Sentinel */
1750};
1751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001752PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753"float(x) -> floating point number\n\
1754\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001755Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756
1757
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001759 float_add, /*nb_add*/
1760 float_sub, /*nb_subtract*/
1761 float_mul, /*nb_multiply*/
1762 float_rem, /*nb_remainder*/
1763 float_divmod, /*nb_divmod*/
1764 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001765 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001766 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001767 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001768 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001769 0, /*nb_invert*/
1770 0, /*nb_lshift*/
1771 0, /*nb_rshift*/
1772 0, /*nb_and*/
1773 0, /*nb_xor*/
1774 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001775 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001776 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001777 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001778 0, /* nb_inplace_add */
1779 0, /* nb_inplace_subtract */
1780 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001781 0, /* nb_inplace_remainder */
1782 0, /* nb_inplace_power */
1783 0, /* nb_inplace_lshift */
1784 0, /* nb_inplace_rshift */
1785 0, /* nb_inplace_and */
1786 0, /* nb_inplace_xor */
1787 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001788 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001789 float_div, /* nb_true_divide */
1790 0, /* nb_inplace_floor_divide */
1791 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001792};
1793
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001794PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001795 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001796 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001797 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001798 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001800 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 0, /* tp_getattr */
1802 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001803 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804 (reprfunc)float_repr, /* tp_repr */
1805 &float_as_number, /* tp_as_number */
1806 0, /* tp_as_sequence */
1807 0, /* tp_as_mapping */
1808 (hashfunc)float_hash, /* tp_hash */
1809 0, /* tp_call */
1810 (reprfunc)float_str, /* tp_str */
1811 PyObject_GenericGetAttr, /* tp_getattro */
1812 0, /* tp_setattro */
1813 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001814 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815 float_doc, /* tp_doc */
1816 0, /* tp_traverse */
1817 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001818 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819 0, /* tp_weaklistoffset */
1820 0, /* tp_iter */
1821 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001822 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001824 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 0, /* tp_base */
1826 0, /* tp_dict */
1827 0, /* tp_descr_get */
1828 0, /* tp_descr_set */
1829 0, /* tp_dictoffset */
1830 0, /* tp_init */
1831 0, /* tp_alloc */
1832 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001833};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001834
1835void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001836_PyFloat_Init(void)
1837{
1838 /* We attempt to determine if this machine is using IEEE
1839 floating point formats by peering at the bits of some
1840 carefully chosen values. If it looks like we are on an
1841 IEEE platform, the float packing/unpacking routines can
1842 just copy bits, if not they resort to arithmetic & shifts
1843 and masks. The shifts & masks approach works on all finite
1844 values, but what happens to infinities, NaNs and signed
1845 zeroes on packing is an accident, and attempting to unpack
1846 a NaN or an infinity will raise an exception.
1847
1848 Note that if we're on some whacked-out platform which uses
1849 IEEE formats but isn't strictly little-endian or big-
1850 endian, we will fall back to the portable shifts & masks
1851 method. */
1852
1853#if SIZEOF_DOUBLE == 8
1854 {
1855 double x = 9006104071832581.0;
1856 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1857 detected_double_format = ieee_big_endian_format;
1858 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1859 detected_double_format = ieee_little_endian_format;
1860 else
1861 detected_double_format = unknown_format;
1862 }
1863#else
1864 detected_double_format = unknown_format;
1865#endif
1866
1867#if SIZEOF_FLOAT == 4
1868 {
1869 float y = 16711938.0;
1870 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1871 detected_float_format = ieee_big_endian_format;
1872 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1873 detected_float_format = ieee_little_endian_format;
1874 else
1875 detected_float_format = unknown_format;
1876 }
1877#else
1878 detected_float_format = unknown_format;
1879#endif
1880
1881 double_format = detected_double_format;
1882 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001883
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001884 /* Init float info */
1885 if (FloatInfoType.tp_name == 0)
1886 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887}
1888
Georg Brandl2ee470f2008-07-16 12:55:28 +00001889int
1890PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001891{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001892 PyFloatObject *p;
1893 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001894 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001895 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001896 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001897
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001898 list = block_list;
1899 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001900 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001901 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001902 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001903 for (i = 0, p = &list->objects[0];
1904 i < N_FLOATOBJECTS;
1905 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001906 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001907 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001908 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001909 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001910 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001911 list->next = block_list;
1912 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001913 for (i = 0, p = &list->objects[0];
1914 i < N_FLOATOBJECTS;
1915 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001916 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001917 Py_REFCNT(p) == 0) {
1918 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001919 free_list;
1920 free_list = p;
1921 }
1922 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001923 }
1924 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001925 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001926 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001927 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001928 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001929 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001930 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001931}
1932
1933void
1934PyFloat_Fini(void)
1935{
1936 PyFloatObject *p;
1937 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001938 int i;
1939 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001940
Georg Brandl2ee470f2008-07-16 12:55:28 +00001941 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001942
Guido van Rossum3fce8831999-03-12 19:43:17 +00001943 if (!Py_VerboseFlag)
1944 return;
1945 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001946 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001947 fprintf(stderr, "\n");
1948 }
1949 else {
1950 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001951 ": %d unfreed float%s\n",
1952 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001953 }
1954 if (Py_VerboseFlag > 1) {
1955 list = block_list;
1956 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001957 for (i = 0, p = &list->objects[0];
1958 i < N_FLOATOBJECTS;
1959 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001960 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001961 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00001962 char *buf = PyOS_double_to_string(
1963 PyFloat_AS_DOUBLE(p), 'r',
1964 0, 0, NULL);
1965 if (buf) {
1966 /* XXX(twouters) cast
1967 refcount to long
1968 until %zd is
1969 universally
1970 available
1971 */
1972 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001973 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001974 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00001975 PyMem_Free(buf);
1976 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001977 }
1978 }
1979 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001980 }
1981 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001982}
Tim Peters9905b942003-03-20 20:53:32 +00001983
1984/*----------------------------------------------------------------------------
1985 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001986 */
1987int
1988_PyFloat_Pack4(double x, unsigned char *p, int le)
1989{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001990 if (float_format == unknown_format) {
1991 unsigned char sign;
1992 int e;
1993 double f;
1994 unsigned int fbits;
1995 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001996
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997 if (le) {
1998 p += 3;
1999 incr = -1;
2000 }
Tim Peters9905b942003-03-20 20:53:32 +00002001
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002002 if (x < 0) {
2003 sign = 1;
2004 x = -x;
2005 }
2006 else
2007 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002008
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002010
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002011 /* Normalize f to be in the range [1.0, 2.0) */
2012 if (0.5 <= f && f < 1.0) {
2013 f *= 2.0;
2014 e--;
2015 }
2016 else if (f == 0.0)
2017 e = 0;
2018 else {
2019 PyErr_SetString(PyExc_SystemError,
2020 "frexp() result out of range");
2021 return -1;
2022 }
2023
2024 if (e >= 128)
2025 goto Overflow;
2026 else if (e < -126) {
2027 /* Gradual underflow */
2028 f = ldexp(f, 126 + e);
2029 e = 0;
2030 }
2031 else if (!(e == 0 && f == 0.0)) {
2032 e += 127;
2033 f -= 1.0; /* Get rid of leading 1 */
2034 }
2035
2036 f *= 8388608.0; /* 2**23 */
2037 fbits = (unsigned int)(f + 0.5); /* Round */
2038 assert(fbits <= 8388608);
2039 if (fbits >> 23) {
2040 /* The carry propagated out of a string of 23 1 bits. */
2041 fbits = 0;
2042 ++e;
2043 if (e >= 255)
2044 goto Overflow;
2045 }
2046
2047 /* First byte */
2048 *p = (sign << 7) | (e >> 1);
2049 p += incr;
2050
2051 /* Second byte */
2052 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2053 p += incr;
2054
2055 /* Third byte */
2056 *p = (fbits >> 8) & 0xFF;
2057 p += incr;
2058
2059 /* Fourth byte */
2060 *p = fbits & 0xFF;
2061
2062 /* Done */
2063 return 0;
2064
Tim Peters9905b942003-03-20 20:53:32 +00002065 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002066 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002067 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002068 const char *s = (char*)&y;
2069 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002070
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002071 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2072 goto Overflow;
2073
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002074 if ((float_format == ieee_little_endian_format && !le)
2075 || (float_format == ieee_big_endian_format && le)) {
2076 p += 3;
2077 incr = -1;
2078 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002079
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002080 for (i = 0; i < 4; i++) {
2081 *p = *s++;
2082 p += incr;
2083 }
2084 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002085 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002086 Overflow:
2087 PyErr_SetString(PyExc_OverflowError,
2088 "float too large to pack with f format");
2089 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002090}
2091
2092int
2093_PyFloat_Pack8(double x, unsigned char *p, int le)
2094{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002095 if (double_format == unknown_format) {
2096 unsigned char sign;
2097 int e;
2098 double f;
2099 unsigned int fhi, flo;
2100 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002101
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102 if (le) {
2103 p += 7;
2104 incr = -1;
2105 }
Tim Peters9905b942003-03-20 20:53:32 +00002106
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107 if (x < 0) {
2108 sign = 1;
2109 x = -x;
2110 }
2111 else
2112 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002113
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002115
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002116 /* Normalize f to be in the range [1.0, 2.0) */
2117 if (0.5 <= f && f < 1.0) {
2118 f *= 2.0;
2119 e--;
2120 }
2121 else if (f == 0.0)
2122 e = 0;
2123 else {
2124 PyErr_SetString(PyExc_SystemError,
2125 "frexp() result out of range");
2126 return -1;
2127 }
2128
2129 if (e >= 1024)
2130 goto Overflow;
2131 else if (e < -1022) {
2132 /* Gradual underflow */
2133 f = ldexp(f, 1022 + e);
2134 e = 0;
2135 }
2136 else if (!(e == 0 && f == 0.0)) {
2137 e += 1023;
2138 f -= 1.0; /* Get rid of leading 1 */
2139 }
2140
2141 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2142 f *= 268435456.0; /* 2**28 */
2143 fhi = (unsigned int)f; /* Truncate */
2144 assert(fhi < 268435456);
2145
2146 f -= (double)fhi;
2147 f *= 16777216.0; /* 2**24 */
2148 flo = (unsigned int)(f + 0.5); /* Round */
2149 assert(flo <= 16777216);
2150 if (flo >> 24) {
2151 /* The carry propagated out of a string of 24 1 bits. */
2152 flo = 0;
2153 ++fhi;
2154 if (fhi >> 28) {
2155 /* And it also progagated out of the next 28 bits. */
2156 fhi = 0;
2157 ++e;
2158 if (e >= 2047)
2159 goto Overflow;
2160 }
2161 }
2162
2163 /* First byte */
2164 *p = (sign << 7) | (e >> 4);
2165 p += incr;
2166
2167 /* Second byte */
2168 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2169 p += incr;
2170
2171 /* Third byte */
2172 *p = (fhi >> 16) & 0xFF;
2173 p += incr;
2174
2175 /* Fourth byte */
2176 *p = (fhi >> 8) & 0xFF;
2177 p += incr;
2178
2179 /* Fifth byte */
2180 *p = fhi & 0xFF;
2181 p += incr;
2182
2183 /* Sixth byte */
2184 *p = (flo >> 16) & 0xFF;
2185 p += incr;
2186
2187 /* Seventh byte */
2188 *p = (flo >> 8) & 0xFF;
2189 p += incr;
2190
2191 /* Eighth byte */
2192 *p = flo & 0xFF;
2193 p += incr;
2194
2195 /* Done */
2196 return 0;
2197
2198 Overflow:
2199 PyErr_SetString(PyExc_OverflowError,
2200 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002201 return -1;
2202 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002203 else {
2204 const char *s = (char*)&x;
2205 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002206
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002207 if ((double_format == ieee_little_endian_format && !le)
2208 || (double_format == ieee_big_endian_format && le)) {
2209 p += 7;
2210 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002211 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002212
2213 for (i = 0; i < 8; i++) {
2214 *p = *s++;
2215 p += incr;
2216 }
2217 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002218 }
Tim Peters9905b942003-03-20 20:53:32 +00002219}
2220
2221double
2222_PyFloat_Unpack4(const unsigned char *p, int le)
2223{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224 if (float_format == unknown_format) {
2225 unsigned char sign;
2226 int e;
2227 unsigned int f;
2228 double x;
2229 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002230
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231 if (le) {
2232 p += 3;
2233 incr = -1;
2234 }
2235
2236 /* First byte */
2237 sign = (*p >> 7) & 1;
2238 e = (*p & 0x7F) << 1;
2239 p += incr;
2240
2241 /* Second byte */
2242 e |= (*p >> 7) & 1;
2243 f = (*p & 0x7F) << 16;
2244 p += incr;
2245
2246 if (e == 255) {
2247 PyErr_SetString(
2248 PyExc_ValueError,
2249 "can't unpack IEEE 754 special value "
2250 "on non-IEEE platform");
2251 return -1;
2252 }
2253
2254 /* Third byte */
2255 f |= *p << 8;
2256 p += incr;
2257
2258 /* Fourth byte */
2259 f |= *p;
2260
2261 x = (double)f / 8388608.0;
2262
2263 /* XXX This sadly ignores Inf/NaN issues */
2264 if (e == 0)
2265 e = -126;
2266 else {
2267 x += 1.0;
2268 e -= 127;
2269 }
2270 x = ldexp(x, e);
2271
2272 if (sign)
2273 x = -x;
2274
2275 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002276 }
Tim Peters9905b942003-03-20 20:53:32 +00002277 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002278 float x;
2279
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002280 if ((float_format == ieee_little_endian_format && !le)
2281 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002282 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002283 char *d = &buf[3];
2284 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002285
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286 for (i = 0; i < 4; i++) {
2287 *d-- = *p++;
2288 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002289 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002290 }
2291 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002292 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002293 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002294
2295 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296 }
Tim Peters9905b942003-03-20 20:53:32 +00002297}
2298
2299double
2300_PyFloat_Unpack8(const unsigned char *p, int le)
2301{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302 if (double_format == unknown_format) {
2303 unsigned char sign;
2304 int e;
2305 unsigned int fhi, flo;
2306 double x;
2307 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002308
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002309 if (le) {
2310 p += 7;
2311 incr = -1;
2312 }
2313
2314 /* First byte */
2315 sign = (*p >> 7) & 1;
2316 e = (*p & 0x7F) << 4;
2317
2318 p += incr;
2319
2320 /* Second byte */
2321 e |= (*p >> 4) & 0xF;
2322 fhi = (*p & 0xF) << 24;
2323 p += incr;
2324
2325 if (e == 2047) {
2326 PyErr_SetString(
2327 PyExc_ValueError,
2328 "can't unpack IEEE 754 special value "
2329 "on non-IEEE platform");
2330 return -1.0;
2331 }
2332
2333 /* Third byte */
2334 fhi |= *p << 16;
2335 p += incr;
2336
2337 /* Fourth byte */
2338 fhi |= *p << 8;
2339 p += incr;
2340
2341 /* Fifth byte */
2342 fhi |= *p;
2343 p += incr;
2344
2345 /* Sixth byte */
2346 flo = *p << 16;
2347 p += incr;
2348
2349 /* Seventh byte */
2350 flo |= *p << 8;
2351 p += incr;
2352
2353 /* Eighth byte */
2354 flo |= *p;
2355
2356 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2357 x /= 268435456.0; /* 2**28 */
2358
2359 if (e == 0)
2360 e = -1022;
2361 else {
2362 x += 1.0;
2363 e -= 1023;
2364 }
2365 x = ldexp(x, e);
2366
2367 if (sign)
2368 x = -x;
2369
2370 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002371 }
Tim Peters9905b942003-03-20 20:53:32 +00002372 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002373 double x;
2374
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002375 if ((double_format == ieee_little_endian_format && !le)
2376 || (double_format == ieee_big_endian_format && le)) {
2377 char buf[8];
2378 char *d = &buf[7];
2379 int i;
2380
2381 for (i = 0; i < 8; i++) {
2382 *d-- = *p++;
2383 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002384 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002385 }
2386 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002387 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002388 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002389
2390 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002391 }
Tim Peters9905b942003-03-20 20:53:32 +00002392}