blob: 061987722ce23f540ddd9bc99f2d5a3f0e428bbb [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Christian Heimesbbe741d2008-03-28 10:53:29 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Guido van Rossum6923e131990-11-02 17:50:43 +000022
Christian Heimes969fe572008-01-25 11:23:10 +000023#ifdef _OSF_SOURCE
24/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
25extern int finite(double);
26#endif
27
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000029#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000030#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000031#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000032
Guido van Rossum3fce8831999-03-12 19:43:17 +000033struct _floatblock {
34 struct _floatblock *next;
35 PyFloatObject objects[N_FLOATOBJECTS];
36};
37
38typedef struct _floatblock PyFloatBlock;
39
40static PyFloatBlock *block_list = NULL;
41static PyFloatObject *free_list = NULL;
42
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000044fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045{
46 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
48 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000050 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000051 ((PyFloatBlock *)p)->next = block_list;
52 block_list = (PyFloatBlock *)p;
53 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 q = p + N_FLOATOBJECTS;
55 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000056 Py_TYPE(q) = (struct _typeobject *)(q-1);
57 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 return p + N_FLOATOBJECTS - 1;
59}
60
Christian Heimes93852662007-12-01 12:22:32 +000061double
62PyFloat_GetMax(void)
63{
64 return DBL_MAX;
65}
66
67double
68PyFloat_GetMin(void)
69{
70 return DBL_MIN;
71}
72
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073static PyTypeObject FloatInfoType;
74
75PyDoc_STRVAR(floatinfo__doc__,
76"sys.floatinfo\n\
77\n\
78A structseq holding information about the float type. It contains low level\n\
79information about the precision and internal representation. Please study\n\
80your system's :file:`float.h` for more information.");
81
82static PyStructSequence_Field floatinfo_fields[] = {
83 {"max", "DBL_MAX -- maximum representable finite float"},
84 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
85 "is representable"},
86 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
87 "is representable"},
88 {"min", "DBL_MIN -- Minimum positive normalizer float"},
89 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
90 "is a normalized float"},
91 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
92 "a normalized"},
93 {"dig", "DBL_DIG -- digits"},
94 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
95 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
96 "representable float"},
97 {"radix", "FLT_RADIX -- radix of exponent"},
98 {"rounds", "FLT_ROUNDS -- addition rounds"},
99 {0}
100};
101
102static PyStructSequence_Desc floatinfo_desc = {
103 "sys.floatinfo", /* name */
104 floatinfo__doc__, /* doc */
105 floatinfo_fields, /* fields */
106 11
107};
108
Christian Heimes93852662007-12-01 12:22:32 +0000109PyObject *
110PyFloat_GetInfo(void)
111{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000112 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000113 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000114
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000115 floatinfo = PyStructSequence_New(&FloatInfoType);
116 if (floatinfo == NULL) {
117 return NULL;
118 }
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120#define SetIntFlag(flag) \
121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
122#define SetDblFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125 SetDblFlag(DBL_MAX);
126 SetIntFlag(DBL_MAX_EXP);
127 SetIntFlag(DBL_MAX_10_EXP);
128 SetDblFlag(DBL_MIN);
129 SetIntFlag(DBL_MIN_EXP);
130 SetIntFlag(DBL_MIN_10_EXP);
131 SetIntFlag(DBL_DIG);
132 SetIntFlag(DBL_MANT_DIG);
133 SetDblFlag(DBL_EPSILON);
134 SetIntFlag(FLT_RADIX);
135 SetIntFlag(FLT_ROUNDS);
136#undef SetIntFlag
137#undef SetDblFlag
138
139 if (PyErr_Occurred()) {
140 Py_CLEAR(floatinfo);
141 return NULL;
142 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000143 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000144}
145
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000154 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000155 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000163PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164{
Mark Dickinson6d65df12009-04-26 15:30:47 +0000165 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000167 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000172 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000178 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000180 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000181 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000183 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000186 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000189 last = s + len;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000190
Mark Dickinson33242472009-04-18 20:19:17 +0000191 while (*s && isspace(Py_CHARMASK(*s)))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 s++;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000193 /* We don't care about overflow or underflow. If the platform
194 * supports them, infinities and signed zeroes (on underflow) are
195 * fine. */
Mark Dickinson725bfd82009-05-03 20:33:40 +0000196 x = PyOS_string_to_double(s, (char **)&end, NULL);
197 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum2be161d2007-05-15 20:43:51 +0000198 goto error;
Mark Dickinson33242472009-04-18 20:19:17 +0000199 while (*end && isspace(Py_CHARMASK(*end)))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000200 end++;
Mark Dickinson725bfd82009-05-03 20:33:40 +0000201 if (end == last)
202 result = PyFloat_FromDouble(x);
203 else {
204 PyOS_snprintf(buffer, sizeof(buffer),
205 "invalid literal for float(): %.200s", s);
206 PyErr_SetString(PyExc_ValueError, buffer);
207 result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 }
Mark Dickinson725bfd82009-05-03 20:33:40 +0000209
Guido van Rossum2be161d2007-05-15 20:43:51 +0000210 error:
211 if (s_buffer)
212 PyMem_FREE(s_buffer);
213 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214}
215
Guido van Rossum234f9421993-06-17 12:35:49 +0000216static void
Fred Drakefd99de62000-07-09 05:02:18 +0000217float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000218{
Guido van Rossum9475a232001-10-05 20:51:39 +0000219 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000220 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000221 free_list = op;
222 }
223 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000224 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000225}
226
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227double
Fred Drakefd99de62000-07-09 05:02:18 +0000228PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230 PyNumberMethods *nb;
231 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000233
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (op && PyFloat_Check(op))
235 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000236
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000237 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239 return -1;
240 }
Tim Petersd2364e82001-11-01 20:09:42 +0000241
Christian Heimes90aa7642007-12-19 02:45:37 +0000242 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000243 PyErr_SetString(PyExc_TypeError, "a float is required");
244 return -1;
245 }
246
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000248 if (fo == NULL)
249 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250 if (!PyFloat_Check(fo)) {
251 PyErr_SetString(PyExc_TypeError,
252 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000253 return -1;
254 }
Tim Petersd2364e82001-11-01 20:09:42 +0000255
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000256 val = PyFloat_AS_DOUBLE(fo);
257 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Guido van Rossumb6775db1994-08-01 11:34:53 +0000259 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Neil Schemenauer32117e52001-01-04 01:44:34 +0000262/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000263 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000264 set to NULL, and the function invoking this macro returns NULL. If
265 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
266 stored in obj, and returned from the function invoking this macro.
267*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000268#define CONVERT_TO_DOUBLE(obj, dbl) \
269 if (PyFloat_Check(obj)) \
270 dbl = PyFloat_AS_DOUBLE(obj); \
271 else if (convert_to_double(&(obj), &(dbl)) < 0) \
272 return obj;
273
Eric Smith0923d1d2009-04-16 20:16:10 +0000274/* Methods */
275
Neil Schemenauer32117e52001-01-04 01:44:34 +0000276static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000277convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278{
279 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000280
Guido van Rossumddefaf32007-01-14 03:31:43 +0000281 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000282 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000283 if (*dbl == -1.0 && PyErr_Occurred()) {
284 *v = NULL;
285 return -1;
286 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000287 }
288 else {
289 Py_INCREF(Py_NotImplemented);
290 *v = Py_NotImplemented;
291 return -1;
292 }
293 return 0;
294}
295
Eric Smith0923d1d2009-04-16 20:16:10 +0000296static PyObject *
297float_str_or_repr(PyFloatObject *v, char format_code)
298{
299 PyObject *result;
300 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
301 format_code, 0, Py_DTSF_ADD_DOT_0,
302 NULL);
303 if (!buf)
304 return PyErr_NoMemory();
305 result = PyUnicode_FromString(buf);
306 PyMem_Free(buf);
307 return result;
308}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000309
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000310static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000311float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312{
Eric Smith0923d1d2009-04-16 20:16:10 +0000313 return float_str_or_repr(v, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000314}
315
316static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000317float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000318{
Eric Smith0923d1d2009-04-16 20:16:10 +0000319 return float_str_or_repr(v, 's');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320}
321
Tim Peters307fa782004-09-23 08:06:40 +0000322/* Comparison is pretty much a nightmare. When comparing float to float,
323 * we do it as straightforwardly (and long-windedly) as conceivable, so
324 * that, e.g., Python x == y delivers the same result as the platform
325 * C x == y when x and/or y is a NaN.
326 * When mixing float with an integer type, there's no good *uniform* approach.
327 * Converting the double to an integer obviously doesn't work, since we
328 * may lose info from fractional bits. Converting the integer to a double
329 * also has two failure modes: (1) a long int may trigger overflow (too
330 * large to fit in the dynamic range of a C double); (2) even a C long may have
331 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
332 * 63 bits of precision, but a C double probably has only 53), and then
333 * we can falsely claim equality when low-order integer bits are lost by
334 * coercion to double. So this part is painful too.
335 */
336
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000337static PyObject*
338float_richcompare(PyObject *v, PyObject *w, int op)
339{
340 double i, j;
341 int r = 0;
342
Tim Peters307fa782004-09-23 08:06:40 +0000343 assert(PyFloat_Check(v));
344 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000345
Tim Peters307fa782004-09-23 08:06:40 +0000346 /* Switch on the type of w. Set i and j to doubles to be compared,
347 * and op to the richcomp to use.
348 */
349 if (PyFloat_Check(w))
350 j = PyFloat_AS_DOUBLE(w);
351
Thomas Wouters477c8d52006-05-27 19:21:47 +0000352 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000353 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000354 /* If i is an infinity, its magnitude exceeds any
355 * finite integer, so it doesn't matter which int we
356 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000357 */
358 j = 0.0;
359 else
360 goto Unimplemented;
361 }
362
Tim Peters307fa782004-09-23 08:06:40 +0000363 else if (PyLong_Check(w)) {
364 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
365 int wsign = _PyLong_Sign(w);
366 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000367 int exponent;
368
369 if (vsign != wsign) {
370 /* Magnitudes are irrelevant -- the signs alone
371 * determine the outcome.
372 */
373 i = (double)vsign;
374 j = (double)wsign;
375 goto Compare;
376 }
377 /* The signs are the same. */
378 /* Convert w to a double if it fits. In particular, 0 fits. */
379 nbits = _PyLong_NumBits(w);
380 if (nbits == (size_t)-1 && PyErr_Occurred()) {
381 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000382 * to hold the # of bits. Replace with little doubles
383 * that give the same outcome -- w is so large that
384 * its magnitude must exceed the magnitude of any
385 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000386 */
387 PyErr_Clear();
388 i = (double)vsign;
389 assert(wsign != 0);
390 j = wsign * 2.0;
391 goto Compare;
392 }
393 if (nbits <= 48) {
394 j = PyLong_AsDouble(w);
395 /* It's impossible that <= 48 bits overflowed. */
396 assert(j != -1.0 || ! PyErr_Occurred());
397 goto Compare;
398 }
399 assert(wsign != 0); /* else nbits was 0 */
400 assert(vsign != 0); /* if vsign were 0, then since wsign is
401 * not 0, we would have taken the
402 * vsign != wsign branch at the start */
403 /* We want to work with non-negative numbers. */
404 if (vsign < 0) {
405 /* "Multiply both sides" by -1; this also swaps the
406 * comparator.
407 */
408 i = -i;
409 op = _Py_SwappedOp[op];
410 }
411 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000412 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000413 /* exponent is the # of bits in v before the radix point;
414 * we know that nbits (the # of bits in w) > 48 at this point
415 */
416 if (exponent < 0 || (size_t)exponent < nbits) {
417 i = 1.0;
418 j = 2.0;
419 goto Compare;
420 }
421 if ((size_t)exponent > nbits) {
422 i = 2.0;
423 j = 1.0;
424 goto Compare;
425 }
426 /* v and w have the same number of bits before the radix
427 * point. Construct two longs that have the same comparison
428 * outcome.
429 */
430 {
431 double fracpart;
432 double intpart;
433 PyObject *result = NULL;
434 PyObject *one = NULL;
435 PyObject *vv = NULL;
436 PyObject *ww = w;
437
438 if (wsign < 0) {
439 ww = PyNumber_Negative(w);
440 if (ww == NULL)
441 goto Error;
442 }
443 else
444 Py_INCREF(ww);
445
446 fracpart = modf(i, &intpart);
447 vv = PyLong_FromDouble(intpart);
448 if (vv == NULL)
449 goto Error;
450
451 if (fracpart != 0.0) {
452 /* Shift left, and or a 1 bit into vv
453 * to represent the lost fraction.
454 */
455 PyObject *temp;
456
Christian Heimes217cfd12007-12-02 14:31:20 +0000457 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000458 if (one == NULL)
459 goto Error;
460
461 temp = PyNumber_Lshift(ww, one);
462 if (temp == NULL)
463 goto Error;
464 Py_DECREF(ww);
465 ww = temp;
466
467 temp = PyNumber_Lshift(vv, one);
468 if (temp == NULL)
469 goto Error;
470 Py_DECREF(vv);
471 vv = temp;
472
473 temp = PyNumber_Or(vv, one);
474 if (temp == NULL)
475 goto Error;
476 Py_DECREF(vv);
477 vv = temp;
478 }
479
480 r = PyObject_RichCompareBool(vv, ww, op);
481 if (r < 0)
482 goto Error;
483 result = PyBool_FromLong(r);
484 Error:
485 Py_XDECREF(vv);
486 Py_XDECREF(ww);
487 Py_XDECREF(one);
488 return result;
489 }
490 } /* else if (PyLong_Check(w)) */
491
492 else /* w isn't float, int, or long */
493 goto Unimplemented;
494
495 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000496 PyFPE_START_PROTECT("richcompare", return NULL)
497 switch (op) {
498 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000499 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000500 break;
501 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000502 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000503 break;
504 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000505 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000506 break;
507 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000508 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000509 break;
510 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000511 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000512 break;
513 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000514 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000515 break;
516 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000517 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000518 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000519
520 Unimplemented:
521 Py_INCREF(Py_NotImplemented);
522 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000523}
524
Guido van Rossum9bfef441993-03-29 10:43:31 +0000525static long
Fred Drakefd99de62000-07-09 05:02:18 +0000526float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000527{
Tim Peters39dce292000-08-15 03:34:48 +0000528 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000529}
530
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000531static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000532float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000534 double a,b;
535 CONVERT_TO_DOUBLE(v, a);
536 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000537 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000538 a = a + b;
539 PyFPE_END_PROTECT(a)
540 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541}
542
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000544float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000546 double a,b;
547 CONVERT_TO_DOUBLE(v, a);
548 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000549 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000550 a = a - b;
551 PyFPE_END_PROTECT(a)
552 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000556float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000558 double a,b;
559 CONVERT_TO_DOUBLE(v, a);
560 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000561 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000562 a = a * b;
563 PyFPE_END_PROTECT(a)
564 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565}
566
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000568float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000570 double a,b;
571 CONVERT_TO_DOUBLE(v, a);
572 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000573#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000574 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000575 PyErr_SetString(PyExc_ZeroDivisionError,
576 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000577 return NULL;
578 }
Christian Heimes53876d92008-04-19 00:31:39 +0000579#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000580 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000581 a = a / b;
582 PyFPE_END_PROTECT(a)
583 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584}
585
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000587float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000589 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000590 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000591 CONVERT_TO_DOUBLE(v, vx);
592 CONVERT_TO_DOUBLE(w, wx);
593#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000595 PyErr_SetString(PyExc_ZeroDivisionError,
596 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597 return NULL;
598 }
Christian Heimes53876d92008-04-19 00:31:39 +0000599#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000600 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000601 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000602 /* note: checking mod*wx < 0 is incorrect -- underflows to
603 0 if wx < sqrt(smallest nonzero double) */
604 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000605 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000606 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000607 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609}
610
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000612float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000613{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000614 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000615 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000616 CONVERT_TO_DOUBLE(v, vx);
617 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000618 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000620 return NULL;
621 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000622 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000623 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000624 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000625 exact multiple of wx. But this is fp arithmetic, and fp
626 vx - mod is an approximation; the result is that div may
627 not be an exact integral value after the division, although
628 it will always be very close to one.
629 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000630 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000631 if (mod) {
632 /* ensure the remainder has the same sign as the denominator */
633 if ((wx < 0) != (mod < 0)) {
634 mod += wx;
635 div -= 1.0;
636 }
637 }
638 else {
639 /* the remainder is zero, and in the presence of signed zeroes
640 fmod returns different results across platforms; ensure
641 it has the same sign as the denominator; we'd like to do
642 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000643 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000644 if (wx < 0.0)
645 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000646 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000647 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000648 if (div) {
649 floordiv = floor(div);
650 if (div - floordiv > 0.5)
651 floordiv += 1.0;
652 }
653 else {
654 /* div is zero - get the same sign as the true quotient */
655 div *= div; /* hide "div = +0" from optimizers */
656 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
657 }
658 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000659 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000660}
661
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000663float_floor_div(PyObject *v, PyObject *w)
664{
665 PyObject *t, *r;
666
667 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000668 if (t == NULL || t == Py_NotImplemented)
669 return t;
670 assert(PyTuple_CheckExact(t));
671 r = PyTuple_GET_ITEM(t, 0);
672 Py_INCREF(r);
673 Py_DECREF(t);
674 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000675}
676
677static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000678float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679{
680 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000681
682 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000683 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000684 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000685 return NULL;
686 }
687
Neil Schemenauer32117e52001-01-04 01:44:34 +0000688 CONVERT_TO_DOUBLE(v, iv);
689 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000690
691 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000692 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000693 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000694 }
Tim Peters96685bf2001-08-23 22:31:37 +0000695 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000696 if (iw < 0.0) {
697 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000698 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000699 return NULL;
700 }
701 return PyFloat_FromDouble(0.0);
702 }
Christian Heimes53876d92008-04-19 00:31:39 +0000703 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
704 return PyFloat_FromDouble(1.0);
705 }
Tim Peterse87568d2003-05-24 20:18:24 +0000706 if (iv < 0.0) {
707 /* Whether this is an error is a mess, and bumps into libm
708 * bugs so we have to figure it out ourselves.
709 */
710 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000711 /* Negative numbers raised to fractional powers
712 * become complex.
713 */
714 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000715 }
716 /* iw is an exact integer, albeit perhaps a very large one.
717 * -1 raised to an exact integer should never be exceptional.
718 * Alas, some libms (chiefly glibc as of early 2003) return
719 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
720 * happen to be representable in a *C* integer. That's a
721 * bug; we let that slide in math.pow() (which currently
722 * reflects all platform accidents), but not for Python's **.
723 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000725 /* Return 1 if iw is even, -1 if iw is odd; there's
726 * no guarantee that any C integral type is big
727 * enough to hold iw, so we have to check this
728 * indirectly.
729 */
730 ix = floor(iw * 0.5) * 2.0;
731 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
732 }
733 /* Else iv != -1.0, and overflow or underflow are possible.
734 * Unless we're to write pow() ourselves, we have to trust
735 * the platform to do this correctly.
736 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000737 }
Tim Peters96685bf2001-08-23 22:31:37 +0000738 errno = 0;
739 PyFPE_START_PROTECT("pow", return NULL)
740 ix = pow(iv, iw);
741 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000742 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000743 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000744 /* We don't expect any errno value other than ERANGE, but
745 * the range of libm bugs appears unbounded.
746 */
747 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
748 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000749 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000750 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000751 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752}
753
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000755float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000758}
759
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000761float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000762{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000763 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764}
765
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000766static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000767float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000768{
769 return v->ob_fval != 0.0;
770}
771
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000772static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000773float_is_integer(PyObject *v)
774{
775 double x = PyFloat_AsDouble(v);
776 PyObject *o;
777
778 if (x == -1.0 && PyErr_Occurred())
779 return NULL;
780 if (!Py_IS_FINITE(x))
781 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000782 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000783 PyFPE_START_PROTECT("is_integer", return NULL)
784 o = (floor(x) == x) ? Py_True : Py_False;
785 PyFPE_END_PROTECT(x)
786 if (errno != 0) {
787 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
788 PyExc_ValueError);
789 return NULL;
790 }
791 Py_INCREF(o);
792 return o;
793}
794
795#if 0
796static PyObject *
797float_is_inf(PyObject *v)
798{
799 double x = PyFloat_AsDouble(v);
800 if (x == -1.0 && PyErr_Occurred())
801 return NULL;
802 return PyBool_FromLong((long)Py_IS_INFINITY(x));
803}
804
805static PyObject *
806float_is_nan(PyObject *v)
807{
808 double x = PyFloat_AsDouble(v);
809 if (x == -1.0 && PyErr_Occurred())
810 return NULL;
811 return PyBool_FromLong((long)Py_IS_NAN(x));
812}
813
814static PyObject *
815float_is_finite(PyObject *v)
816{
817 double x = PyFloat_AsDouble(v);
818 if (x == -1.0 && PyErr_Occurred())
819 return NULL;
820 return PyBool_FromLong((long)Py_IS_FINITE(x));
821}
822#endif
823
824static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000825float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000826{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000827 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000828 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000829
830 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000831 /* Try to get out cheap if this fits in a Python int. The attempt
832 * to cast to long must be protected, as C doesn't define what
833 * happens if the double is too big to fit in a long. Some rare
834 * systems raise an exception then (RISCOS was mentioned as one,
835 * and someone using a non-default option on Sun also bumped into
836 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
837 * still be vulnerable: if a long has more bits of precision than
838 * a double, casting MIN/MAX to double may yield an approximation,
839 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
840 * yield true from the C expression wholepart<=LONG_MAX, despite
841 * that wholepart is actually greater than LONG_MAX.
842 */
843 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
844 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000845 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000846 }
847 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000848}
849
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000850/* double_round: rounds a finite double to the closest multiple of
851 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
852 ndigits <= 323). Returns a Python float, or sets a Python error and
853 returns NULL on failure (OverflowError and memory errors are possible). */
854
855#ifndef PY_NO_SHORT_FLOAT_REPR
856/* version of double_round that uses the correctly-rounded string<->double
857 conversions from Python/dtoa.c */
858
859static PyObject *
860double_round(double x, int ndigits) {
861
862 double rounded;
863 Py_ssize_t buflen, mybuflen=100;
864 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
865 int decpt, sign;
866 PyObject *result = NULL;
867
868 /* round to a decimal string */
869 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
870 if (buf == NULL) {
871 PyErr_NoMemory();
872 return NULL;
873 }
874
875 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
876 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
877 buflen = buf_end - buf;
878 if (buflen + 8 > mybuflen) {
879 mybuflen = buflen+8;
880 mybuf = (char *)PyMem_Malloc(mybuflen);
881 if (mybuf == NULL) {
882 PyErr_NoMemory();
883 goto exit;
884 }
885 }
886 /* copy buf to mybuf, adding exponent, sign and leading 0 */
887 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
888 buf, decpt - (int)buflen);
889
890 /* and convert the resulting string back to a double */
891 errno = 0;
892 rounded = _Py_dg_strtod(mybuf, NULL);
893 if (errno == ERANGE && fabs(rounded) >= 1.)
894 PyErr_SetString(PyExc_OverflowError,
895 "rounded value too large to represent");
896 else
897 result = PyFloat_FromDouble(rounded);
898
899 /* done computing value; now clean up */
900 if (mybuf != shortbuf)
901 PyMem_Free(mybuf);
902 exit:
903 _Py_dg_freedtoa(buf);
904 return result;
905}
906
907#else /* PY_NO_SHORT_FLOAT_REPR */
908
909/* fallback version, to be used when correctly rounded binary<->decimal
910 conversions aren't available */
911
912static PyObject *
913double_round(double x, int ndigits) {
914 double pow1, pow2, y, z;
915 if (ndigits >= 0) {
916 if (ndigits > 22) {
917 /* pow1 and pow2 are each safe from overflow, but
918 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
919 pow1 = pow(10.0, (double)(ndigits-22));
920 pow2 = 1e22;
921 }
922 else {
923 pow1 = pow(10.0, (double)ndigits);
924 pow2 = 1.0;
925 }
926 y = (x*pow1)*pow2;
927 /* if y overflows, then rounded value is exactly x */
928 if (!Py_IS_FINITE(y))
929 return PyFloat_FromDouble(x);
930 }
931 else {
932 pow1 = pow(10.0, (double)-ndigits);
933 pow2 = 1.0; /* unused; silences a gcc compiler warning */
934 y = x / pow1;
935 }
936
937 z = round(y);
938 if (fabs(y-z) == 0.5)
939 /* halfway between two integers; use round-half-even */
940 z = 2.0*round(y/2.0);
941
942 if (ndigits >= 0)
943 z = (z / pow2) / pow1;
944 else
945 z *= pow1;
946
947 /* if computation resulted in overflow, raise OverflowError */
948 if (!Py_IS_FINITE(z)) {
949 PyErr_SetString(PyExc_OverflowError,
950 "overflow occurred during round");
951 return NULL;
952 }
953
954 return PyFloat_FromDouble(z);
955}
956
957#endif /* PY_NO_SHORT_FLOAT_REPR */
958
959/* round a Python float v to the closest multiple of 10**-ndigits */
960
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000961static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000962float_round(PyObject *v, PyObject *args)
963{
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000964 double x, rounded;
965 PyObject *o_ndigits = NULL;
966 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000967
968 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000969 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
970 return NULL;
971 if (o_ndigits == NULL) {
972 /* single-argument round: round to nearest integer */
973 rounded = round(x);
974 if (fabs(x-rounded) == 0.5)
975 /* halfway case: round to even */
976 rounded = 2.0*round(x/2.0);
977 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000978 }
979
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000980 /* interpret second argument as a Py_ssize_t; clips on overflow */
981 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
982 if (ndigits == -1 && PyErr_Occurred())
983 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000984
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000985 /* nans and infinities round to themselves */
986 if (!Py_IS_FINITE(x))
987 return PyFloat_FromDouble(x);
988
989 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
990 always rounds to itself. For ndigits < NDIGITS_MIN, x always
991 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
992#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
993#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
994 if (ndigits > NDIGITS_MAX)
995 /* return x */
996 return PyFloat_FromDouble(x);
997 else if (ndigits < NDIGITS_MIN)
998 /* return 0.0, but with sign of x */
999 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001 /* finite x, and ndigits is not unreasonably large */
1002 return double_round(x, (int)ndigits);
1003#undef NDIGITS_MAX
1004#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001005}
1006
1007static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001008float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001009{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001010 if (PyFloat_CheckExact(v))
1011 Py_INCREF(v);
1012 else
1013 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001014 return v;
1015}
1016
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001017/* turn ASCII hex characters into integer values and vice versa */
1018
1019static char
1020char_from_hex(int x)
1021{
1022 assert(0 <= x && x < 16);
1023 return "0123456789abcdef"[x];
1024}
1025
1026static int
1027hex_from_char(char c) {
1028 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001029 switch(c) {
1030 case '0':
1031 x = 0;
1032 break;
1033 case '1':
1034 x = 1;
1035 break;
1036 case '2':
1037 x = 2;
1038 break;
1039 case '3':
1040 x = 3;
1041 break;
1042 case '4':
1043 x = 4;
1044 break;
1045 case '5':
1046 x = 5;
1047 break;
1048 case '6':
1049 x = 6;
1050 break;
1051 case '7':
1052 x = 7;
1053 break;
1054 case '8':
1055 x = 8;
1056 break;
1057 case '9':
1058 x = 9;
1059 break;
1060 case 'a':
1061 case 'A':
1062 x = 10;
1063 break;
1064 case 'b':
1065 case 'B':
1066 x = 11;
1067 break;
1068 case 'c':
1069 case 'C':
1070 x = 12;
1071 break;
1072 case 'd':
1073 case 'D':
1074 x = 13;
1075 break;
1076 case 'e':
1077 case 'E':
1078 x = 14;
1079 break;
1080 case 'f':
1081 case 'F':
1082 x = 15;
1083 break;
1084 default:
1085 x = -1;
1086 break;
1087 }
1088 return x;
1089}
1090
1091/* convert a float to a hexadecimal string */
1092
1093/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1094 of the form 4k+1. */
1095#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1096
1097static PyObject *
1098float_hex(PyObject *v)
1099{
1100 double x, m;
1101 int e, shift, i, si, esign;
1102 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1103 trailing NUL byte. */
1104 char s[(TOHEX_NBITS-1)/4+3];
1105
1106 CONVERT_TO_DOUBLE(v, x);
1107
1108 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1109 return float_str((PyFloatObject *)v);
1110
1111 if (x == 0.0) {
1112 if(copysign(1.0, x) == -1.0)
1113 return PyUnicode_FromString("-0x0.0p+0");
1114 else
1115 return PyUnicode_FromString("0x0.0p+0");
1116 }
1117
1118 m = frexp(fabs(x), &e);
1119 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1120 m = ldexp(m, shift);
1121 e -= shift;
1122
1123 si = 0;
1124 s[si] = char_from_hex((int)m);
1125 si++;
1126 m -= (int)m;
1127 s[si] = '.';
1128 si++;
1129 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1130 m *= 16.0;
1131 s[si] = char_from_hex((int)m);
1132 si++;
1133 m -= (int)m;
1134 }
1135 s[si] = '\0';
1136
1137 if (e < 0) {
1138 esign = (int)'-';
1139 e = -e;
1140 }
1141 else
1142 esign = (int)'+';
1143
1144 if (x < 0.0)
1145 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1146 else
1147 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1148}
1149
1150PyDoc_STRVAR(float_hex_doc,
1151"float.hex() -> string\n\
1152\n\
1153Return a hexadecimal representation of a floating-point number.\n\
1154>>> (-0.1).hex()\n\
1155'-0x1.999999999999ap-4'\n\
1156>>> 3.14159.hex()\n\
1157'0x1.921f9f01b866ep+1'");
1158
1159/* Convert a hexadecimal string to a float. */
1160
1161static PyObject *
1162float_fromhex(PyObject *cls, PyObject *arg)
1163{
1164 PyObject *result_as_float, *result;
1165 double x;
1166 long exp, top_exp, lsb, key_digit;
1167 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1168 int half_eps, digit, round_up, sign=1;
1169 Py_ssize_t length, ndigits, fdigits, i;
1170
1171 /*
1172 * For the sake of simplicity and correctness, we impose an artificial
1173 * limit on ndigits, the total number of hex digits in the coefficient
1174 * The limit is chosen to ensure that, writing exp for the exponent,
1175 *
1176 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1177 * guaranteed to overflow (provided it's nonzero)
1178 *
1179 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1180 * guaranteed to underflow to 0.
1181 *
1182 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1183 * overflow in the calculation of exp and top_exp below.
1184 *
1185 * More specifically, ndigits is assumed to satisfy the following
1186 * inequalities:
1187 *
1188 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1189 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1190 *
1191 * If either of these inequalities is not satisfied, a ValueError is
1192 * raised. Otherwise, write x for the value of the hex string, and
1193 * assume x is nonzero. Then
1194 *
1195 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1196 *
1197 * Now if exp > LONG_MAX/2 then:
1198 *
1199 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1200 * = DBL_MAX_EXP
1201 *
1202 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1203 * double, so overflows. If exp < LONG_MIN/2, then
1204 *
1205 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1206 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1207 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1208 *
1209 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1210 * when converted to a C double.
1211 *
1212 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1213 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1214 */
1215
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001216 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001217 if (s == NULL)
1218 return NULL;
1219 s_end = s + length;
1220
1221 /********************
1222 * Parse the string *
1223 ********************/
1224
1225 /* leading whitespace and optional sign */
Mark Dickinson33242472009-04-18 20:19:17 +00001226 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001227 s++;
1228 if (*s == '-') {
1229 s++;
1230 sign = -1;
1231 }
1232 else if (*s == '+')
1233 s++;
1234
1235 /* infinities and nans */
Andrew MacIntyre45612572008-09-22 14:49:01 +00001236 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001237 x = Py_NAN;
1238 goto finished;
1239 }
Andrew MacIntyre45612572008-09-22 14:49:01 +00001240 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1241 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001242 x = sign*Py_HUGE_VAL;
1243 goto finished;
1244 }
1245
1246 /* [0x] */
1247 s_store = s;
1248 if (*s == '0') {
1249 s++;
1250 if (tolower(*s) == (int)'x')
1251 s++;
1252 else
1253 s = s_store;
1254 }
1255
1256 /* coefficient: <integer> [. <fraction>] */
1257 coeff_start = 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 s_store = s;
1261 if (*s == '.') {
1262 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001263 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001264 s++;
1265 coeff_end = s-1;
1266 }
1267 else
1268 coeff_end = s;
1269
1270 /* ndigits = total # of hex digits; fdigits = # after point */
1271 ndigits = coeff_end - coeff_start;
1272 fdigits = coeff_end - s_store;
1273 if (ndigits == 0)
1274 goto parse_error;
1275 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1276 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1277 goto insane_length_error;
1278
1279 /* [p <exponent>] */
1280 if (tolower(*s) == (int)'p') {
1281 s++;
1282 exp_start = s;
1283 if (*s == '-' || *s == '+')
1284 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001285 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286 goto parse_error;
1287 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001288 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001289 s++;
1290 exp = strtol(exp_start, NULL, 10);
1291 }
1292 else
1293 exp = 0;
1294
1295 /* optional trailing whitespace leading to the end of the string */
Mark Dickinson33242472009-04-18 20:19:17 +00001296 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001297 s++;
1298 if (s != s_end)
1299 goto parse_error;
1300
1301/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1302#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1303 coeff_end-(j) : \
1304 coeff_end-1-(j)))
1305
1306 /*******************************************
1307 * Compute rounded value of the hex string *
1308 *******************************************/
1309
1310 /* Discard leading zeros, and catch extreme overflow and underflow */
1311 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1312 ndigits--;
1313 if (ndigits == 0 || exp < LONG_MIN/2) {
1314 x = sign * 0.0;
1315 goto finished;
1316 }
1317 if (exp > LONG_MAX/2)
1318 goto overflow_error;
1319
1320 /* Adjust exponent for fractional part. */
1321 exp = exp - 4*((long)fdigits);
1322
1323 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1324 top_exp = exp + 4*((long)ndigits - 1);
1325 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1326 top_exp++;
1327
1328 /* catch almost all nonextreme cases of overflow and underflow here */
1329 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1330 x = sign * 0.0;
1331 goto finished;
1332 }
1333 if (top_exp > DBL_MAX_EXP)
1334 goto overflow_error;
1335
1336 /* lsb = exponent of least significant bit of the *rounded* value.
1337 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1338 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1339
1340 x = 0.0;
1341 if (exp >= lsb) {
1342 /* no rounding required */
1343 for (i = ndigits-1; i >= 0; i--)
1344 x = 16.0*x + HEX_DIGIT(i);
1345 x = sign * ldexp(x, (int)(exp));
1346 goto finished;
1347 }
1348 /* rounding required. key_digit is the index of the hex digit
1349 containing the first bit to be rounded away. */
1350 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1351 key_digit = (lsb - exp - 1) / 4;
1352 for (i = ndigits-1; i > key_digit; i--)
1353 x = 16.0*x + HEX_DIGIT(i);
1354 digit = HEX_DIGIT(key_digit);
1355 x = 16.0*x + (double)(digit & (16-2*half_eps));
1356
1357 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1358 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1359 if ((digit & half_eps) != 0) {
1360 round_up = 0;
1361 if ((digit & (3*half_eps-1)) != 0 ||
1362 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1363 round_up = 1;
1364 else
1365 for (i = key_digit-1; i >= 0; i--)
1366 if (HEX_DIGIT(i) != 0) {
1367 round_up = 1;
1368 break;
1369 }
1370 if (round_up == 1) {
1371 x += 2*half_eps;
1372 if (top_exp == DBL_MAX_EXP &&
1373 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1374 /* overflow corner case: pre-rounded value <
1375 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1376 goto overflow_error;
1377 }
1378 }
1379 x = sign * ldexp(x, (int)(exp+4*key_digit));
1380
1381 finished:
1382 result_as_float = Py_BuildValue("(d)", x);
1383 if (result_as_float == NULL)
1384 return NULL;
1385 result = PyObject_CallObject(cls, result_as_float);
1386 Py_DECREF(result_as_float);
1387 return result;
1388
1389 overflow_error:
1390 PyErr_SetString(PyExc_OverflowError,
1391 "hexadecimal value too large to represent as a float");
1392 return NULL;
1393
1394 parse_error:
1395 PyErr_SetString(PyExc_ValueError,
1396 "invalid hexadecimal floating-point string");
1397 return NULL;
1398
1399 insane_length_error:
1400 PyErr_SetString(PyExc_ValueError,
1401 "hexadecimal string too long to convert");
1402 return NULL;
1403}
1404
1405PyDoc_STRVAR(float_fromhex_doc,
1406"float.fromhex(string) -> float\n\
1407\n\
1408Create a floating-point number from a hexadecimal string.\n\
1409>>> float.fromhex('0x1.ffffp10')\n\
14102047.984375\n\
1411>>> float.fromhex('-0x1p-1074')\n\
1412-4.9406564584124654e-324");
1413
1414
Christian Heimes26855632008-01-27 23:50:43 +00001415static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001416float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001417{
1418 double self;
1419 double float_part;
1420 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001421 int i;
1422
Christian Heimes26855632008-01-27 23:50:43 +00001423 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001424 PyObject *py_exponent = NULL;
1425 PyObject *numerator = NULL;
1426 PyObject *denominator = NULL;
1427 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001428 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001429
1430#define INPLACE_UPDATE(obj, call) \
1431 prev = obj; \
1432 obj = call; \
1433 Py_DECREF(prev); \
1434
1435 CONVERT_TO_DOUBLE(v, self);
1436
1437 if (Py_IS_INFINITY(self)) {
1438 PyErr_SetString(PyExc_OverflowError,
1439 "Cannot pass infinity to float.as_integer_ratio.");
1440 return NULL;
1441 }
1442#ifdef Py_NAN
1443 if (Py_IS_NAN(self)) {
1444 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001445 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001446 return NULL;
1447 }
1448#endif
1449
Christian Heimes26855632008-01-27 23:50:43 +00001450 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001451 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001452 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001453
1454 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1455 float_part *= 2.0;
1456 exponent--;
1457 }
1458 /* self == float_part * 2**exponent exactly and float_part is integral.
1459 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1460 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001461
Christian Heimes292d3512008-02-03 16:51:08 +00001462 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001463 if (numerator == NULL) goto error;
1464
Christian Heimes292d3512008-02-03 16:51:08 +00001465 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001466 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001467 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001468 if (py_exponent == NULL) goto error;
1469 INPLACE_UPDATE(py_exponent,
1470 long_methods->nb_lshift(denominator, py_exponent));
1471 if (py_exponent == NULL) goto error;
1472 if (exponent > 0) {
1473 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001474 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001475 if (numerator == NULL) goto error;
1476 }
1477 else {
1478 Py_DECREF(denominator);
1479 denominator = py_exponent;
1480 py_exponent = NULL;
1481 }
1482
1483 result_pair = PyTuple_Pack(2, numerator, denominator);
1484
1485#undef INPLACE_UPDATE
1486error:
1487 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001488 Py_XDECREF(denominator);
1489 Py_XDECREF(numerator);
1490 return result_pair;
1491}
1492
1493PyDoc_STRVAR(float_as_integer_ratio_doc,
1494"float.as_integer_ratio() -> (int, int)\n"
1495"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001496"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1497"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001498"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001499"\n"
1500">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001501"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001502">>> (0.0).as_integer_ratio()\n"
1503"(0, 1)\n"
1504">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001505"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001506
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001507
Jeremy Hylton938ace62002-07-17 16:30:39 +00001508static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001509float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1510
Tim Peters6d6c1a32001-08-02 04:15:00 +00001511static PyObject *
1512float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1513{
1514 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001515 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516
Guido van Rossumbef14172001-08-29 15:47:46 +00001517 if (type != &PyFloat_Type)
1518 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1520 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001521 /* If it's a string, but not a string subclass, use
1522 PyFloat_FromString. */
1523 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001524 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 return PyNumber_Float(x);
1526}
1527
Guido van Rossumbef14172001-08-29 15:47:46 +00001528/* Wimpy, slow approach to tp_new calls for subtypes of float:
1529 first create a regular float from whatever arguments we got,
1530 then allocate a subtype instance and initialize its ob_fval
1531 from the regular float. The regular float is then thrown away.
1532*/
1533static PyObject *
1534float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1535{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001536 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001537
1538 assert(PyType_IsSubtype(type, &PyFloat_Type));
1539 tmp = float_new(&PyFloat_Type, args, kwds);
1540 if (tmp == NULL)
1541 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001542 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001543 newobj = type->tp_alloc(type, 0);
1544 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001545 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001546 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001547 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001548 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001549 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001550 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001551}
1552
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001553static PyObject *
1554float_getnewargs(PyFloatObject *v)
1555{
1556 return Py_BuildValue("(d)", v->ob_fval);
1557}
1558
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001559/* this is for the benefit of the pack/unpack routines below */
1560
1561typedef enum {
1562 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1563} float_format_type;
1564
1565static float_format_type double_format, float_format;
1566static float_format_type detected_double_format, detected_float_format;
1567
1568static PyObject *
1569float_getformat(PyTypeObject *v, PyObject* arg)
1570{
1571 char* s;
1572 float_format_type r;
1573
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001574 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001575 PyErr_Format(PyExc_TypeError,
1576 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001577 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001578 return NULL;
1579 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001580 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001581 if (s == NULL)
1582 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001583 if (strcmp(s, "double") == 0) {
1584 r = double_format;
1585 }
1586 else if (strcmp(s, "float") == 0) {
1587 r = float_format;
1588 }
1589 else {
1590 PyErr_SetString(PyExc_ValueError,
1591 "__getformat__() argument 1 must be "
1592 "'double' or 'float'");
1593 return NULL;
1594 }
1595
1596 switch (r) {
1597 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001598 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001599 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001600 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001601 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001602 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001603 default:
1604 Py_FatalError("insane float_format or double_format");
1605 return NULL;
1606 }
1607}
1608
1609PyDoc_STRVAR(float_getformat_doc,
1610"float.__getformat__(typestr) -> string\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'. This function returns whichever of\n"
1616"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1617"format of floating point numbers used by the C type named by typestr.");
1618
1619static PyObject *
1620float_setformat(PyTypeObject *v, PyObject* args)
1621{
1622 char* typestr;
1623 char* format;
1624 float_format_type f;
1625 float_format_type detected;
1626 float_format_type *p;
1627
1628 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1629 return NULL;
1630
1631 if (strcmp(typestr, "double") == 0) {
1632 p = &double_format;
1633 detected = detected_double_format;
1634 }
1635 else if (strcmp(typestr, "float") == 0) {
1636 p = &float_format;
1637 detected = detected_float_format;
1638 }
1639 else {
1640 PyErr_SetString(PyExc_ValueError,
1641 "__setformat__() argument 1 must "
1642 "be 'double' or 'float'");
1643 return NULL;
1644 }
1645
1646 if (strcmp(format, "unknown") == 0) {
1647 f = unknown_format;
1648 }
1649 else if (strcmp(format, "IEEE, little-endian") == 0) {
1650 f = ieee_little_endian_format;
1651 }
1652 else if (strcmp(format, "IEEE, big-endian") == 0) {
1653 f = ieee_big_endian_format;
1654 }
1655 else {
1656 PyErr_SetString(PyExc_ValueError,
1657 "__setformat__() argument 2 must be "
1658 "'unknown', 'IEEE, little-endian' or "
1659 "'IEEE, big-endian'");
1660 return NULL;
1661
1662 }
1663
1664 if (f != unknown_format && f != detected) {
1665 PyErr_Format(PyExc_ValueError,
1666 "can only set %s format to 'unknown' or the "
1667 "detected platform value", typestr);
1668 return NULL;
1669 }
1670
1671 *p = f;
1672 Py_RETURN_NONE;
1673}
1674
1675PyDoc_STRVAR(float_setformat_doc,
1676"float.__setformat__(typestr, fmt) -> None\n"
1677"\n"
1678"You probably don't want to use this function. It exists mainly to be\n"
1679"used in Python's test suite.\n"
1680"\n"
1681"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1682"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1683"one of the latter two if it appears to match the underlying C reality.\n"
1684"\n"
1685"Overrides the automatic determination of C-level floating point type.\n"
1686"This affects how floats are converted to and from binary strings.");
1687
Guido van Rossumb43daf72007-08-01 18:08:08 +00001688static PyObject *
1689float_getzero(PyObject *v, void *closure)
1690{
1691 return PyFloat_FromDouble(0.0);
1692}
1693
Eric Smith8c663262007-08-25 02:26:07 +00001694static PyObject *
1695float__format__(PyObject *self, PyObject *args)
1696{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001697 PyObject *format_spec;
1698
1699 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1700 return NULL;
1701 return _PyFloat_FormatAdvanced(self,
1702 PyUnicode_AS_UNICODE(format_spec),
1703 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001704}
1705
1706PyDoc_STRVAR(float__format__doc,
1707"float.__format__(format_spec) -> string\n"
1708"\n"
1709"Formats the float according to format_spec.");
1710
1711
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001712static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001713 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001714 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001715 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1716 "Returns the Integral closest to x between 0 and x."},
1717 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1718 "Returns the Integral closest to x, rounding half toward even.\n"
1719 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001720 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1721 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001722 {"fromhex", (PyCFunction)float_fromhex,
1723 METH_O|METH_CLASS, float_fromhex_doc},
1724 {"hex", (PyCFunction)float_hex,
1725 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001726 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1727 "Returns True if the float is an integer."},
1728#if 0
1729 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1730 "Returns True if the float is positive or negative infinite."},
1731 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1732 "Returns True if the float is finite, neither infinite nor NaN."},
1733 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1734 "Returns True if the float is not a number (NaN)."},
1735#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001736 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001737 {"__getformat__", (PyCFunction)float_getformat,
1738 METH_O|METH_CLASS, float_getformat_doc},
1739 {"__setformat__", (PyCFunction)float_setformat,
1740 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001741 {"__format__", (PyCFunction)float__format__,
1742 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001743 {NULL, NULL} /* sentinel */
1744};
1745
Guido van Rossumb43daf72007-08-01 18:08:08 +00001746static PyGetSetDef float_getset[] = {
1747 {"real",
1748 (getter)float_float, (setter)NULL,
1749 "the real part of a complex number",
1750 NULL},
1751 {"imag",
1752 (getter)float_getzero, (setter)NULL,
1753 "the imaginary part of a complex number",
1754 NULL},
1755 {NULL} /* Sentinel */
1756};
1757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001758PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759"float(x) -> floating point number\n\
1760\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001761Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762
1763
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001764static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001765 float_add, /*nb_add*/
1766 float_sub, /*nb_subtract*/
1767 float_mul, /*nb_multiply*/
1768 float_rem, /*nb_remainder*/
1769 float_divmod, /*nb_divmod*/
1770 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001771 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001772 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001773 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001774 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001775 0, /*nb_invert*/
1776 0, /*nb_lshift*/
1777 0, /*nb_rshift*/
1778 0, /*nb_and*/
1779 0, /*nb_xor*/
1780 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001781 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001782 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001783 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001784 0, /* nb_inplace_add */
1785 0, /* nb_inplace_subtract */
1786 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001787 0, /* nb_inplace_remainder */
1788 0, /* nb_inplace_power */
1789 0, /* nb_inplace_lshift */
1790 0, /* nb_inplace_rshift */
1791 0, /* nb_inplace_and */
1792 0, /* nb_inplace_xor */
1793 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001794 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001795 float_div, /* nb_true_divide */
1796 0, /* nb_inplace_floor_divide */
1797 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001798};
1799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001800PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001801 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001802 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001803 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001804 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001806 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807 0, /* tp_getattr */
1808 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001809 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 (reprfunc)float_repr, /* tp_repr */
1811 &float_as_number, /* tp_as_number */
1812 0, /* tp_as_sequence */
1813 0, /* tp_as_mapping */
1814 (hashfunc)float_hash, /* tp_hash */
1815 0, /* tp_call */
1816 (reprfunc)float_str, /* tp_str */
1817 PyObject_GenericGetAttr, /* tp_getattro */
1818 0, /* tp_setattro */
1819 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001820 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 float_doc, /* tp_doc */
1822 0, /* tp_traverse */
1823 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001824 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 0, /* tp_weaklistoffset */
1826 0, /* tp_iter */
1827 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001828 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001830 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 0, /* tp_base */
1832 0, /* tp_dict */
1833 0, /* tp_descr_get */
1834 0, /* tp_descr_set */
1835 0, /* tp_dictoffset */
1836 0, /* tp_init */
1837 0, /* tp_alloc */
1838 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001839};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001840
1841void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001842_PyFloat_Init(void)
1843{
1844 /* We attempt to determine if this machine is using IEEE
1845 floating point formats by peering at the bits of some
1846 carefully chosen values. If it looks like we are on an
1847 IEEE platform, the float packing/unpacking routines can
1848 just copy bits, if not they resort to arithmetic & shifts
1849 and masks. The shifts & masks approach works on all finite
1850 values, but what happens to infinities, NaNs and signed
1851 zeroes on packing is an accident, and attempting to unpack
1852 a NaN or an infinity will raise an exception.
1853
1854 Note that if we're on some whacked-out platform which uses
1855 IEEE formats but isn't strictly little-endian or big-
1856 endian, we will fall back to the portable shifts & masks
1857 method. */
1858
1859#if SIZEOF_DOUBLE == 8
1860 {
1861 double x = 9006104071832581.0;
1862 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1863 detected_double_format = ieee_big_endian_format;
1864 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1865 detected_double_format = ieee_little_endian_format;
1866 else
1867 detected_double_format = unknown_format;
1868 }
1869#else
1870 detected_double_format = unknown_format;
1871#endif
1872
1873#if SIZEOF_FLOAT == 4
1874 {
1875 float y = 16711938.0;
1876 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1877 detected_float_format = ieee_big_endian_format;
1878 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1879 detected_float_format = ieee_little_endian_format;
1880 else
1881 detected_float_format = unknown_format;
1882 }
1883#else
1884 detected_float_format = unknown_format;
1885#endif
1886
1887 double_format = detected_double_format;
1888 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001889
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001890 /* Init float info */
1891 if (FloatInfoType.tp_name == 0)
1892 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001893}
1894
Georg Brandl2ee470f2008-07-16 12:55:28 +00001895int
1896PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001897{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001898 PyFloatObject *p;
1899 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001900 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001901 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001902 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001903
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001904 list = block_list;
1905 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001906 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001907 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001908 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001909 for (i = 0, p = &list->objects[0];
1910 i < N_FLOATOBJECTS;
1911 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001912 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001913 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001914 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001915 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001916 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001917 list->next = block_list;
1918 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001919 for (i = 0, p = &list->objects[0];
1920 i < N_FLOATOBJECTS;
1921 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001922 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001923 Py_REFCNT(p) == 0) {
1924 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001925 free_list;
1926 free_list = p;
1927 }
1928 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001929 }
1930 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001931 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001932 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001933 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001934 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001935 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001936 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001937}
1938
1939void
1940PyFloat_Fini(void)
1941{
1942 PyFloatObject *p;
1943 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001944 int i;
1945 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001946
Georg Brandl2ee470f2008-07-16 12:55:28 +00001947 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001948
Guido van Rossum3fce8831999-03-12 19:43:17 +00001949 if (!Py_VerboseFlag)
1950 return;
1951 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001952 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001953 fprintf(stderr, "\n");
1954 }
1955 else {
1956 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001957 ": %d unfreed float%s\n",
1958 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001959 }
1960 if (Py_VerboseFlag > 1) {
1961 list = block_list;
1962 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001963 for (i = 0, p = &list->objects[0];
1964 i < N_FLOATOBJECTS;
1965 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001966 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001967 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00001968 char *buf = PyOS_double_to_string(
1969 PyFloat_AS_DOUBLE(p), 'r',
1970 0, 0, NULL);
1971 if (buf) {
1972 /* XXX(twouters) cast
1973 refcount to long
1974 until %zd is
1975 universally
1976 available
1977 */
1978 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001979 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001980 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00001981 PyMem_Free(buf);
1982 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001983 }
1984 }
1985 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001986 }
1987 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001988}
Tim Peters9905b942003-03-20 20:53:32 +00001989
1990/*----------------------------------------------------------------------------
1991 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001992 */
1993int
1994_PyFloat_Pack4(double x, unsigned char *p, int le)
1995{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001996 if (float_format == unknown_format) {
1997 unsigned char sign;
1998 int e;
1999 double f;
2000 unsigned int fbits;
2001 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002002
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003 if (le) {
2004 p += 3;
2005 incr = -1;
2006 }
Tim Peters9905b942003-03-20 20:53:32 +00002007
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002008 if (x < 0) {
2009 sign = 1;
2010 x = -x;
2011 }
2012 else
2013 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002014
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002016
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002017 /* Normalize f to be in the range [1.0, 2.0) */
2018 if (0.5 <= f && f < 1.0) {
2019 f *= 2.0;
2020 e--;
2021 }
2022 else if (f == 0.0)
2023 e = 0;
2024 else {
2025 PyErr_SetString(PyExc_SystemError,
2026 "frexp() result out of range");
2027 return -1;
2028 }
2029
2030 if (e >= 128)
2031 goto Overflow;
2032 else if (e < -126) {
2033 /* Gradual underflow */
2034 f = ldexp(f, 126 + e);
2035 e = 0;
2036 }
2037 else if (!(e == 0 && f == 0.0)) {
2038 e += 127;
2039 f -= 1.0; /* Get rid of leading 1 */
2040 }
2041
2042 f *= 8388608.0; /* 2**23 */
2043 fbits = (unsigned int)(f + 0.5); /* Round */
2044 assert(fbits <= 8388608);
2045 if (fbits >> 23) {
2046 /* The carry propagated out of a string of 23 1 bits. */
2047 fbits = 0;
2048 ++e;
2049 if (e >= 255)
2050 goto Overflow;
2051 }
2052
2053 /* First byte */
2054 *p = (sign << 7) | (e >> 1);
2055 p += incr;
2056
2057 /* Second byte */
2058 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2059 p += incr;
2060
2061 /* Third byte */
2062 *p = (fbits >> 8) & 0xFF;
2063 p += incr;
2064
2065 /* Fourth byte */
2066 *p = fbits & 0xFF;
2067
2068 /* Done */
2069 return 0;
2070
Tim Peters9905b942003-03-20 20:53:32 +00002071 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002072 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002073 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002074 const char *s = (char*)&y;
2075 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002076
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002077 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2078 goto Overflow;
2079
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002080 if ((float_format == ieee_little_endian_format && !le)
2081 || (float_format == ieee_big_endian_format && le)) {
2082 p += 3;
2083 incr = -1;
2084 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002085
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002086 for (i = 0; i < 4; i++) {
2087 *p = *s++;
2088 p += incr;
2089 }
2090 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002091 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002092 Overflow:
2093 PyErr_SetString(PyExc_OverflowError,
2094 "float too large to pack with f format");
2095 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002096}
2097
2098int
2099_PyFloat_Pack8(double x, unsigned char *p, int le)
2100{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101 if (double_format == unknown_format) {
2102 unsigned char sign;
2103 int e;
2104 double f;
2105 unsigned int fhi, flo;
2106 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002107
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002108 if (le) {
2109 p += 7;
2110 incr = -1;
2111 }
Tim Peters9905b942003-03-20 20:53:32 +00002112
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113 if (x < 0) {
2114 sign = 1;
2115 x = -x;
2116 }
2117 else
2118 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002119
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002120 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002121
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 /* Normalize f to be in the range [1.0, 2.0) */
2123 if (0.5 <= f && f < 1.0) {
2124 f *= 2.0;
2125 e--;
2126 }
2127 else if (f == 0.0)
2128 e = 0;
2129 else {
2130 PyErr_SetString(PyExc_SystemError,
2131 "frexp() result out of range");
2132 return -1;
2133 }
2134
2135 if (e >= 1024)
2136 goto Overflow;
2137 else if (e < -1022) {
2138 /* Gradual underflow */
2139 f = ldexp(f, 1022 + e);
2140 e = 0;
2141 }
2142 else if (!(e == 0 && f == 0.0)) {
2143 e += 1023;
2144 f -= 1.0; /* Get rid of leading 1 */
2145 }
2146
2147 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2148 f *= 268435456.0; /* 2**28 */
2149 fhi = (unsigned int)f; /* Truncate */
2150 assert(fhi < 268435456);
2151
2152 f -= (double)fhi;
2153 f *= 16777216.0; /* 2**24 */
2154 flo = (unsigned int)(f + 0.5); /* Round */
2155 assert(flo <= 16777216);
2156 if (flo >> 24) {
2157 /* The carry propagated out of a string of 24 1 bits. */
2158 flo = 0;
2159 ++fhi;
2160 if (fhi >> 28) {
2161 /* And it also progagated out of the next 28 bits. */
2162 fhi = 0;
2163 ++e;
2164 if (e >= 2047)
2165 goto Overflow;
2166 }
2167 }
2168
2169 /* First byte */
2170 *p = (sign << 7) | (e >> 4);
2171 p += incr;
2172
2173 /* Second byte */
2174 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2175 p += incr;
2176
2177 /* Third byte */
2178 *p = (fhi >> 16) & 0xFF;
2179 p += incr;
2180
2181 /* Fourth byte */
2182 *p = (fhi >> 8) & 0xFF;
2183 p += incr;
2184
2185 /* Fifth byte */
2186 *p = fhi & 0xFF;
2187 p += incr;
2188
2189 /* Sixth byte */
2190 *p = (flo >> 16) & 0xFF;
2191 p += incr;
2192
2193 /* Seventh byte */
2194 *p = (flo >> 8) & 0xFF;
2195 p += incr;
2196
2197 /* Eighth byte */
2198 *p = flo & 0xFF;
2199 p += incr;
2200
2201 /* Done */
2202 return 0;
2203
2204 Overflow:
2205 PyErr_SetString(PyExc_OverflowError,
2206 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002207 return -1;
2208 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002209 else {
2210 const char *s = (char*)&x;
2211 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002212
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213 if ((double_format == ieee_little_endian_format && !le)
2214 || (double_format == ieee_big_endian_format && le)) {
2215 p += 7;
2216 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002217 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002218
2219 for (i = 0; i < 8; i++) {
2220 *p = *s++;
2221 p += incr;
2222 }
2223 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002224 }
Tim Peters9905b942003-03-20 20:53:32 +00002225}
2226
2227double
2228_PyFloat_Unpack4(const unsigned char *p, int le)
2229{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002230 if (float_format == unknown_format) {
2231 unsigned char sign;
2232 int e;
2233 unsigned int f;
2234 double x;
2235 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002236
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237 if (le) {
2238 p += 3;
2239 incr = -1;
2240 }
2241
2242 /* First byte */
2243 sign = (*p >> 7) & 1;
2244 e = (*p & 0x7F) << 1;
2245 p += incr;
2246
2247 /* Second byte */
2248 e |= (*p >> 7) & 1;
2249 f = (*p & 0x7F) << 16;
2250 p += incr;
2251
2252 if (e == 255) {
2253 PyErr_SetString(
2254 PyExc_ValueError,
2255 "can't unpack IEEE 754 special value "
2256 "on non-IEEE platform");
2257 return -1;
2258 }
2259
2260 /* Third byte */
2261 f |= *p << 8;
2262 p += incr;
2263
2264 /* Fourth byte */
2265 f |= *p;
2266
2267 x = (double)f / 8388608.0;
2268
2269 /* XXX This sadly ignores Inf/NaN issues */
2270 if (e == 0)
2271 e = -126;
2272 else {
2273 x += 1.0;
2274 e -= 127;
2275 }
2276 x = ldexp(x, e);
2277
2278 if (sign)
2279 x = -x;
2280
2281 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002282 }
Tim Peters9905b942003-03-20 20:53:32 +00002283 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002284 float x;
2285
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286 if ((float_format == ieee_little_endian_format && !le)
2287 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002288 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002289 char *d = &buf[3];
2290 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002291
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002292 for (i = 0; i < 4; i++) {
2293 *d-- = *p++;
2294 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002295 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296 }
2297 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002298 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002299 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002300
2301 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302 }
Tim Peters9905b942003-03-20 20:53:32 +00002303}
2304
2305double
2306_PyFloat_Unpack8(const unsigned char *p, int le)
2307{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308 if (double_format == unknown_format) {
2309 unsigned char sign;
2310 int e;
2311 unsigned int fhi, flo;
2312 double x;
2313 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002314
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315 if (le) {
2316 p += 7;
2317 incr = -1;
2318 }
2319
2320 /* First byte */
2321 sign = (*p >> 7) & 1;
2322 e = (*p & 0x7F) << 4;
2323
2324 p += incr;
2325
2326 /* Second byte */
2327 e |= (*p >> 4) & 0xF;
2328 fhi = (*p & 0xF) << 24;
2329 p += incr;
2330
2331 if (e == 2047) {
2332 PyErr_SetString(
2333 PyExc_ValueError,
2334 "can't unpack IEEE 754 special value "
2335 "on non-IEEE platform");
2336 return -1.0;
2337 }
2338
2339 /* Third byte */
2340 fhi |= *p << 16;
2341 p += incr;
2342
2343 /* Fourth byte */
2344 fhi |= *p << 8;
2345 p += incr;
2346
2347 /* Fifth byte */
2348 fhi |= *p;
2349 p += incr;
2350
2351 /* Sixth byte */
2352 flo = *p << 16;
2353 p += incr;
2354
2355 /* Seventh byte */
2356 flo |= *p << 8;
2357 p += incr;
2358
2359 /* Eighth byte */
2360 flo |= *p;
2361
2362 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2363 x /= 268435456.0; /* 2**28 */
2364
2365 if (e == 0)
2366 e = -1022;
2367 else {
2368 x += 1.0;
2369 e -= 1023;
2370 }
2371 x = ldexp(x, e);
2372
2373 if (sign)
2374 x = -x;
2375
2376 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002377 }
Tim Peters9905b942003-03-20 20:53:32 +00002378 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002379 double x;
2380
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002381 if ((double_format == ieee_little_endian_format && !le)
2382 || (double_format == ieee_big_endian_format && le)) {
2383 char buf[8];
2384 char *d = &buf[7];
2385 int i;
2386
2387 for (i = 0; i < 8; i++) {
2388 *d-- = *p++;
2389 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002390 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002391 }
2392 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002393 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002394 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002395
2396 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002397 }
Tim Peters9905b942003-03-20 20:53:32 +00002398}