blob: fdca3bef3640b5526c934d4b5a3f439bb29f61e0 [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. */
196 errno = 0;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000197 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000198 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000199 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000200 if (end == s) {
Mark Dickinson6d65df12009-04-26 15:30:47 +0000201 if (errno == ENOMEM)
202 PyErr_NoMemory();
203 else {
204 PyOS_snprintf(buffer, sizeof(buffer),
205 "invalid literal for float(): %.200s", s);
206 PyErr_SetString(PyExc_ValueError, buffer);
Christian Heimes99170a52007-12-19 02:07:34 +0000207 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000208 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000209 }
210 /* Since end != s, the platform made *some* kind of sense out
211 of the input. Trust it. */
Mark Dickinson33242472009-04-18 20:19:17 +0000212 while (*end && isspace(Py_CHARMASK(*end)))
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 end++;
Mark Dickinson6d65df12009-04-26 15:30:47 +0000214 if (end != last) {
215 if (*end == '\0')
216 PyErr_SetString(PyExc_ValueError,
217 "null byte in argument for float()");
218 else {
219 PyOS_snprintf(buffer, sizeof(buffer),
220 "invalid literal for float(): %.200s", s);
221 PyErr_SetString(PyExc_ValueError, buffer);
222 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000223 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000224 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000225 result = PyFloat_FromDouble(x);
226 error:
227 if (s_buffer)
228 PyMem_FREE(s_buffer);
229 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000230}
231
Guido van Rossum234f9421993-06-17 12:35:49 +0000232static void
Fred Drakefd99de62000-07-09 05:02:18 +0000233float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000234{
Guido van Rossum9475a232001-10-05 20:51:39 +0000235 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000236 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000237 free_list = op;
238 }
239 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000240 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000241}
242
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243double
Fred Drakefd99de62000-07-09 05:02:18 +0000244PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 PyNumberMethods *nb;
247 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000248 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000249
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250 if (op && PyFloat_Check(op))
251 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000252
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000253 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255 return -1;
256 }
Tim Petersd2364e82001-11-01 20:09:42 +0000257
Christian Heimes90aa7642007-12-19 02:45:37 +0000258 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000259 PyErr_SetString(PyExc_TypeError, "a float is required");
260 return -1;
261 }
262
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264 if (fo == NULL)
265 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266 if (!PyFloat_Check(fo)) {
267 PyErr_SetString(PyExc_TypeError,
268 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000269 return -1;
270 }
Tim Petersd2364e82001-11-01 20:09:42 +0000271
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 val = PyFloat_AS_DOUBLE(fo);
273 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000274
Guido van Rossumb6775db1994-08-01 11:34:53 +0000275 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276}
277
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000279 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000280 set to NULL, and the function invoking this macro returns NULL. If
281 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
282 stored in obj, and returned from the function invoking this macro.
283*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000284#define CONVERT_TO_DOUBLE(obj, dbl) \
285 if (PyFloat_Check(obj)) \
286 dbl = PyFloat_AS_DOUBLE(obj); \
287 else if (convert_to_double(&(obj), &(dbl)) < 0) \
288 return obj;
289
Eric Smith0923d1d2009-04-16 20:16:10 +0000290/* Methods */
291
Neil Schemenauer32117e52001-01-04 01:44:34 +0000292static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000293convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000294{
295 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000296
Guido van Rossumddefaf32007-01-14 03:31:43 +0000297 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000298 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000299 if (*dbl == -1.0 && PyErr_Occurred()) {
300 *v = NULL;
301 return -1;
302 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000303 }
304 else {
305 Py_INCREF(Py_NotImplemented);
306 *v = Py_NotImplemented;
307 return -1;
308 }
309 return 0;
310}
311
Eric Smith0923d1d2009-04-16 20:16:10 +0000312static PyObject *
313float_str_or_repr(PyFloatObject *v, char format_code)
314{
315 PyObject *result;
316 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
317 format_code, 0, Py_DTSF_ADD_DOT_0,
318 NULL);
319 if (!buf)
320 return PyErr_NoMemory();
321 result = PyUnicode_FromString(buf);
322 PyMem_Free(buf);
323 return result;
324}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000327float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328{
Eric Smith0923d1d2009-04-16 20:16:10 +0000329 return float_str_or_repr(v, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000330}
331
332static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000333float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000334{
Eric Smith0923d1d2009-04-16 20:16:10 +0000335 return float_str_or_repr(v, 's');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336}
337
Tim Peters307fa782004-09-23 08:06:40 +0000338/* Comparison is pretty much a nightmare. When comparing float to float,
339 * we do it as straightforwardly (and long-windedly) as conceivable, so
340 * that, e.g., Python x == y delivers the same result as the platform
341 * C x == y when x and/or y is a NaN.
342 * When mixing float with an integer type, there's no good *uniform* approach.
343 * Converting the double to an integer obviously doesn't work, since we
344 * may lose info from fractional bits. Converting the integer to a double
345 * also has two failure modes: (1) a long int may trigger overflow (too
346 * large to fit in the dynamic range of a C double); (2) even a C long may have
347 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
348 * 63 bits of precision, but a C double probably has only 53), and then
349 * we can falsely claim equality when low-order integer bits are lost by
350 * coercion to double. So this part is painful too.
351 */
352
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000353static PyObject*
354float_richcompare(PyObject *v, PyObject *w, int op)
355{
356 double i, j;
357 int r = 0;
358
Tim Peters307fa782004-09-23 08:06:40 +0000359 assert(PyFloat_Check(v));
360 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000361
Tim Peters307fa782004-09-23 08:06:40 +0000362 /* Switch on the type of w. Set i and j to doubles to be compared,
363 * and op to the richcomp to use.
364 */
365 if (PyFloat_Check(w))
366 j = PyFloat_AS_DOUBLE(w);
367
Thomas Wouters477c8d52006-05-27 19:21:47 +0000368 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000369 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000370 /* If i is an infinity, its magnitude exceeds any
371 * finite integer, so it doesn't matter which int we
372 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000373 */
374 j = 0.0;
375 else
376 goto Unimplemented;
377 }
378
Tim Peters307fa782004-09-23 08:06:40 +0000379 else if (PyLong_Check(w)) {
380 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
381 int wsign = _PyLong_Sign(w);
382 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000383 int exponent;
384
385 if (vsign != wsign) {
386 /* Magnitudes are irrelevant -- the signs alone
387 * determine the outcome.
388 */
389 i = (double)vsign;
390 j = (double)wsign;
391 goto Compare;
392 }
393 /* The signs are the same. */
394 /* Convert w to a double if it fits. In particular, 0 fits. */
395 nbits = _PyLong_NumBits(w);
396 if (nbits == (size_t)-1 && PyErr_Occurred()) {
397 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000398 * to hold the # of bits. Replace with little doubles
399 * that give the same outcome -- w is so large that
400 * its magnitude must exceed the magnitude of any
401 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000402 */
403 PyErr_Clear();
404 i = (double)vsign;
405 assert(wsign != 0);
406 j = wsign * 2.0;
407 goto Compare;
408 }
409 if (nbits <= 48) {
410 j = PyLong_AsDouble(w);
411 /* It's impossible that <= 48 bits overflowed. */
412 assert(j != -1.0 || ! PyErr_Occurred());
413 goto Compare;
414 }
415 assert(wsign != 0); /* else nbits was 0 */
416 assert(vsign != 0); /* if vsign were 0, then since wsign is
417 * not 0, we would have taken the
418 * vsign != wsign branch at the start */
419 /* We want to work with non-negative numbers. */
420 if (vsign < 0) {
421 /* "Multiply both sides" by -1; this also swaps the
422 * comparator.
423 */
424 i = -i;
425 op = _Py_SwappedOp[op];
426 }
427 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000428 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000429 /* exponent is the # of bits in v before the radix point;
430 * we know that nbits (the # of bits in w) > 48 at this point
431 */
432 if (exponent < 0 || (size_t)exponent < nbits) {
433 i = 1.0;
434 j = 2.0;
435 goto Compare;
436 }
437 if ((size_t)exponent > nbits) {
438 i = 2.0;
439 j = 1.0;
440 goto Compare;
441 }
442 /* v and w have the same number of bits before the radix
443 * point. Construct two longs that have the same comparison
444 * outcome.
445 */
446 {
447 double fracpart;
448 double intpart;
449 PyObject *result = NULL;
450 PyObject *one = NULL;
451 PyObject *vv = NULL;
452 PyObject *ww = w;
453
454 if (wsign < 0) {
455 ww = PyNumber_Negative(w);
456 if (ww == NULL)
457 goto Error;
458 }
459 else
460 Py_INCREF(ww);
461
462 fracpart = modf(i, &intpart);
463 vv = PyLong_FromDouble(intpart);
464 if (vv == NULL)
465 goto Error;
466
467 if (fracpart != 0.0) {
468 /* Shift left, and or a 1 bit into vv
469 * to represent the lost fraction.
470 */
471 PyObject *temp;
472
Christian Heimes217cfd12007-12-02 14:31:20 +0000473 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000474 if (one == NULL)
475 goto Error;
476
477 temp = PyNumber_Lshift(ww, one);
478 if (temp == NULL)
479 goto Error;
480 Py_DECREF(ww);
481 ww = temp;
482
483 temp = PyNumber_Lshift(vv, one);
484 if (temp == NULL)
485 goto Error;
486 Py_DECREF(vv);
487 vv = temp;
488
489 temp = PyNumber_Or(vv, one);
490 if (temp == NULL)
491 goto Error;
492 Py_DECREF(vv);
493 vv = temp;
494 }
495
496 r = PyObject_RichCompareBool(vv, ww, op);
497 if (r < 0)
498 goto Error;
499 result = PyBool_FromLong(r);
500 Error:
501 Py_XDECREF(vv);
502 Py_XDECREF(ww);
503 Py_XDECREF(one);
504 return result;
505 }
506 } /* else if (PyLong_Check(w)) */
507
508 else /* w isn't float, int, or long */
509 goto Unimplemented;
510
511 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000512 PyFPE_START_PROTECT("richcompare", return NULL)
513 switch (op) {
514 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000515 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000516 break;
517 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000518 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000519 break;
520 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000521 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522 break;
523 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000524 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000525 break;
526 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000527 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000528 break;
529 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000530 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000531 break;
532 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000533 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000534 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000535
536 Unimplemented:
537 Py_INCREF(Py_NotImplemented);
538 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000539}
540
Guido van Rossum9bfef441993-03-29 10:43:31 +0000541static long
Fred Drakefd99de62000-07-09 05:02:18 +0000542float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000543{
Tim Peters39dce292000-08-15 03:34:48 +0000544 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000545}
546
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000548float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000550 double a,b;
551 CONVERT_TO_DOUBLE(v, a);
552 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000553 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000554 a = a + b;
555 PyFPE_END_PROTECT(a)
556 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557}
558
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000560float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000562 double a,b;
563 CONVERT_TO_DOUBLE(v, a);
564 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000565 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000566 a = a - b;
567 PyFPE_END_PROTECT(a)
568 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000574 double a,b;
575 CONVERT_TO_DOUBLE(v, a);
576 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000577 PyFPE_START_PROTECT("multiply", 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_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000586 double a,b;
587 CONVERT_TO_DOUBLE(v, a);
588 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000589#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000590 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000591 PyErr_SetString(PyExc_ZeroDivisionError,
592 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593 return NULL;
594 }
Christian Heimes53876d92008-04-19 00:31:39 +0000595#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000596 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000597 a = a / b;
598 PyFPE_END_PROTECT(a)
599 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000600}
601
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000602static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000603float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000605 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000606 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000607 CONVERT_TO_DOUBLE(v, vx);
608 CONVERT_TO_DOUBLE(w, wx);
609#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000611 PyErr_SetString(PyExc_ZeroDivisionError,
612 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613 return NULL;
614 }
Christian Heimes53876d92008-04-19 00:31:39 +0000615#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000616 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000617 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000618 /* note: checking mod*wx < 0 is incorrect -- underflows to
619 0 if wx < sqrt(smallest nonzero double) */
620 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000621 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000622 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000623 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000625}
626
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000628float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000629{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000630 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000631 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000632 CONVERT_TO_DOUBLE(v, vx);
633 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000634 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000636 return NULL;
637 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000638 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000639 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000640 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000641 exact multiple of wx. But this is fp arithmetic, and fp
642 vx - mod is an approximation; the result is that div may
643 not be an exact integral value after the division, although
644 it will always be very close to one.
645 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000646 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000647 if (mod) {
648 /* ensure the remainder has the same sign as the denominator */
649 if ((wx < 0) != (mod < 0)) {
650 mod += wx;
651 div -= 1.0;
652 }
653 }
654 else {
655 /* the remainder is zero, and in the presence of signed zeroes
656 fmod returns different results across platforms; ensure
657 it has the same sign as the denominator; we'd like to do
658 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000659 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000660 if (wx < 0.0)
661 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000662 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000663 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000664 if (div) {
665 floordiv = floor(div);
666 if (div - floordiv > 0.5)
667 floordiv += 1.0;
668 }
669 else {
670 /* div is zero - get the same sign as the true quotient */
671 div *= div; /* hide "div = +0" from optimizers */
672 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
673 }
674 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000675 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000676}
677
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000678static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000679float_floor_div(PyObject *v, PyObject *w)
680{
681 PyObject *t, *r;
682
683 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000684 if (t == NULL || t == Py_NotImplemented)
685 return t;
686 assert(PyTuple_CheckExact(t));
687 r = PyTuple_GET_ITEM(t, 0);
688 Py_INCREF(r);
689 Py_DECREF(t);
690 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000691}
692
693static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000694float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000695{
696 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000697
698 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000699 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000700 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000701 return NULL;
702 }
703
Neil Schemenauer32117e52001-01-04 01:44:34 +0000704 CONVERT_TO_DOUBLE(v, iv);
705 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000706
707 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000708 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000709 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000710 }
Tim Peters96685bf2001-08-23 22:31:37 +0000711 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000712 if (iw < 0.0) {
713 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000714 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000715 return NULL;
716 }
717 return PyFloat_FromDouble(0.0);
718 }
Christian Heimes53876d92008-04-19 00:31:39 +0000719 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
720 return PyFloat_FromDouble(1.0);
721 }
Tim Peterse87568d2003-05-24 20:18:24 +0000722 if (iv < 0.0) {
723 /* Whether this is an error is a mess, and bumps into libm
724 * bugs so we have to figure it out ourselves.
725 */
726 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000727 /* Negative numbers raised to fractional powers
728 * become complex.
729 */
730 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000731 }
732 /* iw is an exact integer, albeit perhaps a very large one.
733 * -1 raised to an exact integer should never be exceptional.
734 * Alas, some libms (chiefly glibc as of early 2003) return
735 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
736 * happen to be representable in a *C* integer. That's a
737 * bug; we let that slide in math.pow() (which currently
738 * reflects all platform accidents), but not for Python's **.
739 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000740 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000741 /* Return 1 if iw is even, -1 if iw is odd; there's
742 * no guarantee that any C integral type is big
743 * enough to hold iw, so we have to check this
744 * indirectly.
745 */
746 ix = floor(iw * 0.5) * 2.0;
747 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
748 }
749 /* Else iv != -1.0, and overflow or underflow are possible.
750 * Unless we're to write pow() ourselves, we have to trust
751 * the platform to do this correctly.
752 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000753 }
Tim Peters96685bf2001-08-23 22:31:37 +0000754 errno = 0;
755 PyFPE_START_PROTECT("pow", return NULL)
756 ix = pow(iv, iw);
757 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000758 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000759 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000760 /* We don't expect any errno value other than ERANGE, but
761 * the range of libm bugs appears unbounded.
762 */
763 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
764 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000765 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000766 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768}
769
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000771float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774}
775
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000777float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000778{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000779 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780}
781
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000782static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000783float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000784{
785 return v->ob_fval != 0.0;
786}
787
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000789float_is_integer(PyObject *v)
790{
791 double x = PyFloat_AsDouble(v);
792 PyObject *o;
793
794 if (x == -1.0 && PyErr_Occurred())
795 return NULL;
796 if (!Py_IS_FINITE(x))
797 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000798 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000799 PyFPE_START_PROTECT("is_integer", return NULL)
800 o = (floor(x) == x) ? Py_True : Py_False;
801 PyFPE_END_PROTECT(x)
802 if (errno != 0) {
803 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
804 PyExc_ValueError);
805 return NULL;
806 }
807 Py_INCREF(o);
808 return o;
809}
810
811#if 0
812static PyObject *
813float_is_inf(PyObject *v)
814{
815 double x = PyFloat_AsDouble(v);
816 if (x == -1.0 && PyErr_Occurred())
817 return NULL;
818 return PyBool_FromLong((long)Py_IS_INFINITY(x));
819}
820
821static PyObject *
822float_is_nan(PyObject *v)
823{
824 double x = PyFloat_AsDouble(v);
825 if (x == -1.0 && PyErr_Occurred())
826 return NULL;
827 return PyBool_FromLong((long)Py_IS_NAN(x));
828}
829
830static PyObject *
831float_is_finite(PyObject *v)
832{
833 double x = PyFloat_AsDouble(v);
834 if (x == -1.0 && PyErr_Occurred())
835 return NULL;
836 return PyBool_FromLong((long)Py_IS_FINITE(x));
837}
838#endif
839
840static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000841float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000842{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000844 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000845
846 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000847 /* Try to get out cheap if this fits in a Python int. The attempt
848 * to cast to long must be protected, as C doesn't define what
849 * happens if the double is too big to fit in a long. Some rare
850 * systems raise an exception then (RISCOS was mentioned as one,
851 * and someone using a non-default option on Sun also bumped into
852 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
853 * still be vulnerable: if a long has more bits of precision than
854 * a double, casting MIN/MAX to double may yield an approximation,
855 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
856 * yield true from the C expression wholepart<=LONG_MAX, despite
857 * that wholepart is actually greater than LONG_MAX.
858 */
859 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
860 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000861 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000862 }
863 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000864}
865
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000866/* double_round: rounds a finite double to the closest multiple of
867 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
868 ndigits <= 323). Returns a Python float, or sets a Python error and
869 returns NULL on failure (OverflowError and memory errors are possible). */
870
871#ifndef PY_NO_SHORT_FLOAT_REPR
872/* version of double_round that uses the correctly-rounded string<->double
873 conversions from Python/dtoa.c */
874
875static PyObject *
876double_round(double x, int ndigits) {
877
878 double rounded;
879 Py_ssize_t buflen, mybuflen=100;
880 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
881 int decpt, sign;
882 PyObject *result = NULL;
883
884 /* round to a decimal string */
885 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
886 if (buf == NULL) {
887 PyErr_NoMemory();
888 return NULL;
889 }
890
891 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
892 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
893 buflen = buf_end - buf;
894 if (buflen + 8 > mybuflen) {
895 mybuflen = buflen+8;
896 mybuf = (char *)PyMem_Malloc(mybuflen);
897 if (mybuf == NULL) {
898 PyErr_NoMemory();
899 goto exit;
900 }
901 }
902 /* copy buf to mybuf, adding exponent, sign and leading 0 */
903 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
904 buf, decpt - (int)buflen);
905
906 /* and convert the resulting string back to a double */
907 errno = 0;
908 rounded = _Py_dg_strtod(mybuf, NULL);
909 if (errno == ERANGE && fabs(rounded) >= 1.)
910 PyErr_SetString(PyExc_OverflowError,
911 "rounded value too large to represent");
912 else
913 result = PyFloat_FromDouble(rounded);
914
915 /* done computing value; now clean up */
916 if (mybuf != shortbuf)
917 PyMem_Free(mybuf);
918 exit:
919 _Py_dg_freedtoa(buf);
920 return result;
921}
922
923#else /* PY_NO_SHORT_FLOAT_REPR */
924
925/* fallback version, to be used when correctly rounded binary<->decimal
926 conversions aren't available */
927
928static PyObject *
929double_round(double x, int ndigits) {
930 double pow1, pow2, y, z;
931 if (ndigits >= 0) {
932 if (ndigits > 22) {
933 /* pow1 and pow2 are each safe from overflow, but
934 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
935 pow1 = pow(10.0, (double)(ndigits-22));
936 pow2 = 1e22;
937 }
938 else {
939 pow1 = pow(10.0, (double)ndigits);
940 pow2 = 1.0;
941 }
942 y = (x*pow1)*pow2;
943 /* if y overflows, then rounded value is exactly x */
944 if (!Py_IS_FINITE(y))
945 return PyFloat_FromDouble(x);
946 }
947 else {
948 pow1 = pow(10.0, (double)-ndigits);
949 pow2 = 1.0; /* unused; silences a gcc compiler warning */
950 y = x / pow1;
951 }
952
953 z = round(y);
954 if (fabs(y-z) == 0.5)
955 /* halfway between two integers; use round-half-even */
956 z = 2.0*round(y/2.0);
957
958 if (ndigits >= 0)
959 z = (z / pow2) / pow1;
960 else
961 z *= pow1;
962
963 /* if computation resulted in overflow, raise OverflowError */
964 if (!Py_IS_FINITE(z)) {
965 PyErr_SetString(PyExc_OverflowError,
966 "overflow occurred during round");
967 return NULL;
968 }
969
970 return PyFloat_FromDouble(z);
971}
972
973#endif /* PY_NO_SHORT_FLOAT_REPR */
974
975/* round a Python float v to the closest multiple of 10**-ndigits */
976
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000977static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000978float_round(PyObject *v, PyObject *args)
979{
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000980 double x, rounded;
981 PyObject *o_ndigits = NULL;
982 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000983
984 x = PyFloat_AsDouble(v);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000985 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
986 return NULL;
987 if (o_ndigits == NULL) {
988 /* single-argument round: round to nearest integer */
989 rounded = round(x);
990 if (fabs(x-rounded) == 0.5)
991 /* halfway case: round to even */
992 rounded = 2.0*round(x/2.0);
993 return PyLong_FromDouble(rounded);
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000994 }
995
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000996 /* interpret second argument as a Py_ssize_t; clips on overflow */
997 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
998 if (ndigits == -1 && PyErr_Occurred())
999 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001 /* nans and infinities round to themselves */
1002 if (!Py_IS_FINITE(x))
1003 return PyFloat_FromDouble(x);
1004
1005 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1006 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1007 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
1008#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1009#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
1010 if (ndigits > NDIGITS_MAX)
1011 /* return x */
1012 return PyFloat_FromDouble(x);
1013 else if (ndigits < NDIGITS_MIN)
1014 /* return 0.0, but with sign of x */
1015 return PyFloat_FromDouble(0.0*x);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001016 else
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001017 /* finite x, and ndigits is not unreasonably large */
1018 return double_round(x, (int)ndigits);
1019#undef NDIGITS_MAX
1020#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001021}
1022
1023static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001024float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001025{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001026 if (PyFloat_CheckExact(v))
1027 Py_INCREF(v);
1028 else
1029 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001030 return v;
1031}
1032
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001033/* turn ASCII hex characters into integer values and vice versa */
1034
1035static char
1036char_from_hex(int x)
1037{
1038 assert(0 <= x && x < 16);
1039 return "0123456789abcdef"[x];
1040}
1041
1042static int
1043hex_from_char(char c) {
1044 int x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001045 switch(c) {
1046 case '0':
1047 x = 0;
1048 break;
1049 case '1':
1050 x = 1;
1051 break;
1052 case '2':
1053 x = 2;
1054 break;
1055 case '3':
1056 x = 3;
1057 break;
1058 case '4':
1059 x = 4;
1060 break;
1061 case '5':
1062 x = 5;
1063 break;
1064 case '6':
1065 x = 6;
1066 break;
1067 case '7':
1068 x = 7;
1069 break;
1070 case '8':
1071 x = 8;
1072 break;
1073 case '9':
1074 x = 9;
1075 break;
1076 case 'a':
1077 case 'A':
1078 x = 10;
1079 break;
1080 case 'b':
1081 case 'B':
1082 x = 11;
1083 break;
1084 case 'c':
1085 case 'C':
1086 x = 12;
1087 break;
1088 case 'd':
1089 case 'D':
1090 x = 13;
1091 break;
1092 case 'e':
1093 case 'E':
1094 x = 14;
1095 break;
1096 case 'f':
1097 case 'F':
1098 x = 15;
1099 break;
1100 default:
1101 x = -1;
1102 break;
1103 }
1104 return x;
1105}
1106
1107/* convert a float to a hexadecimal string */
1108
1109/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1110 of the form 4k+1. */
1111#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1112
1113static PyObject *
1114float_hex(PyObject *v)
1115{
1116 double x, m;
1117 int e, shift, i, si, esign;
1118 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1119 trailing NUL byte. */
1120 char s[(TOHEX_NBITS-1)/4+3];
1121
1122 CONVERT_TO_DOUBLE(v, x);
1123
1124 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1125 return float_str((PyFloatObject *)v);
1126
1127 if (x == 0.0) {
1128 if(copysign(1.0, x) == -1.0)
1129 return PyUnicode_FromString("-0x0.0p+0");
1130 else
1131 return PyUnicode_FromString("0x0.0p+0");
1132 }
1133
1134 m = frexp(fabs(x), &e);
1135 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1136 m = ldexp(m, shift);
1137 e -= shift;
1138
1139 si = 0;
1140 s[si] = char_from_hex((int)m);
1141 si++;
1142 m -= (int)m;
1143 s[si] = '.';
1144 si++;
1145 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1146 m *= 16.0;
1147 s[si] = char_from_hex((int)m);
1148 si++;
1149 m -= (int)m;
1150 }
1151 s[si] = '\0';
1152
1153 if (e < 0) {
1154 esign = (int)'-';
1155 e = -e;
1156 }
1157 else
1158 esign = (int)'+';
1159
1160 if (x < 0.0)
1161 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1162 else
1163 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1164}
1165
1166PyDoc_STRVAR(float_hex_doc,
1167"float.hex() -> string\n\
1168\n\
1169Return a hexadecimal representation of a floating-point number.\n\
1170>>> (-0.1).hex()\n\
1171'-0x1.999999999999ap-4'\n\
1172>>> 3.14159.hex()\n\
1173'0x1.921f9f01b866ep+1'");
1174
1175/* Convert a hexadecimal string to a float. */
1176
1177static PyObject *
1178float_fromhex(PyObject *cls, PyObject *arg)
1179{
1180 PyObject *result_as_float, *result;
1181 double x;
1182 long exp, top_exp, lsb, key_digit;
1183 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1184 int half_eps, digit, round_up, sign=1;
1185 Py_ssize_t length, ndigits, fdigits, i;
1186
1187 /*
1188 * For the sake of simplicity and correctness, we impose an artificial
1189 * limit on ndigits, the total number of hex digits in the coefficient
1190 * The limit is chosen to ensure that, writing exp for the exponent,
1191 *
1192 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1193 * guaranteed to overflow (provided it's nonzero)
1194 *
1195 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1196 * guaranteed to underflow to 0.
1197 *
1198 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1199 * overflow in the calculation of exp and top_exp below.
1200 *
1201 * More specifically, ndigits is assumed to satisfy the following
1202 * inequalities:
1203 *
1204 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1205 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1206 *
1207 * If either of these inequalities is not satisfied, a ValueError is
1208 * raised. Otherwise, write x for the value of the hex string, and
1209 * assume x is nonzero. Then
1210 *
1211 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1212 *
1213 * Now if exp > LONG_MAX/2 then:
1214 *
1215 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1216 * = DBL_MAX_EXP
1217 *
1218 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1219 * double, so overflows. If exp < LONG_MIN/2, then
1220 *
1221 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1222 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1223 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1224 *
1225 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1226 * when converted to a C double.
1227 *
1228 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1229 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1230 */
1231
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001232 s = _PyUnicode_AsStringAndSize(arg, &length);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233 if (s == NULL)
1234 return NULL;
1235 s_end = s + length;
1236
1237 /********************
1238 * Parse the string *
1239 ********************/
1240
1241 /* leading whitespace and optional sign */
Mark Dickinson33242472009-04-18 20:19:17 +00001242 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001243 s++;
1244 if (*s == '-') {
1245 s++;
1246 sign = -1;
1247 }
1248 else if (*s == '+')
1249 s++;
1250
1251 /* infinities and nans */
Andrew MacIntyre45612572008-09-22 14:49:01 +00001252 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001253 x = Py_NAN;
1254 goto finished;
1255 }
Andrew MacIntyre45612572008-09-22 14:49:01 +00001256 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1257 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258 x = sign*Py_HUGE_VAL;
1259 goto finished;
1260 }
1261
1262 /* [0x] */
1263 s_store = s;
1264 if (*s == '0') {
1265 s++;
1266 if (tolower(*s) == (int)'x')
1267 s++;
1268 else
1269 s = s_store;
1270 }
1271
1272 /* coefficient: <integer> [. <fraction>] */
1273 coeff_start = s;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001274 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001275 s++;
1276 s_store = s;
1277 if (*s == '.') {
1278 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001279 while (hex_from_char(*s) >= 0)
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001280 s++;
1281 coeff_end = s-1;
1282 }
1283 else
1284 coeff_end = s;
1285
1286 /* ndigits = total # of hex digits; fdigits = # after point */
1287 ndigits = coeff_end - coeff_start;
1288 fdigits = coeff_end - s_store;
1289 if (ndigits == 0)
1290 goto parse_error;
1291 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1292 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1293 goto insane_length_error;
1294
1295 /* [p <exponent>] */
1296 if (tolower(*s) == (int)'p') {
1297 s++;
1298 exp_start = s;
1299 if (*s == '-' || *s == '+')
1300 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001301 if (!('0' <= *s && *s <= '9'))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001302 goto parse_error;
1303 s++;
Mark Dickinson42a72ee2008-08-21 21:40:15 +00001304 while ('0' <= *s && *s <= '9')
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001305 s++;
1306 exp = strtol(exp_start, NULL, 10);
1307 }
1308 else
1309 exp = 0;
1310
1311 /* optional trailing whitespace leading to the end of the string */
Mark Dickinson33242472009-04-18 20:19:17 +00001312 while (isspace(Py_CHARMASK(*s)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001313 s++;
1314 if (s != s_end)
1315 goto parse_error;
1316
1317/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1318#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1319 coeff_end-(j) : \
1320 coeff_end-1-(j)))
1321
1322 /*******************************************
1323 * Compute rounded value of the hex string *
1324 *******************************************/
1325
1326 /* Discard leading zeros, and catch extreme overflow and underflow */
1327 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1328 ndigits--;
1329 if (ndigits == 0 || exp < LONG_MIN/2) {
1330 x = sign * 0.0;
1331 goto finished;
1332 }
1333 if (exp > LONG_MAX/2)
1334 goto overflow_error;
1335
1336 /* Adjust exponent for fractional part. */
1337 exp = exp - 4*((long)fdigits);
1338
1339 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1340 top_exp = exp + 4*((long)ndigits - 1);
1341 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1342 top_exp++;
1343
1344 /* catch almost all nonextreme cases of overflow and underflow here */
1345 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1346 x = sign * 0.0;
1347 goto finished;
1348 }
1349 if (top_exp > DBL_MAX_EXP)
1350 goto overflow_error;
1351
1352 /* lsb = exponent of least significant bit of the *rounded* value.
1353 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1354 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1355
1356 x = 0.0;
1357 if (exp >= lsb) {
1358 /* no rounding required */
1359 for (i = ndigits-1; i >= 0; i--)
1360 x = 16.0*x + HEX_DIGIT(i);
1361 x = sign * ldexp(x, (int)(exp));
1362 goto finished;
1363 }
1364 /* rounding required. key_digit is the index of the hex digit
1365 containing the first bit to be rounded away. */
1366 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1367 key_digit = (lsb - exp - 1) / 4;
1368 for (i = ndigits-1; i > key_digit; i--)
1369 x = 16.0*x + HEX_DIGIT(i);
1370 digit = HEX_DIGIT(key_digit);
1371 x = 16.0*x + (double)(digit & (16-2*half_eps));
1372
1373 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1374 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1375 if ((digit & half_eps) != 0) {
1376 round_up = 0;
1377 if ((digit & (3*half_eps-1)) != 0 ||
1378 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1379 round_up = 1;
1380 else
1381 for (i = key_digit-1; i >= 0; i--)
1382 if (HEX_DIGIT(i) != 0) {
1383 round_up = 1;
1384 break;
1385 }
1386 if (round_up == 1) {
1387 x += 2*half_eps;
1388 if (top_exp == DBL_MAX_EXP &&
1389 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1390 /* overflow corner case: pre-rounded value <
1391 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1392 goto overflow_error;
1393 }
1394 }
1395 x = sign * ldexp(x, (int)(exp+4*key_digit));
1396
1397 finished:
1398 result_as_float = Py_BuildValue("(d)", x);
1399 if (result_as_float == NULL)
1400 return NULL;
1401 result = PyObject_CallObject(cls, result_as_float);
1402 Py_DECREF(result_as_float);
1403 return result;
1404
1405 overflow_error:
1406 PyErr_SetString(PyExc_OverflowError,
1407 "hexadecimal value too large to represent as a float");
1408 return NULL;
1409
1410 parse_error:
1411 PyErr_SetString(PyExc_ValueError,
1412 "invalid hexadecimal floating-point string");
1413 return NULL;
1414
1415 insane_length_error:
1416 PyErr_SetString(PyExc_ValueError,
1417 "hexadecimal string too long to convert");
1418 return NULL;
1419}
1420
1421PyDoc_STRVAR(float_fromhex_doc,
1422"float.fromhex(string) -> float\n\
1423\n\
1424Create a floating-point number from a hexadecimal string.\n\
1425>>> float.fromhex('0x1.ffffp10')\n\
14262047.984375\n\
1427>>> float.fromhex('-0x1p-1074')\n\
1428-4.9406564584124654e-324");
1429
1430
Christian Heimes26855632008-01-27 23:50:43 +00001431static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001432float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001433{
1434 double self;
1435 double float_part;
1436 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001437 int i;
1438
Christian Heimes26855632008-01-27 23:50:43 +00001439 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001440 PyObject *py_exponent = NULL;
1441 PyObject *numerator = NULL;
1442 PyObject *denominator = NULL;
1443 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001444 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001445
1446#define INPLACE_UPDATE(obj, call) \
1447 prev = obj; \
1448 obj = call; \
1449 Py_DECREF(prev); \
1450
1451 CONVERT_TO_DOUBLE(v, self);
1452
1453 if (Py_IS_INFINITY(self)) {
1454 PyErr_SetString(PyExc_OverflowError,
1455 "Cannot pass infinity to float.as_integer_ratio.");
1456 return NULL;
1457 }
1458#ifdef Py_NAN
1459 if (Py_IS_NAN(self)) {
1460 PyErr_SetString(PyExc_ValueError,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001461 "Cannot pass NaN to float.as_integer_ratio.");
Christian Heimes26855632008-01-27 23:50:43 +00001462 return NULL;
1463 }
1464#endif
1465
Christian Heimes26855632008-01-27 23:50:43 +00001466 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001467 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001468 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001469
1470 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1471 float_part *= 2.0;
1472 exponent--;
1473 }
1474 /* self == float_part * 2**exponent exactly and float_part is integral.
1475 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1476 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001477
Christian Heimes292d3512008-02-03 16:51:08 +00001478 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001479 if (numerator == NULL) goto error;
1480
Christian Heimes292d3512008-02-03 16:51:08 +00001481 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001482 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001483 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001484 if (py_exponent == NULL) goto error;
1485 INPLACE_UPDATE(py_exponent,
1486 long_methods->nb_lshift(denominator, py_exponent));
1487 if (py_exponent == NULL) goto error;
1488 if (exponent > 0) {
1489 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001490 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001491 if (numerator == NULL) goto error;
1492 }
1493 else {
1494 Py_DECREF(denominator);
1495 denominator = py_exponent;
1496 py_exponent = NULL;
1497 }
1498
1499 result_pair = PyTuple_Pack(2, numerator, denominator);
1500
1501#undef INPLACE_UPDATE
1502error:
1503 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001504 Py_XDECREF(denominator);
1505 Py_XDECREF(numerator);
1506 return result_pair;
1507}
1508
1509PyDoc_STRVAR(float_as_integer_ratio_doc,
1510"float.as_integer_ratio() -> (int, int)\n"
1511"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001512"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1513"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001514"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001515"\n"
1516">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001517"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001518">>> (0.0).as_integer_ratio()\n"
1519"(0, 1)\n"
1520">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001521"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001522
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001523
Jeremy Hylton938ace62002-07-17 16:30:39 +00001524static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001525float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1526
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527static PyObject *
1528float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1529{
1530 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001531 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532
Guido van Rossumbef14172001-08-29 15:47:46 +00001533 if (type != &PyFloat_Type)
1534 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1536 return NULL;
Benjamin Peterson2808d3c2009-04-15 21:34:27 +00001537 /* If it's a string, but not a string subclass, use
1538 PyFloat_FromString. */
1539 if (PyUnicode_CheckExact(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001540 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 return PyNumber_Float(x);
1542}
1543
Guido van Rossumbef14172001-08-29 15:47:46 +00001544/* Wimpy, slow approach to tp_new calls for subtypes of float:
1545 first create a regular float from whatever arguments we got,
1546 then allocate a subtype instance and initialize its ob_fval
1547 from the regular float. The regular float is then thrown away.
1548*/
1549static PyObject *
1550float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1551{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001552 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001553
1554 assert(PyType_IsSubtype(type, &PyFloat_Type));
1555 tmp = float_new(&PyFloat_Type, args, kwds);
1556 if (tmp == NULL)
1557 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001558 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001559 newobj = type->tp_alloc(type, 0);
1560 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001561 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001562 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001563 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001564 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001565 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001566 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001567}
1568
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001569static PyObject *
1570float_getnewargs(PyFloatObject *v)
1571{
1572 return Py_BuildValue("(d)", v->ob_fval);
1573}
1574
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001575/* this is for the benefit of the pack/unpack routines below */
1576
1577typedef enum {
1578 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1579} float_format_type;
1580
1581static float_format_type double_format, float_format;
1582static float_format_type detected_double_format, detected_float_format;
1583
1584static PyObject *
1585float_getformat(PyTypeObject *v, PyObject* arg)
1586{
1587 char* s;
1588 float_format_type r;
1589
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001590 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001591 PyErr_Format(PyExc_TypeError,
1592 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001593 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001594 return NULL;
1595 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001596 s = _PyUnicode_AsString(arg);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001597 if (s == NULL)
1598 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001599 if (strcmp(s, "double") == 0) {
1600 r = double_format;
1601 }
1602 else if (strcmp(s, "float") == 0) {
1603 r = float_format;
1604 }
1605 else {
1606 PyErr_SetString(PyExc_ValueError,
1607 "__getformat__() argument 1 must be "
1608 "'double' or 'float'");
1609 return NULL;
1610 }
1611
1612 switch (r) {
1613 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001614 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001616 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001618 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001619 default:
1620 Py_FatalError("insane float_format or double_format");
1621 return NULL;
1622 }
1623}
1624
1625PyDoc_STRVAR(float_getformat_doc,
1626"float.__getformat__(typestr) -> string\n"
1627"\n"
1628"You probably don't want to use this function. It exists mainly to be\n"
1629"used in Python's test suite.\n"
1630"\n"
1631"typestr must be 'double' or 'float'. This function returns whichever of\n"
1632"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1633"format of floating point numbers used by the C type named by typestr.");
1634
1635static PyObject *
1636float_setformat(PyTypeObject *v, PyObject* args)
1637{
1638 char* typestr;
1639 char* format;
1640 float_format_type f;
1641 float_format_type detected;
1642 float_format_type *p;
1643
1644 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1645 return NULL;
1646
1647 if (strcmp(typestr, "double") == 0) {
1648 p = &double_format;
1649 detected = detected_double_format;
1650 }
1651 else if (strcmp(typestr, "float") == 0) {
1652 p = &float_format;
1653 detected = detected_float_format;
1654 }
1655 else {
1656 PyErr_SetString(PyExc_ValueError,
1657 "__setformat__() argument 1 must "
1658 "be 'double' or 'float'");
1659 return NULL;
1660 }
1661
1662 if (strcmp(format, "unknown") == 0) {
1663 f = unknown_format;
1664 }
1665 else if (strcmp(format, "IEEE, little-endian") == 0) {
1666 f = ieee_little_endian_format;
1667 }
1668 else if (strcmp(format, "IEEE, big-endian") == 0) {
1669 f = ieee_big_endian_format;
1670 }
1671 else {
1672 PyErr_SetString(PyExc_ValueError,
1673 "__setformat__() argument 2 must be "
1674 "'unknown', 'IEEE, little-endian' or "
1675 "'IEEE, big-endian'");
1676 return NULL;
1677
1678 }
1679
1680 if (f != unknown_format && f != detected) {
1681 PyErr_Format(PyExc_ValueError,
1682 "can only set %s format to 'unknown' or the "
1683 "detected platform value", typestr);
1684 return NULL;
1685 }
1686
1687 *p = f;
1688 Py_RETURN_NONE;
1689}
1690
1691PyDoc_STRVAR(float_setformat_doc,
1692"float.__setformat__(typestr, fmt) -> None\n"
1693"\n"
1694"You probably don't want to use this function. It exists mainly to be\n"
1695"used in Python's test suite.\n"
1696"\n"
1697"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1698"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1699"one of the latter two if it appears to match the underlying C reality.\n"
1700"\n"
1701"Overrides the automatic determination of C-level floating point type.\n"
1702"This affects how floats are converted to and from binary strings.");
1703
Guido van Rossumb43daf72007-08-01 18:08:08 +00001704static PyObject *
1705float_getzero(PyObject *v, void *closure)
1706{
1707 return PyFloat_FromDouble(0.0);
1708}
1709
Eric Smith8c663262007-08-25 02:26:07 +00001710static PyObject *
1711float__format__(PyObject *self, PyObject *args)
1712{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001713 PyObject *format_spec;
1714
1715 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1716 return NULL;
1717 return _PyFloat_FormatAdvanced(self,
1718 PyUnicode_AS_UNICODE(format_spec),
1719 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001720}
1721
1722PyDoc_STRVAR(float__format__doc,
1723"float.__format__(format_spec) -> string\n"
1724"\n"
1725"Formats the float according to format_spec.");
1726
1727
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001728static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001729 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001730 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001731 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1732 "Returns the Integral closest to x between 0 and x."},
1733 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1734 "Returns the Integral closest to x, rounding half toward even.\n"
1735 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001736 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1737 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001738 {"fromhex", (PyCFunction)float_fromhex,
1739 METH_O|METH_CLASS, float_fromhex_doc},
1740 {"hex", (PyCFunction)float_hex,
1741 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001742 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1743 "Returns True if the float is an integer."},
1744#if 0
1745 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1746 "Returns True if the float is positive or negative infinite."},
1747 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1748 "Returns True if the float is finite, neither infinite nor NaN."},
1749 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1750 "Returns True if the float is not a number (NaN)."},
1751#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001752 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001753 {"__getformat__", (PyCFunction)float_getformat,
1754 METH_O|METH_CLASS, float_getformat_doc},
1755 {"__setformat__", (PyCFunction)float_setformat,
1756 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001757 {"__format__", (PyCFunction)float__format__,
1758 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001759 {NULL, NULL} /* sentinel */
1760};
1761
Guido van Rossumb43daf72007-08-01 18:08:08 +00001762static PyGetSetDef float_getset[] = {
1763 {"real",
1764 (getter)float_float, (setter)NULL,
1765 "the real part of a complex number",
1766 NULL},
1767 {"imag",
1768 (getter)float_getzero, (setter)NULL,
1769 "the imaginary part of a complex number",
1770 NULL},
1771 {NULL} /* Sentinel */
1772};
1773
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001774PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775"float(x) -> floating point number\n\
1776\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001777Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778
1779
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001780static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001781 float_add, /*nb_add*/
1782 float_sub, /*nb_subtract*/
1783 float_mul, /*nb_multiply*/
1784 float_rem, /*nb_remainder*/
1785 float_divmod, /*nb_divmod*/
1786 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001787 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001788 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001789 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001790 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001791 0, /*nb_invert*/
1792 0, /*nb_lshift*/
1793 0, /*nb_rshift*/
1794 0, /*nb_and*/
1795 0, /*nb_xor*/
1796 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001797 float_trunc, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00001798 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001799 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001800 0, /* nb_inplace_add */
1801 0, /* nb_inplace_subtract */
1802 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001803 0, /* nb_inplace_remainder */
1804 0, /* nb_inplace_power */
1805 0, /* nb_inplace_lshift */
1806 0, /* nb_inplace_rshift */
1807 0, /* nb_inplace_and */
1808 0, /* nb_inplace_xor */
1809 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001810 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001811 float_div, /* nb_true_divide */
1812 0, /* nb_inplace_floor_divide */
1813 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001814};
1815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001816PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001817 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001818 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001820 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001822 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 0, /* tp_getattr */
1824 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001825 0, /* tp_reserved */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 (reprfunc)float_repr, /* tp_repr */
1827 &float_as_number, /* tp_as_number */
1828 0, /* tp_as_sequence */
1829 0, /* tp_as_mapping */
1830 (hashfunc)float_hash, /* tp_hash */
1831 0, /* tp_call */
1832 (reprfunc)float_str, /* tp_str */
1833 PyObject_GenericGetAttr, /* tp_getattro */
1834 0, /* tp_setattro */
1835 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001836 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 float_doc, /* tp_doc */
1838 0, /* tp_traverse */
1839 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001840 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 0, /* tp_weaklistoffset */
1842 0, /* tp_iter */
1843 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001844 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001846 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 0, /* tp_base */
1848 0, /* tp_dict */
1849 0, /* tp_descr_get */
1850 0, /* tp_descr_set */
1851 0, /* tp_dictoffset */
1852 0, /* tp_init */
1853 0, /* tp_alloc */
1854 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001856
1857void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001858_PyFloat_Init(void)
1859{
1860 /* We attempt to determine if this machine is using IEEE
1861 floating point formats by peering at the bits of some
1862 carefully chosen values. If it looks like we are on an
1863 IEEE platform, the float packing/unpacking routines can
1864 just copy bits, if not they resort to arithmetic & shifts
1865 and masks. The shifts & masks approach works on all finite
1866 values, but what happens to infinities, NaNs and signed
1867 zeroes on packing is an accident, and attempting to unpack
1868 a NaN or an infinity will raise an exception.
1869
1870 Note that if we're on some whacked-out platform which uses
1871 IEEE formats but isn't strictly little-endian or big-
1872 endian, we will fall back to the portable shifts & masks
1873 method. */
1874
1875#if SIZEOF_DOUBLE == 8
1876 {
1877 double x = 9006104071832581.0;
1878 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1879 detected_double_format = ieee_big_endian_format;
1880 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1881 detected_double_format = ieee_little_endian_format;
1882 else
1883 detected_double_format = unknown_format;
1884 }
1885#else
1886 detected_double_format = unknown_format;
1887#endif
1888
1889#if SIZEOF_FLOAT == 4
1890 {
1891 float y = 16711938.0;
1892 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1893 detected_float_format = ieee_big_endian_format;
1894 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1895 detected_float_format = ieee_little_endian_format;
1896 else
1897 detected_float_format = unknown_format;
1898 }
1899#else
1900 detected_float_format = unknown_format;
1901#endif
1902
1903 double_format = detected_double_format;
1904 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001905
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001906 /* Init float info */
1907 if (FloatInfoType.tp_name == 0)
1908 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001909}
1910
Georg Brandl2ee470f2008-07-16 12:55:28 +00001911int
1912PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001913{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001914 PyFloatObject *p;
1915 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001916 int i;
Gregory P. Smithd8fa68b2008-08-18 01:05:25 +00001917 int u; /* remaining unfreed floats per block */
Georg Brandl2ee470f2008-07-16 12:55:28 +00001918 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001919
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001920 list = block_list;
1921 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001922 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001923 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001924 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001925 for (i = 0, p = &list->objects[0];
1926 i < N_FLOATOBJECTS;
1927 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001928 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001929 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001930 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001931 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001932 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001933 list->next = block_list;
1934 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001935 for (i = 0, p = &list->objects[0];
1936 i < N_FLOATOBJECTS;
1937 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001938 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001939 Py_REFCNT(p) == 0) {
1940 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001941 free_list;
1942 free_list = p;
1943 }
1944 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001945 }
1946 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001947 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001948 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001949 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001950 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001951 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001952 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001953}
1954
1955void
1956PyFloat_Fini(void)
1957{
1958 PyFloatObject *p;
1959 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001960 int i;
1961 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001962
Georg Brandl2ee470f2008-07-16 12:55:28 +00001963 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001964
Guido van Rossum3fce8831999-03-12 19:43:17 +00001965 if (!Py_VerboseFlag)
1966 return;
1967 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001968 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001969 fprintf(stderr, "\n");
1970 }
1971 else {
1972 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001973 ": %d unfreed float%s\n",
1974 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001975 }
1976 if (Py_VerboseFlag > 1) {
1977 list = block_list;
1978 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001979 for (i = 0, p = &list->objects[0];
1980 i < N_FLOATOBJECTS;
1981 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001982 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001983 Py_REFCNT(p) != 0) {
Eric Smith0923d1d2009-04-16 20:16:10 +00001984 char *buf = PyOS_double_to_string(
1985 PyFloat_AS_DOUBLE(p), 'r',
1986 0, 0, NULL);
1987 if (buf) {
1988 /* XXX(twouters) cast
1989 refcount to long
1990 until %zd is
1991 universally
1992 available
1993 */
1994 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001995 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001996 p, (long)Py_REFCNT(p), buf);
Eric Smith0923d1d2009-04-16 20:16:10 +00001997 PyMem_Free(buf);
1998 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001999 }
2000 }
2001 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002002 }
2003 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002004}
Tim Peters9905b942003-03-20 20:53:32 +00002005
2006/*----------------------------------------------------------------------------
2007 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002008 */
2009int
2010_PyFloat_Pack4(double x, unsigned char *p, int le)
2011{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012 if (float_format == unknown_format) {
2013 unsigned char sign;
2014 int e;
2015 double f;
2016 unsigned int fbits;
2017 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002018
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002019 if (le) {
2020 p += 3;
2021 incr = -1;
2022 }
Tim Peters9905b942003-03-20 20:53:32 +00002023
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024 if (x < 0) {
2025 sign = 1;
2026 x = -x;
2027 }
2028 else
2029 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002030
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002031 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002032
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002033 /* Normalize f to be in the range [1.0, 2.0) */
2034 if (0.5 <= f && f < 1.0) {
2035 f *= 2.0;
2036 e--;
2037 }
2038 else if (f == 0.0)
2039 e = 0;
2040 else {
2041 PyErr_SetString(PyExc_SystemError,
2042 "frexp() result out of range");
2043 return -1;
2044 }
2045
2046 if (e >= 128)
2047 goto Overflow;
2048 else if (e < -126) {
2049 /* Gradual underflow */
2050 f = ldexp(f, 126 + e);
2051 e = 0;
2052 }
2053 else if (!(e == 0 && f == 0.0)) {
2054 e += 127;
2055 f -= 1.0; /* Get rid of leading 1 */
2056 }
2057
2058 f *= 8388608.0; /* 2**23 */
2059 fbits = (unsigned int)(f + 0.5); /* Round */
2060 assert(fbits <= 8388608);
2061 if (fbits >> 23) {
2062 /* The carry propagated out of a string of 23 1 bits. */
2063 fbits = 0;
2064 ++e;
2065 if (e >= 255)
2066 goto Overflow;
2067 }
2068
2069 /* First byte */
2070 *p = (sign << 7) | (e >> 1);
2071 p += incr;
2072
2073 /* Second byte */
2074 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2075 p += incr;
2076
2077 /* Third byte */
2078 *p = (fbits >> 8) & 0xFF;
2079 p += incr;
2080
2081 /* Fourth byte */
2082 *p = fbits & 0xFF;
2083
2084 /* Done */
2085 return 0;
2086
Tim Peters9905b942003-03-20 20:53:32 +00002087 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002089 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002090 const char *s = (char*)&y;
2091 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002092
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002093 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2094 goto Overflow;
2095
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002096 if ((float_format == ieee_little_endian_format && !le)
2097 || (float_format == ieee_big_endian_format && le)) {
2098 p += 3;
2099 incr = -1;
2100 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002101
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102 for (i = 0; i < 4; i++) {
2103 *p = *s++;
2104 p += incr;
2105 }
2106 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002107 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002108 Overflow:
2109 PyErr_SetString(PyExc_OverflowError,
2110 "float too large to pack with f format");
2111 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002112}
2113
2114int
2115_PyFloat_Pack8(double x, unsigned char *p, int le)
2116{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117 if (double_format == unknown_format) {
2118 unsigned char sign;
2119 int e;
2120 double f;
2121 unsigned int fhi, flo;
2122 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002123
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124 if (le) {
2125 p += 7;
2126 incr = -1;
2127 }
Tim Peters9905b942003-03-20 20:53:32 +00002128
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129 if (x < 0) {
2130 sign = 1;
2131 x = -x;
2132 }
2133 else
2134 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002135
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002136 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002137
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138 /* Normalize f to be in the range [1.0, 2.0) */
2139 if (0.5 <= f && f < 1.0) {
2140 f *= 2.0;
2141 e--;
2142 }
2143 else if (f == 0.0)
2144 e = 0;
2145 else {
2146 PyErr_SetString(PyExc_SystemError,
2147 "frexp() result out of range");
2148 return -1;
2149 }
2150
2151 if (e >= 1024)
2152 goto Overflow;
2153 else if (e < -1022) {
2154 /* Gradual underflow */
2155 f = ldexp(f, 1022 + e);
2156 e = 0;
2157 }
2158 else if (!(e == 0 && f == 0.0)) {
2159 e += 1023;
2160 f -= 1.0; /* Get rid of leading 1 */
2161 }
2162
2163 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2164 f *= 268435456.0; /* 2**28 */
2165 fhi = (unsigned int)f; /* Truncate */
2166 assert(fhi < 268435456);
2167
2168 f -= (double)fhi;
2169 f *= 16777216.0; /* 2**24 */
2170 flo = (unsigned int)(f + 0.5); /* Round */
2171 assert(flo <= 16777216);
2172 if (flo >> 24) {
2173 /* The carry propagated out of a string of 24 1 bits. */
2174 flo = 0;
2175 ++fhi;
2176 if (fhi >> 28) {
2177 /* And it also progagated out of the next 28 bits. */
2178 fhi = 0;
2179 ++e;
2180 if (e >= 2047)
2181 goto Overflow;
2182 }
2183 }
2184
2185 /* First byte */
2186 *p = (sign << 7) | (e >> 4);
2187 p += incr;
2188
2189 /* Second byte */
2190 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2191 p += incr;
2192
2193 /* Third byte */
2194 *p = (fhi >> 16) & 0xFF;
2195 p += incr;
2196
2197 /* Fourth byte */
2198 *p = (fhi >> 8) & 0xFF;
2199 p += incr;
2200
2201 /* Fifth byte */
2202 *p = fhi & 0xFF;
2203 p += incr;
2204
2205 /* Sixth byte */
2206 *p = (flo >> 16) & 0xFF;
2207 p += incr;
2208
2209 /* Seventh byte */
2210 *p = (flo >> 8) & 0xFF;
2211 p += incr;
2212
2213 /* Eighth byte */
2214 *p = flo & 0xFF;
2215 p += incr;
2216
2217 /* Done */
2218 return 0;
2219
2220 Overflow:
2221 PyErr_SetString(PyExc_OverflowError,
2222 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002223 return -1;
2224 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225 else {
2226 const char *s = (char*)&x;
2227 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002228
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002229 if ((double_format == ieee_little_endian_format && !le)
2230 || (double_format == ieee_big_endian_format && le)) {
2231 p += 7;
2232 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002233 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234
2235 for (i = 0; i < 8; i++) {
2236 *p = *s++;
2237 p += incr;
2238 }
2239 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002240 }
Tim Peters9905b942003-03-20 20:53:32 +00002241}
2242
2243double
2244_PyFloat_Unpack4(const unsigned char *p, int le)
2245{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246 if (float_format == unknown_format) {
2247 unsigned char sign;
2248 int e;
2249 unsigned int f;
2250 double x;
2251 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002252
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253 if (le) {
2254 p += 3;
2255 incr = -1;
2256 }
2257
2258 /* First byte */
2259 sign = (*p >> 7) & 1;
2260 e = (*p & 0x7F) << 1;
2261 p += incr;
2262
2263 /* Second byte */
2264 e |= (*p >> 7) & 1;
2265 f = (*p & 0x7F) << 16;
2266 p += incr;
2267
2268 if (e == 255) {
2269 PyErr_SetString(
2270 PyExc_ValueError,
2271 "can't unpack IEEE 754 special value "
2272 "on non-IEEE platform");
2273 return -1;
2274 }
2275
2276 /* Third byte */
2277 f |= *p << 8;
2278 p += incr;
2279
2280 /* Fourth byte */
2281 f |= *p;
2282
2283 x = (double)f / 8388608.0;
2284
2285 /* XXX This sadly ignores Inf/NaN issues */
2286 if (e == 0)
2287 e = -126;
2288 else {
2289 x += 1.0;
2290 e -= 127;
2291 }
2292 x = ldexp(x, e);
2293
2294 if (sign)
2295 x = -x;
2296
2297 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002298 }
Tim Peters9905b942003-03-20 20:53:32 +00002299 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002300 float x;
2301
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302 if ((float_format == ieee_little_endian_format && !le)
2303 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002304 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305 char *d = &buf[3];
2306 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002307
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308 for (i = 0; i < 4; i++) {
2309 *d-- = *p++;
2310 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002311 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312 }
2313 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002314 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002316
2317 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318 }
Tim Peters9905b942003-03-20 20:53:32 +00002319}
2320
2321double
2322_PyFloat_Unpack8(const unsigned char *p, int le)
2323{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324 if (double_format == unknown_format) {
2325 unsigned char sign;
2326 int e;
2327 unsigned int fhi, flo;
2328 double x;
2329 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002330
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331 if (le) {
2332 p += 7;
2333 incr = -1;
2334 }
2335
2336 /* First byte */
2337 sign = (*p >> 7) & 1;
2338 e = (*p & 0x7F) << 4;
2339
2340 p += incr;
2341
2342 /* Second byte */
2343 e |= (*p >> 4) & 0xF;
2344 fhi = (*p & 0xF) << 24;
2345 p += incr;
2346
2347 if (e == 2047) {
2348 PyErr_SetString(
2349 PyExc_ValueError,
2350 "can't unpack IEEE 754 special value "
2351 "on non-IEEE platform");
2352 return -1.0;
2353 }
2354
2355 /* Third byte */
2356 fhi |= *p << 16;
2357 p += incr;
2358
2359 /* Fourth byte */
2360 fhi |= *p << 8;
2361 p += incr;
2362
2363 /* Fifth byte */
2364 fhi |= *p;
2365 p += incr;
2366
2367 /* Sixth byte */
2368 flo = *p << 16;
2369 p += incr;
2370
2371 /* Seventh byte */
2372 flo |= *p << 8;
2373 p += incr;
2374
2375 /* Eighth byte */
2376 flo |= *p;
2377
2378 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2379 x /= 268435456.0; /* 2**28 */
2380
2381 if (e == 0)
2382 e = -1022;
2383 else {
2384 x += 1.0;
2385 e -= 1023;
2386 }
2387 x = ldexp(x, e);
2388
2389 if (sign)
2390 x = -x;
2391
2392 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002393 }
Tim Peters9905b942003-03-20 20:53:32 +00002394 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002395 double x;
2396
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002397 if ((double_format == ieee_little_endian_format && !le)
2398 || (double_format == ieee_big_endian_format && le)) {
2399 char buf[8];
2400 char *d = &buf[7];
2401 int i;
2402
2403 for (i = 0; i < 8; i++) {
2404 *d-- = *p++;
2405 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002406 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002407 }
2408 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002409 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002410 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002411
2412 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002413 }
Tim Peters9905b942003-03-20 20:53:32 +00002414}