blob: f18e7dd85e4260e8a3861a685b357d3af2a58994 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson65fe25e2008-07-16 11:30:51 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Christian Heimesbbe741d2008-03-28 10:53:29 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Guido van Rossum6923e131990-11-02 17:50:43 +000022
Christian Heimes969fe572008-01-25 11:23:10 +000023#ifdef _OSF_SOURCE
24/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
25extern int finite(double);
26#endif
27
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000029#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000030#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000031#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000032
Guido van Rossum3fce8831999-03-12 19:43:17 +000033struct _floatblock {
34 struct _floatblock *next;
35 PyFloatObject objects[N_FLOATOBJECTS];
36};
37
38typedef struct _floatblock PyFloatBlock;
39
40static PyFloatBlock *block_list = NULL;
41static PyFloatObject *free_list = NULL;
42
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000044fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045{
46 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
48 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000050 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000051 ((PyFloatBlock *)p)->next = block_list;
52 block_list = (PyFloatBlock *)p;
53 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 q = p + N_FLOATOBJECTS;
55 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000056 Py_TYPE(q) = (struct _typeobject *)(q-1);
57 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 return p + N_FLOATOBJECTS - 1;
59}
60
Christian Heimes93852662007-12-01 12:22:32 +000061double
62PyFloat_GetMax(void)
63{
64 return DBL_MAX;
65}
66
67double
68PyFloat_GetMin(void)
69{
70 return DBL_MIN;
71}
72
Christian Heimesd32ed6f2008-01-14 18:49:24 +000073static PyTypeObject FloatInfoType;
74
75PyDoc_STRVAR(floatinfo__doc__,
76"sys.floatinfo\n\
77\n\
78A structseq holding information about the float type. It contains low level\n\
79information about the precision and internal representation. Please study\n\
80your system's :file:`float.h` for more information.");
81
82static PyStructSequence_Field floatinfo_fields[] = {
83 {"max", "DBL_MAX -- maximum representable finite float"},
84 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
85 "is representable"},
86 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
87 "is representable"},
88 {"min", "DBL_MIN -- Minimum positive normalizer float"},
89 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
90 "is a normalized float"},
91 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
92 "a normalized"},
93 {"dig", "DBL_DIG -- digits"},
94 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
95 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
96 "representable float"},
97 {"radix", "FLT_RADIX -- radix of exponent"},
98 {"rounds", "FLT_ROUNDS -- addition rounds"},
99 {0}
100};
101
102static PyStructSequence_Desc floatinfo_desc = {
103 "sys.floatinfo", /* name */
104 floatinfo__doc__, /* doc */
105 floatinfo_fields, /* fields */
106 11
107};
108
Christian Heimes93852662007-12-01 12:22:32 +0000109PyObject *
110PyFloat_GetInfo(void)
111{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000112 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000113 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000114
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000115 floatinfo = PyStructSequence_New(&FloatInfoType);
116 if (floatinfo == NULL) {
117 return NULL;
118 }
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120#define SetIntFlag(flag) \
121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
122#define SetDblFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000124
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000125 SetDblFlag(DBL_MAX);
126 SetIntFlag(DBL_MAX_EXP);
127 SetIntFlag(DBL_MAX_10_EXP);
128 SetDblFlag(DBL_MIN);
129 SetIntFlag(DBL_MIN_EXP);
130 SetIntFlag(DBL_MIN_10_EXP);
131 SetIntFlag(DBL_DIG);
132 SetIntFlag(DBL_MANT_DIG);
133 SetDblFlag(DBL_EPSILON);
134 SetIntFlag(FLT_RADIX);
135 SetIntFlag(FLT_ROUNDS);
136#undef SetIntFlag
137#undef SetDblFlag
138
139 if (PyErr_Occurred()) {
140 Py_CLEAR(floatinfo);
141 return NULL;
142 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000143 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000144}
145
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000154 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000155 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000163PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164{
Christian Heimes99170a52007-12-19 02:07:34 +0000165 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000167 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000172 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000178 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000180 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000181 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000183 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000186 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000189
Guido van Rossum4c08d552000-03-10 22:55:18 +0000190 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191 while (*s && isspace(Py_CHARMASK(*s)))
192 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000193 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000194 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000195 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 }
Christian Heimes99170a52007-12-19 02:07:34 +0000197 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000198 /* We don't care about overflow or underflow. If the platform supports
199 * them, infinities and signed zeroes (on underflow) are fine.
200 * However, strtod can return 0 for denormalized numbers, where atof
201 * does not. So (alas!) we special-case a zero result. Note that
202 * whether strtod sets errno on underflow is not defined, so we can't
203 * key off errno.
204 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000205 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000206 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000207 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000209 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000210 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000211 if (end > last)
212 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000213 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000214 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000215 char *p = (char*)sp;
216 int sign = 1;
217
218 if (*p == '-') {
219 sign = -1;
220 p++;
221 }
222 if (*p == '+') {
223 p++;
224 }
225 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000226 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000227 }
228#ifdef Py_NAN
229 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000230 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000231 }
232#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000233 PyOS_snprintf(buffer, sizeof(buffer),
234 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000235 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000236 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000237 }
238 /* Since end != s, the platform made *some* kind of sense out
239 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000240 while (*end && isspace(Py_CHARMASK(*end)))
241 end++;
242 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000243 PyOS_snprintf(buffer, sizeof(buffer),
244 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000245 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000246 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000247 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000248 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 PyErr_SetString(PyExc_ValueError,
250 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000251 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000252 }
Tim Petersef14d732000-09-23 03:39:17 +0000253 if (x == 0.0) {
254 /* See above -- may have been strtod being anal
255 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000256 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000257 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000258 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000259 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000261 result = PyFloat_FromDouble(x);
262 error:
263 if (s_buffer)
264 PyMem_FREE(s_buffer);
265 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266}
267
Guido van Rossum234f9421993-06-17 12:35:49 +0000268static void
Fred Drakefd99de62000-07-09 05:02:18 +0000269float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000270{
Guido van Rossum9475a232001-10-05 20:51:39 +0000271 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000272 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000273 free_list = op;
274 }
275 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000276 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000277}
278
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279double
Fred Drakefd99de62000-07-09 05:02:18 +0000280PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 PyNumberMethods *nb;
283 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000286 if (op && PyFloat_Check(op))
287 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000289 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 return -1;
292 }
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Christian Heimes90aa7642007-12-19 02:45:37 +0000294 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000295 PyErr_SetString(PyExc_TypeError, "a float is required");
296 return -1;
297 }
298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300 if (fo == NULL)
301 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 if (!PyFloat_Check(fo)) {
303 PyErr_SetString(PyExc_TypeError,
304 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 return -1;
306 }
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 val = PyFloat_AS_DOUBLE(fo);
309 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312}
313
314/* Methods */
315
Tim Peters97019e42001-11-28 22:43:45 +0000316static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000317format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318{
319 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000320 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000321 int i;
322
323 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324 We want float numbers to be recognizable as such,
325 i.e., they should contain a decimal point or an exponent.
326 However, %g may print the number as an integer;
327 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000328
Martin v. Löwis737ea822004-06-08 18:52:54 +0000329 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000330 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331 cp = buf;
332 if (*cp == '-')
333 cp++;
334 for (; *cp != '\0'; cp++) {
335 /* Any non-digit means it's not an integer;
336 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000337 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 break;
339 }
340 if (*cp == '\0') {
341 *cp++ = '.';
342 *cp++ = '0';
343 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000344 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345 }
Christian Heimes99170a52007-12-19 02:07:34 +0000346 /* Checking the next three chars should be more than enough to
347 * detect inf or nan, even on Windows. We check for inf or nan
348 * at last because they are rare cases.
349 */
350 for (i=0; *cp != '\0' && i<3; cp++, i++) {
351 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
352 continue;
353 /* found something that is neither a digit nor point
354 * it might be a NaN or INF
355 */
356#ifdef Py_NAN
357 if (Py_IS_NAN(ob_fval)) {
358 strcpy(buf, "nan");
359 }
360 else
361#endif
362 if (Py_IS_INFINITY(ob_fval)) {
363 cp = buf;
364 if (*cp == '-')
365 cp++;
366 strcpy(cp, "inf");
367 }
368 break;
369 }
370
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371}
372
Neal Norwitz545686b2006-12-28 04:45:06 +0000373static void
374format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000375{
Neal Norwitz545686b2006-12-28 04:45:06 +0000376 assert(PyFloat_Check(v));
377 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000378}
379
Neil Schemenauer32117e52001-01-04 01:44:34 +0000380/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000381 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000382 set to NULL, and the function invoking this macro returns NULL. If
383 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
384 stored in obj, and returned from the function invoking this macro.
385*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000386#define CONVERT_TO_DOUBLE(obj, dbl) \
387 if (PyFloat_Check(obj)) \
388 dbl = PyFloat_AS_DOUBLE(obj); \
389 else if (convert_to_double(&(obj), &(dbl)) < 0) \
390 return obj;
391
392static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000393convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000394{
395 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000396
Guido van Rossumddefaf32007-01-14 03:31:43 +0000397 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000398 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000399 if (*dbl == -1.0 && PyErr_Occurred()) {
400 *v = NULL;
401 return -1;
402 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000403 }
404 else {
405 Py_INCREF(Py_NotImplemented);
406 *v = Py_NotImplemented;
407 return -1;
408 }
409 return 0;
410}
411
Guido van Rossum57072eb1999-12-23 19:00:28 +0000412/* Precisions used by repr() and str(), respectively.
413
414 The repr() precision (17 significant decimal digits) is the minimal number
415 that is guaranteed to have enough precision so that if the number is read
416 back in the exact same binary value is recreated. This is true for IEEE
417 floating point by design, and also happens to work for all other modern
418 hardware.
419
420 The str() precision is chosen so that in most cases, the rounding noise
421 created by various operations is suppressed, while giving plenty of
422 precision for practical use.
423
424*/
425
426#define PREC_REPR 17
427#define PREC_STR 12
428
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000430float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431{
Christian Heimesb76922a2007-12-11 01:06:40 +0000432 char buf[100];
433 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesb76922a2007-12-11 01:06:40 +0000434
Walter Dörwald1ab83302007-05-18 17:15:44 +0000435 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000436}
437
438static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000439float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000440{
441 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000442 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000443 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444}
445
Tim Peters307fa782004-09-23 08:06:40 +0000446/* Comparison is pretty much a nightmare. When comparing float to float,
447 * we do it as straightforwardly (and long-windedly) as conceivable, so
448 * that, e.g., Python x == y delivers the same result as the platform
449 * C x == y when x and/or y is a NaN.
450 * When mixing float with an integer type, there's no good *uniform* approach.
451 * Converting the double to an integer obviously doesn't work, since we
452 * may lose info from fractional bits. Converting the integer to a double
453 * also has two failure modes: (1) a long int may trigger overflow (too
454 * large to fit in the dynamic range of a C double); (2) even a C long may have
455 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
456 * 63 bits of precision, but a C double probably has only 53), and then
457 * we can falsely claim equality when low-order integer bits are lost by
458 * coercion to double. So this part is painful too.
459 */
460
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000461static PyObject*
462float_richcompare(PyObject *v, PyObject *w, int op)
463{
464 double i, j;
465 int r = 0;
466
Tim Peters307fa782004-09-23 08:06:40 +0000467 assert(PyFloat_Check(v));
468 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000469
Tim Peters307fa782004-09-23 08:06:40 +0000470 /* Switch on the type of w. Set i and j to doubles to be compared,
471 * and op to the richcomp to use.
472 */
473 if (PyFloat_Check(w))
474 j = PyFloat_AS_DOUBLE(w);
475
Thomas Wouters477c8d52006-05-27 19:21:47 +0000476 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000477 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000478 /* If i is an infinity, its magnitude exceeds any
479 * finite integer, so it doesn't matter which int we
480 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000481 */
482 j = 0.0;
483 else
484 goto Unimplemented;
485 }
486
Tim Peters307fa782004-09-23 08:06:40 +0000487 else if (PyLong_Check(w)) {
488 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
489 int wsign = _PyLong_Sign(w);
490 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000491 int exponent;
492
493 if (vsign != wsign) {
494 /* Magnitudes are irrelevant -- the signs alone
495 * determine the outcome.
496 */
497 i = (double)vsign;
498 j = (double)wsign;
499 goto Compare;
500 }
501 /* The signs are the same. */
502 /* Convert w to a double if it fits. In particular, 0 fits. */
503 nbits = _PyLong_NumBits(w);
504 if (nbits == (size_t)-1 && PyErr_Occurred()) {
505 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000506 * to hold the # of bits. Replace with little doubles
507 * that give the same outcome -- w is so large that
508 * its magnitude must exceed the magnitude of any
509 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000510 */
511 PyErr_Clear();
512 i = (double)vsign;
513 assert(wsign != 0);
514 j = wsign * 2.0;
515 goto Compare;
516 }
517 if (nbits <= 48) {
518 j = PyLong_AsDouble(w);
519 /* It's impossible that <= 48 bits overflowed. */
520 assert(j != -1.0 || ! PyErr_Occurred());
521 goto Compare;
522 }
523 assert(wsign != 0); /* else nbits was 0 */
524 assert(vsign != 0); /* if vsign were 0, then since wsign is
525 * not 0, we would have taken the
526 * vsign != wsign branch at the start */
527 /* We want to work with non-negative numbers. */
528 if (vsign < 0) {
529 /* "Multiply both sides" by -1; this also swaps the
530 * comparator.
531 */
532 i = -i;
533 op = _Py_SwappedOp[op];
534 }
535 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000536 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000537 /* exponent is the # of bits in v before the radix point;
538 * we know that nbits (the # of bits in w) > 48 at this point
539 */
540 if (exponent < 0 || (size_t)exponent < nbits) {
541 i = 1.0;
542 j = 2.0;
543 goto Compare;
544 }
545 if ((size_t)exponent > nbits) {
546 i = 2.0;
547 j = 1.0;
548 goto Compare;
549 }
550 /* v and w have the same number of bits before the radix
551 * point. Construct two longs that have the same comparison
552 * outcome.
553 */
554 {
555 double fracpart;
556 double intpart;
557 PyObject *result = NULL;
558 PyObject *one = NULL;
559 PyObject *vv = NULL;
560 PyObject *ww = w;
561
562 if (wsign < 0) {
563 ww = PyNumber_Negative(w);
564 if (ww == NULL)
565 goto Error;
566 }
567 else
568 Py_INCREF(ww);
569
570 fracpart = modf(i, &intpart);
571 vv = PyLong_FromDouble(intpart);
572 if (vv == NULL)
573 goto Error;
574
575 if (fracpart != 0.0) {
576 /* Shift left, and or a 1 bit into vv
577 * to represent the lost fraction.
578 */
579 PyObject *temp;
580
Christian Heimes217cfd12007-12-02 14:31:20 +0000581 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000582 if (one == NULL)
583 goto Error;
584
585 temp = PyNumber_Lshift(ww, one);
586 if (temp == NULL)
587 goto Error;
588 Py_DECREF(ww);
589 ww = temp;
590
591 temp = PyNumber_Lshift(vv, one);
592 if (temp == NULL)
593 goto Error;
594 Py_DECREF(vv);
595 vv = temp;
596
597 temp = PyNumber_Or(vv, one);
598 if (temp == NULL)
599 goto Error;
600 Py_DECREF(vv);
601 vv = temp;
602 }
603
604 r = PyObject_RichCompareBool(vv, ww, op);
605 if (r < 0)
606 goto Error;
607 result = PyBool_FromLong(r);
608 Error:
609 Py_XDECREF(vv);
610 Py_XDECREF(ww);
611 Py_XDECREF(one);
612 return result;
613 }
614 } /* else if (PyLong_Check(w)) */
615
616 else /* w isn't float, int, or long */
617 goto Unimplemented;
618
619 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000620 PyFPE_START_PROTECT("richcompare", return NULL)
621 switch (op) {
622 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000623 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000624 break;
625 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000626 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000627 break;
628 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000629 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000630 break;
631 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000632 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633 break;
634 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000635 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000636 break;
637 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000638 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000639 break;
640 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000641 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000642 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000643
644 Unimplemented:
645 Py_INCREF(Py_NotImplemented);
646 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000647}
648
Guido van Rossum9bfef441993-03-29 10:43:31 +0000649static long
Fred Drakefd99de62000-07-09 05:02:18 +0000650float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000651{
Tim Peters39dce292000-08-15 03:34:48 +0000652 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000653}
654
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000656float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000658 double a,b;
659 CONVERT_TO_DOUBLE(v, a);
660 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000661 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000662 a = a + b;
663 PyFPE_END_PROTECT(a)
664 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000665}
666
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000668float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000669{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000670 double a,b;
671 CONVERT_TO_DOUBLE(v, a);
672 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000673 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000674 a = a - b;
675 PyFPE_END_PROTECT(a)
676 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000677}
678
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000680float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000681{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000682 double a,b;
683 CONVERT_TO_DOUBLE(v, a);
684 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000685 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000686 a = a * b;
687 PyFPE_END_PROTECT(a)
688 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000689}
690
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000692float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000693{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000694 double a,b;
695 CONVERT_TO_DOUBLE(v, a);
696 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000697#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000698 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000699 PyErr_SetString(PyExc_ZeroDivisionError,
700 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000701 return NULL;
702 }
Christian Heimes53876d92008-04-19 00:31:39 +0000703#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000704 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000705 a = a / b;
706 PyFPE_END_PROTECT(a)
707 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000708}
709
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000710static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000711float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000713 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000714 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000715 CONVERT_TO_DOUBLE(v, vx);
716 CONVERT_TO_DOUBLE(w, wx);
717#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000719 PyErr_SetString(PyExc_ZeroDivisionError,
720 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721 return NULL;
722 }
Christian Heimes53876d92008-04-19 00:31:39 +0000723#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000724 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000725 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000726 /* note: checking mod*wx < 0 is incorrect -- underflows to
727 0 if wx < sqrt(smallest nonzero double) */
728 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000729 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000730 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000731 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733}
734
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000736float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000737{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000738 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000739 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000740 CONVERT_TO_DOUBLE(v, vx);
741 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000742 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000744 return NULL;
745 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000746 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000747 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000748 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000749 exact multiple of wx. But this is fp arithmetic, and fp
750 vx - mod is an approximation; the result is that div may
751 not be an exact integral value after the division, although
752 it will always be very close to one.
753 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000754 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000755 if (mod) {
756 /* ensure the remainder has the same sign as the denominator */
757 if ((wx < 0) != (mod < 0)) {
758 mod += wx;
759 div -= 1.0;
760 }
761 }
762 else {
763 /* the remainder is zero, and in the presence of signed zeroes
764 fmod returns different results across platforms; ensure
765 it has the same sign as the denominator; we'd like to do
766 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000767 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000768 if (wx < 0.0)
769 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000770 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000771 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000772 if (div) {
773 floordiv = floor(div);
774 if (div - floordiv > 0.5)
775 floordiv += 1.0;
776 }
777 else {
778 /* div is zero - get the same sign as the true quotient */
779 div *= div; /* hide "div = +0" from optimizers */
780 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
781 }
782 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000783 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000784}
785
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000786static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000787float_floor_div(PyObject *v, PyObject *w)
788{
789 PyObject *t, *r;
790
791 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000792 if (t == NULL || t == Py_NotImplemented)
793 return t;
794 assert(PyTuple_CheckExact(t));
795 r = PyTuple_GET_ITEM(t, 0);
796 Py_INCREF(r);
797 Py_DECREF(t);
798 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000799}
800
801static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000802float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803{
804 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000805
806 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000807 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000808 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000809 return NULL;
810 }
811
Neil Schemenauer32117e52001-01-04 01:44:34 +0000812 CONVERT_TO_DOUBLE(v, iv);
813 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000814
815 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000816 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000817 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000818 }
Tim Peters96685bf2001-08-23 22:31:37 +0000819 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000820 if (iw < 0.0) {
821 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000822 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000823 return NULL;
824 }
825 return PyFloat_FromDouble(0.0);
826 }
Christian Heimes53876d92008-04-19 00:31:39 +0000827 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
828 return PyFloat_FromDouble(1.0);
829 }
Tim Peterse87568d2003-05-24 20:18:24 +0000830 if (iv < 0.0) {
831 /* Whether this is an error is a mess, and bumps into libm
832 * bugs so we have to figure it out ourselves.
833 */
834 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000835 /* Negative numbers raised to fractional powers
836 * become complex.
837 */
838 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000839 }
840 /* iw is an exact integer, albeit perhaps a very large one.
841 * -1 raised to an exact integer should never be exceptional.
842 * Alas, some libms (chiefly glibc as of early 2003) return
843 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
844 * happen to be representable in a *C* integer. That's a
845 * bug; we let that slide in math.pow() (which currently
846 * reflects all platform accidents), but not for Python's **.
847 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000849 /* Return 1 if iw is even, -1 if iw is odd; there's
850 * no guarantee that any C integral type is big
851 * enough to hold iw, so we have to check this
852 * indirectly.
853 */
854 ix = floor(iw * 0.5) * 2.0;
855 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
856 }
857 /* Else iv != -1.0, and overflow or underflow are possible.
858 * Unless we're to write pow() ourselves, we have to trust
859 * the platform to do this correctly.
860 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000861 }
Tim Peters96685bf2001-08-23 22:31:37 +0000862 errno = 0;
863 PyFPE_START_PROTECT("pow", return NULL)
864 ix = pow(iv, iw);
865 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000866 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000867 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000868 /* We don't expect any errno value other than ERANGE, but
869 * the range of libm bugs appears unbounded.
870 */
871 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
872 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000873 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000874 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000875 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000876}
877
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000878static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000879float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000882}
883
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000884static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000885float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000886{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000887 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000888}
889
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000890static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000891float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000892{
893 return v->ob_fval != 0.0;
894}
895
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000896static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000897float_is_integer(PyObject *v)
898{
899 double x = PyFloat_AsDouble(v);
900 PyObject *o;
901
902 if (x == -1.0 && PyErr_Occurred())
903 return NULL;
904 if (!Py_IS_FINITE(x))
905 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000906 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000907 PyFPE_START_PROTECT("is_integer", return NULL)
908 o = (floor(x) == x) ? Py_True : Py_False;
909 PyFPE_END_PROTECT(x)
910 if (errno != 0) {
911 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
912 PyExc_ValueError);
913 return NULL;
914 }
915 Py_INCREF(o);
916 return o;
917}
918
919#if 0
920static PyObject *
921float_is_inf(PyObject *v)
922{
923 double x = PyFloat_AsDouble(v);
924 if (x == -1.0 && PyErr_Occurred())
925 return NULL;
926 return PyBool_FromLong((long)Py_IS_INFINITY(x));
927}
928
929static PyObject *
930float_is_nan(PyObject *v)
931{
932 double x = PyFloat_AsDouble(v);
933 if (x == -1.0 && PyErr_Occurred())
934 return NULL;
935 return PyBool_FromLong((long)Py_IS_NAN(x));
936}
937
938static PyObject *
939float_is_finite(PyObject *v)
940{
941 double x = PyFloat_AsDouble(v);
942 if (x == -1.0 && PyErr_Occurred())
943 return NULL;
944 return PyBool_FromLong((long)Py_IS_FINITE(x));
945}
946#endif
947
948static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000949float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000950{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000952 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000953
954 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000955 /* Try to get out cheap if this fits in a Python int. The attempt
956 * to cast to long must be protected, as C doesn't define what
957 * happens if the double is too big to fit in a long. Some rare
958 * systems raise an exception then (RISCOS was mentioned as one,
959 * and someone using a non-default option on Sun also bumped into
960 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
961 * still be vulnerable: if a long has more bits of precision than
962 * a double, casting MIN/MAX to double may yield an approximation,
963 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
964 * yield true from the C expression wholepart<=LONG_MAX, despite
965 * that wholepart is actually greater than LONG_MAX.
966 */
967 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
968 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000969 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000970 }
971 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000972}
973
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000974static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000975float_round(PyObject *v, PyObject *args)
976{
977#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
978 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000979 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000980 double flr, cil;
981 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000982 int ndigits = UNDEF_NDIGITS;
983
984 if (!PyArg_ParseTuple(args, "|i", &ndigits))
985 return NULL;
986
987 x = PyFloat_AsDouble(v);
988
989 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000990 f = pow(10.0, ndigits);
991 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000992 }
993
994 flr = floor(x);
995 cil = ceil(x);
996
997 if (x-flr > 0.5)
998 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000999 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000 rounded = fmod(flr, 2) == 0 ? flr : cil;
1001 else
1002 rounded = flr;
1003
1004 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001005 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001006 return PyFloat_FromDouble(rounded);
1007 }
1008
1009 return PyLong_FromDouble(rounded);
1010#undef UNDEF_NDIGITS
1011}
1012
1013static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001014float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001015{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001016 if (PyFloat_CheckExact(v))
1017 Py_INCREF(v);
1018 else
1019 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001020 return v;
1021}
1022
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001023/* turn ASCII hex characters into integer values and vice versa */
1024
1025static char
1026char_from_hex(int x)
1027{
1028 assert(0 <= x && x < 16);
1029 return "0123456789abcdef"[x];
1030}
1031
1032static int
1033hex_from_char(char c) {
1034 int x;
1035 assert(isxdigit(c));
1036 switch(c) {
1037 case '0':
1038 x = 0;
1039 break;
1040 case '1':
1041 x = 1;
1042 break;
1043 case '2':
1044 x = 2;
1045 break;
1046 case '3':
1047 x = 3;
1048 break;
1049 case '4':
1050 x = 4;
1051 break;
1052 case '5':
1053 x = 5;
1054 break;
1055 case '6':
1056 x = 6;
1057 break;
1058 case '7':
1059 x = 7;
1060 break;
1061 case '8':
1062 x = 8;
1063 break;
1064 case '9':
1065 x = 9;
1066 break;
1067 case 'a':
1068 case 'A':
1069 x = 10;
1070 break;
1071 case 'b':
1072 case 'B':
1073 x = 11;
1074 break;
1075 case 'c':
1076 case 'C':
1077 x = 12;
1078 break;
1079 case 'd':
1080 case 'D':
1081 x = 13;
1082 break;
1083 case 'e':
1084 case 'E':
1085 x = 14;
1086 break;
1087 case 'f':
1088 case 'F':
1089 x = 15;
1090 break;
1091 default:
1092 x = -1;
1093 break;
1094 }
1095 return x;
1096}
1097
1098/* convert a float to a hexadecimal string */
1099
1100/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1101 of the form 4k+1. */
1102#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1103
1104static PyObject *
1105float_hex(PyObject *v)
1106{
1107 double x, m;
1108 int e, shift, i, si, esign;
1109 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1110 trailing NUL byte. */
1111 char s[(TOHEX_NBITS-1)/4+3];
1112
1113 CONVERT_TO_DOUBLE(v, x);
1114
1115 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1116 return float_str((PyFloatObject *)v);
1117
1118 if (x == 0.0) {
1119 if(copysign(1.0, x) == -1.0)
1120 return PyUnicode_FromString("-0x0.0p+0");
1121 else
1122 return PyUnicode_FromString("0x0.0p+0");
1123 }
1124
1125 m = frexp(fabs(x), &e);
1126 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1127 m = ldexp(m, shift);
1128 e -= shift;
1129
1130 si = 0;
1131 s[si] = char_from_hex((int)m);
1132 si++;
1133 m -= (int)m;
1134 s[si] = '.';
1135 si++;
1136 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1137 m *= 16.0;
1138 s[si] = char_from_hex((int)m);
1139 si++;
1140 m -= (int)m;
1141 }
1142 s[si] = '\0';
1143
1144 if (e < 0) {
1145 esign = (int)'-';
1146 e = -e;
1147 }
1148 else
1149 esign = (int)'+';
1150
1151 if (x < 0.0)
1152 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1153 else
1154 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1155}
1156
1157PyDoc_STRVAR(float_hex_doc,
1158"float.hex() -> string\n\
1159\n\
1160Return a hexadecimal representation of a floating-point number.\n\
1161>>> (-0.1).hex()\n\
1162'-0x1.999999999999ap-4'\n\
1163>>> 3.14159.hex()\n\
1164'0x1.921f9f01b866ep+1'");
1165
1166/* Convert a hexadecimal string to a float. */
1167
1168static PyObject *
1169float_fromhex(PyObject *cls, PyObject *arg)
1170{
1171 PyObject *result_as_float, *result;
1172 double x;
1173 long exp, top_exp, lsb, key_digit;
1174 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1175 int half_eps, digit, round_up, sign=1;
1176 Py_ssize_t length, ndigits, fdigits, i;
1177
1178 /*
1179 * For the sake of simplicity and correctness, we impose an artificial
1180 * limit on ndigits, the total number of hex digits in the coefficient
1181 * The limit is chosen to ensure that, writing exp for the exponent,
1182 *
1183 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1184 * guaranteed to overflow (provided it's nonzero)
1185 *
1186 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1187 * guaranteed to underflow to 0.
1188 *
1189 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1190 * overflow in the calculation of exp and top_exp below.
1191 *
1192 * More specifically, ndigits is assumed to satisfy the following
1193 * inequalities:
1194 *
1195 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1196 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1197 *
1198 * If either of these inequalities is not satisfied, a ValueError is
1199 * raised. Otherwise, write x for the value of the hex string, and
1200 * assume x is nonzero. Then
1201 *
1202 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1203 *
1204 * Now if exp > LONG_MAX/2 then:
1205 *
1206 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1207 * = DBL_MAX_EXP
1208 *
1209 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1210 * double, so overflows. If exp < LONG_MIN/2, then
1211 *
1212 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1213 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1214 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1215 *
1216 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1217 * when converted to a C double.
1218 *
1219 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1220 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1221 */
1222
1223 s = PyUnicode_AsStringAndSize(arg, &length);
1224 if (s == NULL)
1225 return NULL;
1226 s_end = s + length;
1227
1228 /********************
1229 * Parse the string *
1230 ********************/
1231
1232 /* leading whitespace and optional sign */
1233 while (isspace(*s))
1234 s++;
1235 if (*s == '-') {
1236 s++;
1237 sign = -1;
1238 }
1239 else if (*s == '+')
1240 s++;
1241
1242 /* infinities and nans */
1243 if (PyOS_mystrnicmp(s, "nan", 4) == 0) {
1244 x = Py_NAN;
1245 goto finished;
1246 }
1247 if (PyOS_mystrnicmp(s, "inf", 4) == 0 ||
1248 PyOS_mystrnicmp(s, "infinity", 9) == 0) {
1249 x = sign*Py_HUGE_VAL;
1250 goto finished;
1251 }
1252
1253 /* [0x] */
1254 s_store = s;
1255 if (*s == '0') {
1256 s++;
1257 if (tolower(*s) == (int)'x')
1258 s++;
1259 else
1260 s = s_store;
1261 }
1262
1263 /* coefficient: <integer> [. <fraction>] */
1264 coeff_start = s;
1265 while (isxdigit(*s))
1266 s++;
1267 s_store = s;
1268 if (*s == '.') {
1269 s++;
1270 while (isxdigit(*s))
1271 s++;
1272 coeff_end = s-1;
1273 }
1274 else
1275 coeff_end = s;
1276
1277 /* ndigits = total # of hex digits; fdigits = # after point */
1278 ndigits = coeff_end - coeff_start;
1279 fdigits = coeff_end - s_store;
1280 if (ndigits == 0)
1281 goto parse_error;
1282 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1283 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1284 goto insane_length_error;
1285
1286 /* [p <exponent>] */
1287 if (tolower(*s) == (int)'p') {
1288 s++;
1289 exp_start = s;
1290 if (*s == '-' || *s == '+')
1291 s++;
1292 if (!isdigit(*s))
1293 goto parse_error;
1294 s++;
1295 while (isdigit(*s))
1296 s++;
1297 exp = strtol(exp_start, NULL, 10);
1298 }
1299 else
1300 exp = 0;
1301
1302 /* optional trailing whitespace leading to the end of the string */
1303 while (isspace(*s))
1304 s++;
1305 if (s != s_end)
1306 goto parse_error;
1307
1308/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1309#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1310 coeff_end-(j) : \
1311 coeff_end-1-(j)))
1312
1313 /*******************************************
1314 * Compute rounded value of the hex string *
1315 *******************************************/
1316
1317 /* Discard leading zeros, and catch extreme overflow and underflow */
1318 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1319 ndigits--;
1320 if (ndigits == 0 || exp < LONG_MIN/2) {
1321 x = sign * 0.0;
1322 goto finished;
1323 }
1324 if (exp > LONG_MAX/2)
1325 goto overflow_error;
1326
1327 /* Adjust exponent for fractional part. */
1328 exp = exp - 4*((long)fdigits);
1329
1330 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1331 top_exp = exp + 4*((long)ndigits - 1);
1332 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1333 top_exp++;
1334
1335 /* catch almost all nonextreme cases of overflow and underflow here */
1336 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1337 x = sign * 0.0;
1338 goto finished;
1339 }
1340 if (top_exp > DBL_MAX_EXP)
1341 goto overflow_error;
1342
1343 /* lsb = exponent of least significant bit of the *rounded* value.
1344 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1345 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1346
1347 x = 0.0;
1348 if (exp >= lsb) {
1349 /* no rounding required */
1350 for (i = ndigits-1; i >= 0; i--)
1351 x = 16.0*x + HEX_DIGIT(i);
1352 x = sign * ldexp(x, (int)(exp));
1353 goto finished;
1354 }
1355 /* rounding required. key_digit is the index of the hex digit
1356 containing the first bit to be rounded away. */
1357 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1358 key_digit = (lsb - exp - 1) / 4;
1359 for (i = ndigits-1; i > key_digit; i--)
1360 x = 16.0*x + HEX_DIGIT(i);
1361 digit = HEX_DIGIT(key_digit);
1362 x = 16.0*x + (double)(digit & (16-2*half_eps));
1363
1364 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1365 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1366 if ((digit & half_eps) != 0) {
1367 round_up = 0;
1368 if ((digit & (3*half_eps-1)) != 0 ||
1369 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1370 round_up = 1;
1371 else
1372 for (i = key_digit-1; i >= 0; i--)
1373 if (HEX_DIGIT(i) != 0) {
1374 round_up = 1;
1375 break;
1376 }
1377 if (round_up == 1) {
1378 x += 2*half_eps;
1379 if (top_exp == DBL_MAX_EXP &&
1380 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1381 /* overflow corner case: pre-rounded value <
1382 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1383 goto overflow_error;
1384 }
1385 }
1386 x = sign * ldexp(x, (int)(exp+4*key_digit));
1387
1388 finished:
1389 result_as_float = Py_BuildValue("(d)", x);
1390 if (result_as_float == NULL)
1391 return NULL;
1392 result = PyObject_CallObject(cls, result_as_float);
1393 Py_DECREF(result_as_float);
1394 return result;
1395
1396 overflow_error:
1397 PyErr_SetString(PyExc_OverflowError,
1398 "hexadecimal value too large to represent as a float");
1399 return NULL;
1400
1401 parse_error:
1402 PyErr_SetString(PyExc_ValueError,
1403 "invalid hexadecimal floating-point string");
1404 return NULL;
1405
1406 insane_length_error:
1407 PyErr_SetString(PyExc_ValueError,
1408 "hexadecimal string too long to convert");
1409 return NULL;
1410}
1411
1412PyDoc_STRVAR(float_fromhex_doc,
1413"float.fromhex(string) -> float\n\
1414\n\
1415Create a floating-point number from a hexadecimal string.\n\
1416>>> float.fromhex('0x1.ffffp10')\n\
14172047.984375\n\
1418>>> float.fromhex('-0x1p-1074')\n\
1419-4.9406564584124654e-324");
1420
1421
Christian Heimes26855632008-01-27 23:50:43 +00001422static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001423float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001424{
1425 double self;
1426 double float_part;
1427 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001428 int i;
1429
Christian Heimes26855632008-01-27 23:50:43 +00001430 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001431 PyObject *py_exponent = NULL;
1432 PyObject *numerator = NULL;
1433 PyObject *denominator = NULL;
1434 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001435 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001436
1437#define INPLACE_UPDATE(obj, call) \
1438 prev = obj; \
1439 obj = call; \
1440 Py_DECREF(prev); \
1441
1442 CONVERT_TO_DOUBLE(v, self);
1443
1444 if (Py_IS_INFINITY(self)) {
1445 PyErr_SetString(PyExc_OverflowError,
1446 "Cannot pass infinity to float.as_integer_ratio.");
1447 return NULL;
1448 }
1449#ifdef Py_NAN
1450 if (Py_IS_NAN(self)) {
1451 PyErr_SetString(PyExc_ValueError,
1452 "Cannot pass nan to float.as_integer_ratio.");
1453 return NULL;
1454 }
1455#endif
1456
Christian Heimes26855632008-01-27 23:50:43 +00001457 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001458 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001459 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001460
1461 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1462 float_part *= 2.0;
1463 exponent--;
1464 }
1465 /* self == float_part * 2**exponent exactly and float_part is integral.
1466 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1467 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001468
Christian Heimes292d3512008-02-03 16:51:08 +00001469 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001470 if (numerator == NULL) goto error;
1471
Christian Heimes292d3512008-02-03 16:51:08 +00001472 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001473 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001474 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001475 if (py_exponent == NULL) goto error;
1476 INPLACE_UPDATE(py_exponent,
1477 long_methods->nb_lshift(denominator, py_exponent));
1478 if (py_exponent == NULL) goto error;
1479 if (exponent > 0) {
1480 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001481 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001482 if (numerator == NULL) goto error;
1483 }
1484 else {
1485 Py_DECREF(denominator);
1486 denominator = py_exponent;
1487 py_exponent = NULL;
1488 }
1489
Christian Heimes292d3512008-02-03 16:51:08 +00001490 /* Returns ints instead of longs where possible */
1491 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1492 if (numerator == NULL) goto error;
1493 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1494 if (denominator == NULL) goto error;
1495
Christian Heimes26855632008-01-27 23:50:43 +00001496 result_pair = PyTuple_Pack(2, numerator, denominator);
1497
1498#undef INPLACE_UPDATE
1499error:
1500 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001501 Py_XDECREF(denominator);
1502 Py_XDECREF(numerator);
1503 return result_pair;
1504}
1505
1506PyDoc_STRVAR(float_as_integer_ratio_doc,
1507"float.as_integer_ratio() -> (int, int)\n"
1508"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001509"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1510"float and with a positive denominator.\n"
1511"Raises OverflowError on infinities and a ValueError on nans.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001512"\n"
1513">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001514"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001515">>> (0.0).as_integer_ratio()\n"
1516"(0, 1)\n"
1517">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001518"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001519
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001520
Jeremy Hylton938ace62002-07-17 16:30:39 +00001521static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001522float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1523
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524static PyObject *
1525float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1526{
1527 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001528 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529
Guido van Rossumbef14172001-08-29 15:47:46 +00001530 if (type != &PyFloat_Type)
1531 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1533 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001534 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001535 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536 return PyNumber_Float(x);
1537}
1538
Guido van Rossumbef14172001-08-29 15:47:46 +00001539/* Wimpy, slow approach to tp_new calls for subtypes of float:
1540 first create a regular float from whatever arguments we got,
1541 then allocate a subtype instance and initialize its ob_fval
1542 from the regular float. The regular float is then thrown away.
1543*/
1544static PyObject *
1545float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1546{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001547 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001548
1549 assert(PyType_IsSubtype(type, &PyFloat_Type));
1550 tmp = float_new(&PyFloat_Type, args, kwds);
1551 if (tmp == NULL)
1552 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001553 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001554 newobj = type->tp_alloc(type, 0);
1555 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001556 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001557 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001558 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001559 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001560 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001561 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001562}
1563
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001564static PyObject *
1565float_getnewargs(PyFloatObject *v)
1566{
1567 return Py_BuildValue("(d)", v->ob_fval);
1568}
1569
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001570/* this is for the benefit of the pack/unpack routines below */
1571
1572typedef enum {
1573 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1574} float_format_type;
1575
1576static float_format_type double_format, float_format;
1577static float_format_type detected_double_format, detected_float_format;
1578
1579static PyObject *
1580float_getformat(PyTypeObject *v, PyObject* arg)
1581{
1582 char* s;
1583 float_format_type r;
1584
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001585 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001586 PyErr_Format(PyExc_TypeError,
1587 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001588 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001589 return NULL;
1590 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001591 s = PyUnicode_AsString(arg);
1592 if (s == NULL)
1593 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001594 if (strcmp(s, "double") == 0) {
1595 r = double_format;
1596 }
1597 else if (strcmp(s, "float") == 0) {
1598 r = float_format;
1599 }
1600 else {
1601 PyErr_SetString(PyExc_ValueError,
1602 "__getformat__() argument 1 must be "
1603 "'double' or 'float'");
1604 return NULL;
1605 }
1606
1607 switch (r) {
1608 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001609 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001610 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001611 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001612 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001613 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614 default:
1615 Py_FatalError("insane float_format or double_format");
1616 return NULL;
1617 }
1618}
1619
1620PyDoc_STRVAR(float_getformat_doc,
1621"float.__getformat__(typestr) -> string\n"
1622"\n"
1623"You probably don't want to use this function. It exists mainly to be\n"
1624"used in Python's test suite.\n"
1625"\n"
1626"typestr must be 'double' or 'float'. This function returns whichever of\n"
1627"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1628"format of floating point numbers used by the C type named by typestr.");
1629
1630static PyObject *
1631float_setformat(PyTypeObject *v, PyObject* args)
1632{
1633 char* typestr;
1634 char* format;
1635 float_format_type f;
1636 float_format_type detected;
1637 float_format_type *p;
1638
1639 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1640 return NULL;
1641
1642 if (strcmp(typestr, "double") == 0) {
1643 p = &double_format;
1644 detected = detected_double_format;
1645 }
1646 else if (strcmp(typestr, "float") == 0) {
1647 p = &float_format;
1648 detected = detected_float_format;
1649 }
1650 else {
1651 PyErr_SetString(PyExc_ValueError,
1652 "__setformat__() argument 1 must "
1653 "be 'double' or 'float'");
1654 return NULL;
1655 }
1656
1657 if (strcmp(format, "unknown") == 0) {
1658 f = unknown_format;
1659 }
1660 else if (strcmp(format, "IEEE, little-endian") == 0) {
1661 f = ieee_little_endian_format;
1662 }
1663 else if (strcmp(format, "IEEE, big-endian") == 0) {
1664 f = ieee_big_endian_format;
1665 }
1666 else {
1667 PyErr_SetString(PyExc_ValueError,
1668 "__setformat__() argument 2 must be "
1669 "'unknown', 'IEEE, little-endian' or "
1670 "'IEEE, big-endian'");
1671 return NULL;
1672
1673 }
1674
1675 if (f != unknown_format && f != detected) {
1676 PyErr_Format(PyExc_ValueError,
1677 "can only set %s format to 'unknown' or the "
1678 "detected platform value", typestr);
1679 return NULL;
1680 }
1681
1682 *p = f;
1683 Py_RETURN_NONE;
1684}
1685
1686PyDoc_STRVAR(float_setformat_doc,
1687"float.__setformat__(typestr, fmt) -> None\n"
1688"\n"
1689"You probably don't want to use this function. It exists mainly to be\n"
1690"used in Python's test suite.\n"
1691"\n"
1692"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1693"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1694"one of the latter two if it appears to match the underlying C reality.\n"
1695"\n"
1696"Overrides the automatic determination of C-level floating point type.\n"
1697"This affects how floats are converted to and from binary strings.");
1698
Guido van Rossumb43daf72007-08-01 18:08:08 +00001699static PyObject *
1700float_getzero(PyObject *v, void *closure)
1701{
1702 return PyFloat_FromDouble(0.0);
1703}
1704
Eric Smith8c663262007-08-25 02:26:07 +00001705static PyObject *
1706float__format__(PyObject *self, PyObject *args)
1707{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001708 PyObject *format_spec;
1709
1710 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1711 return NULL;
1712 return _PyFloat_FormatAdvanced(self,
1713 PyUnicode_AS_UNICODE(format_spec),
1714 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001715}
1716
1717PyDoc_STRVAR(float__format__doc,
1718"float.__format__(format_spec) -> string\n"
1719"\n"
1720"Formats the float according to format_spec.");
1721
1722
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001723static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001724 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001725 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001726 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1727 "Returns the Integral closest to x between 0 and x."},
1728 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1729 "Returns the Integral closest to x, rounding half toward even.\n"
1730 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001731 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1732 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001733 {"fromhex", (PyCFunction)float_fromhex,
1734 METH_O|METH_CLASS, float_fromhex_doc},
1735 {"hex", (PyCFunction)float_hex,
1736 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001737 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1738 "Returns True if the float is an integer."},
1739#if 0
1740 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1741 "Returns True if the float is positive or negative infinite."},
1742 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1743 "Returns True if the float is finite, neither infinite nor NaN."},
1744 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1745 "Returns True if the float is not a number (NaN)."},
1746#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001747 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001748 {"__getformat__", (PyCFunction)float_getformat,
1749 METH_O|METH_CLASS, float_getformat_doc},
1750 {"__setformat__", (PyCFunction)float_setformat,
1751 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001752 {"__format__", (PyCFunction)float__format__,
1753 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001754 {NULL, NULL} /* sentinel */
1755};
1756
Guido van Rossumb43daf72007-08-01 18:08:08 +00001757static PyGetSetDef float_getset[] = {
1758 {"real",
1759 (getter)float_float, (setter)NULL,
1760 "the real part of a complex number",
1761 NULL},
1762 {"imag",
1763 (getter)float_getzero, (setter)NULL,
1764 "the imaginary part of a complex number",
1765 NULL},
1766 {NULL} /* Sentinel */
1767};
1768
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001769PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770"float(x) -> floating point number\n\
1771\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001772Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773
1774
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001775static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001776 float_add, /*nb_add*/
1777 float_sub, /*nb_subtract*/
1778 float_mul, /*nb_multiply*/
1779 float_rem, /*nb_remainder*/
1780 float_divmod, /*nb_divmod*/
1781 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001782 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001783 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001784 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001785 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001786 0, /*nb_invert*/
1787 0, /*nb_lshift*/
1788 0, /*nb_rshift*/
1789 0, /*nb_and*/
1790 0, /*nb_xor*/
1791 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001792 float_trunc, /*nb_int*/
1793 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001794 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001795 0, /* nb_inplace_add */
1796 0, /* nb_inplace_subtract */
1797 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001798 0, /* nb_inplace_remainder */
1799 0, /* nb_inplace_power */
1800 0, /* nb_inplace_lshift */
1801 0, /* nb_inplace_rshift */
1802 0, /* nb_inplace_and */
1803 0, /* nb_inplace_xor */
1804 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001805 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001806 float_div, /* nb_true_divide */
1807 0, /* nb_inplace_floor_divide */
1808 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809};
1810
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001811PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001812 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001813 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001814 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001815 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001817 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001818 0, /* tp_getattr */
1819 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001820 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 (reprfunc)float_repr, /* tp_repr */
1822 &float_as_number, /* tp_as_number */
1823 0, /* tp_as_sequence */
1824 0, /* tp_as_mapping */
1825 (hashfunc)float_hash, /* tp_hash */
1826 0, /* tp_call */
1827 (reprfunc)float_str, /* tp_str */
1828 PyObject_GenericGetAttr, /* tp_getattro */
1829 0, /* tp_setattro */
1830 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001831 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832 float_doc, /* tp_doc */
1833 0, /* tp_traverse */
1834 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001835 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 0, /* tp_weaklistoffset */
1837 0, /* tp_iter */
1838 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001839 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001841 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 0, /* tp_base */
1843 0, /* tp_dict */
1844 0, /* tp_descr_get */
1845 0, /* tp_descr_set */
1846 0, /* tp_dictoffset */
1847 0, /* tp_init */
1848 0, /* tp_alloc */
1849 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001850};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001851
1852void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001853_PyFloat_Init(void)
1854{
1855 /* We attempt to determine if this machine is using IEEE
1856 floating point formats by peering at the bits of some
1857 carefully chosen values. If it looks like we are on an
1858 IEEE platform, the float packing/unpacking routines can
1859 just copy bits, if not they resort to arithmetic & shifts
1860 and masks. The shifts & masks approach works on all finite
1861 values, but what happens to infinities, NaNs and signed
1862 zeroes on packing is an accident, and attempting to unpack
1863 a NaN or an infinity will raise an exception.
1864
1865 Note that if we're on some whacked-out platform which uses
1866 IEEE formats but isn't strictly little-endian or big-
1867 endian, we will fall back to the portable shifts & masks
1868 method. */
1869
1870#if SIZEOF_DOUBLE == 8
1871 {
1872 double x = 9006104071832581.0;
1873 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1874 detected_double_format = ieee_big_endian_format;
1875 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1876 detected_double_format = ieee_little_endian_format;
1877 else
1878 detected_double_format = unknown_format;
1879 }
1880#else
1881 detected_double_format = unknown_format;
1882#endif
1883
1884#if SIZEOF_FLOAT == 4
1885 {
1886 float y = 16711938.0;
1887 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1888 detected_float_format = ieee_big_endian_format;
1889 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1890 detected_float_format = ieee_little_endian_format;
1891 else
1892 detected_float_format = unknown_format;
1893 }
1894#else
1895 detected_float_format = unknown_format;
1896#endif
1897
1898 double_format = detected_double_format;
1899 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001900
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001901 /* Init float info */
1902 if (FloatInfoType.tp_name == 0)
1903 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001904}
1905
1906void
Christian Heimes15ebc882008-02-04 18:48:49 +00001907PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001908{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001909 PyFloatObject *p;
1910 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001911 unsigned i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001912 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1913 size_t fsum = 0; /* total unfreed ints */
1914 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001915
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001916 list = block_list;
1917 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001918 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001919 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001920 bc++;
1921 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001922 for (i = 0, p = &list->objects[0];
1923 i < N_FLOATOBJECTS;
1924 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001925 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001926 frem++;
1927 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001928 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001929 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001930 list->next = block_list;
1931 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001932 for (i = 0, p = &list->objects[0];
1933 i < N_FLOATOBJECTS;
1934 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001935 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001936 Py_REFCNT(p) == 0) {
1937 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001938 free_list;
1939 free_list = p;
1940 }
1941 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001942 }
1943 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001944 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001945 bf++;
1946 }
1947 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001948 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001949 }
Christian Heimes15ebc882008-02-04 18:48:49 +00001950 *pbc = bc;
1951 *pbf = bf;
1952 *bsum = fsum;
1953}
1954
1955void
1956PyFloat_Fini(void)
1957{
1958 PyFloatObject *p;
1959 PyFloatBlock *list;
1960 unsigned i;
1961 size_t bc, bf; /* block count, number of freed blocks */
1962 size_t fsum; /* total unfreed floats per block */
1963
1964 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1965
Guido van Rossum3fce8831999-03-12 19:43:17 +00001966 if (!Py_VerboseFlag)
1967 return;
1968 fprintf(stderr, "# cleanup floats");
1969 if (!fsum) {
1970 fprintf(stderr, "\n");
1971 }
1972 else {
1973 fprintf(stderr,
Christian Heimesba4af492008-03-28 00:55:15 +00001974 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes15ebc882008-02-04 18:48:49 +00001975 PY_FORMAT_SIZE_T "d out of %"
1976 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001977 fsum, fsum == 1 ? "" : "s",
1978 bc - bf, bc, bc == 1 ? "" : "s");
1979 }
1980 if (Py_VerboseFlag > 1) {
1981 list = block_list;
1982 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001983 for (i = 0, p = &list->objects[0];
1984 i < N_FLOATOBJECTS;
1985 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001986 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001987 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001988 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001989 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001990 /* XXX(twouters) cast refcount to
1991 long until %zd is universally
1992 available
1993 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001994 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);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001997 }
1998 }
1999 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002000 }
2001 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002002}
Tim Peters9905b942003-03-20 20:53:32 +00002003
2004/*----------------------------------------------------------------------------
2005 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002006 */
2007int
2008_PyFloat_Pack4(double x, unsigned char *p, int le)
2009{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002010 if (float_format == unknown_format) {
2011 unsigned char sign;
2012 int e;
2013 double f;
2014 unsigned int fbits;
2015 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002016
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002017 if (le) {
2018 p += 3;
2019 incr = -1;
2020 }
Tim Peters9905b942003-03-20 20:53:32 +00002021
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002022 if (x < 0) {
2023 sign = 1;
2024 x = -x;
2025 }
2026 else
2027 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002028
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002029 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002030
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002031 /* Normalize f to be in the range [1.0, 2.0) */
2032 if (0.5 <= f && f < 1.0) {
2033 f *= 2.0;
2034 e--;
2035 }
2036 else if (f == 0.0)
2037 e = 0;
2038 else {
2039 PyErr_SetString(PyExc_SystemError,
2040 "frexp() result out of range");
2041 return -1;
2042 }
2043
2044 if (e >= 128)
2045 goto Overflow;
2046 else if (e < -126) {
2047 /* Gradual underflow */
2048 f = ldexp(f, 126 + e);
2049 e = 0;
2050 }
2051 else if (!(e == 0 && f == 0.0)) {
2052 e += 127;
2053 f -= 1.0; /* Get rid of leading 1 */
2054 }
2055
2056 f *= 8388608.0; /* 2**23 */
2057 fbits = (unsigned int)(f + 0.5); /* Round */
2058 assert(fbits <= 8388608);
2059 if (fbits >> 23) {
2060 /* The carry propagated out of a string of 23 1 bits. */
2061 fbits = 0;
2062 ++e;
2063 if (e >= 255)
2064 goto Overflow;
2065 }
2066
2067 /* First byte */
2068 *p = (sign << 7) | (e >> 1);
2069 p += incr;
2070
2071 /* Second byte */
2072 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2073 p += incr;
2074
2075 /* Third byte */
2076 *p = (fbits >> 8) & 0xFF;
2077 p += incr;
2078
2079 /* Fourth byte */
2080 *p = fbits & 0xFF;
2081
2082 /* Done */
2083 return 0;
2084
Tim Peters9905b942003-03-20 20:53:32 +00002085 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002086 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002087 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088 const char *s = (char*)&y;
2089 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002090
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002091 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2092 goto Overflow;
2093
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002094 if ((float_format == ieee_little_endian_format && !le)
2095 || (float_format == ieee_big_endian_format && le)) {
2096 p += 3;
2097 incr = -1;
2098 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002099
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002100 for (i = 0; i < 4; i++) {
2101 *p = *s++;
2102 p += incr;
2103 }
2104 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002105 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002106 Overflow:
2107 PyErr_SetString(PyExc_OverflowError,
2108 "float too large to pack with f format");
2109 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002110}
2111
2112int
2113_PyFloat_Pack8(double x, unsigned char *p, int le)
2114{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002115 if (double_format == unknown_format) {
2116 unsigned char sign;
2117 int e;
2118 double f;
2119 unsigned int fhi, flo;
2120 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002121
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122 if (le) {
2123 p += 7;
2124 incr = -1;
2125 }
Tim Peters9905b942003-03-20 20:53:32 +00002126
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002127 if (x < 0) {
2128 sign = 1;
2129 x = -x;
2130 }
2131 else
2132 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002133
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002134 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002135
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002136 /* Normalize f to be in the range [1.0, 2.0) */
2137 if (0.5 <= f && f < 1.0) {
2138 f *= 2.0;
2139 e--;
2140 }
2141 else if (f == 0.0)
2142 e = 0;
2143 else {
2144 PyErr_SetString(PyExc_SystemError,
2145 "frexp() result out of range");
2146 return -1;
2147 }
2148
2149 if (e >= 1024)
2150 goto Overflow;
2151 else if (e < -1022) {
2152 /* Gradual underflow */
2153 f = ldexp(f, 1022 + e);
2154 e = 0;
2155 }
2156 else if (!(e == 0 && f == 0.0)) {
2157 e += 1023;
2158 f -= 1.0; /* Get rid of leading 1 */
2159 }
2160
2161 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2162 f *= 268435456.0; /* 2**28 */
2163 fhi = (unsigned int)f; /* Truncate */
2164 assert(fhi < 268435456);
2165
2166 f -= (double)fhi;
2167 f *= 16777216.0; /* 2**24 */
2168 flo = (unsigned int)(f + 0.5); /* Round */
2169 assert(flo <= 16777216);
2170 if (flo >> 24) {
2171 /* The carry propagated out of a string of 24 1 bits. */
2172 flo = 0;
2173 ++fhi;
2174 if (fhi >> 28) {
2175 /* And it also progagated out of the next 28 bits. */
2176 fhi = 0;
2177 ++e;
2178 if (e >= 2047)
2179 goto Overflow;
2180 }
2181 }
2182
2183 /* First byte */
2184 *p = (sign << 7) | (e >> 4);
2185 p += incr;
2186
2187 /* Second byte */
2188 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2189 p += incr;
2190
2191 /* Third byte */
2192 *p = (fhi >> 16) & 0xFF;
2193 p += incr;
2194
2195 /* Fourth byte */
2196 *p = (fhi >> 8) & 0xFF;
2197 p += incr;
2198
2199 /* Fifth byte */
2200 *p = fhi & 0xFF;
2201 p += incr;
2202
2203 /* Sixth byte */
2204 *p = (flo >> 16) & 0xFF;
2205 p += incr;
2206
2207 /* Seventh byte */
2208 *p = (flo >> 8) & 0xFF;
2209 p += incr;
2210
2211 /* Eighth byte */
2212 *p = flo & 0xFF;
2213 p += incr;
2214
2215 /* Done */
2216 return 0;
2217
2218 Overflow:
2219 PyErr_SetString(PyExc_OverflowError,
2220 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002221 return -1;
2222 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002223 else {
2224 const char *s = (char*)&x;
2225 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002226
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002227 if ((double_format == ieee_little_endian_format && !le)
2228 || (double_format == ieee_big_endian_format && le)) {
2229 p += 7;
2230 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002231 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232
2233 for (i = 0; i < 8; i++) {
2234 *p = *s++;
2235 p += incr;
2236 }
2237 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002238 }
Tim Peters9905b942003-03-20 20:53:32 +00002239}
2240
Neal Norwitz545686b2006-12-28 04:45:06 +00002241/* Should only be used by marshal. */
2242int
2243_PyFloat_Repr(double x, char *p, size_t len)
2244{
2245 format_double(p, len, x, PREC_REPR);
2246 return (int)strlen(p);
2247}
2248
Tim Peters9905b942003-03-20 20:53:32 +00002249double
2250_PyFloat_Unpack4(const unsigned char *p, int le)
2251{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252 if (float_format == unknown_format) {
2253 unsigned char sign;
2254 int e;
2255 unsigned int f;
2256 double x;
2257 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002258
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002259 if (le) {
2260 p += 3;
2261 incr = -1;
2262 }
2263
2264 /* First byte */
2265 sign = (*p >> 7) & 1;
2266 e = (*p & 0x7F) << 1;
2267 p += incr;
2268
2269 /* Second byte */
2270 e |= (*p >> 7) & 1;
2271 f = (*p & 0x7F) << 16;
2272 p += incr;
2273
2274 if (e == 255) {
2275 PyErr_SetString(
2276 PyExc_ValueError,
2277 "can't unpack IEEE 754 special value "
2278 "on non-IEEE platform");
2279 return -1;
2280 }
2281
2282 /* Third byte */
2283 f |= *p << 8;
2284 p += incr;
2285
2286 /* Fourth byte */
2287 f |= *p;
2288
2289 x = (double)f / 8388608.0;
2290
2291 /* XXX This sadly ignores Inf/NaN issues */
2292 if (e == 0)
2293 e = -126;
2294 else {
2295 x += 1.0;
2296 e -= 127;
2297 }
2298 x = ldexp(x, e);
2299
2300 if (sign)
2301 x = -x;
2302
2303 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002304 }
Tim Peters9905b942003-03-20 20:53:32 +00002305 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002306 float x;
2307
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308 if ((float_format == ieee_little_endian_format && !le)
2309 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002310 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002311 char *d = &buf[3];
2312 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002313
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002314 for (i = 0; i < 4; i++) {
2315 *d-- = *p++;
2316 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002317 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318 }
2319 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002320 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002321 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002322
2323 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324 }
Tim Peters9905b942003-03-20 20:53:32 +00002325}
2326
2327double
2328_PyFloat_Unpack8(const unsigned char *p, int le)
2329{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002330 if (double_format == unknown_format) {
2331 unsigned char sign;
2332 int e;
2333 unsigned int fhi, flo;
2334 double x;
2335 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002336
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002337 if (le) {
2338 p += 7;
2339 incr = -1;
2340 }
2341
2342 /* First byte */
2343 sign = (*p >> 7) & 1;
2344 e = (*p & 0x7F) << 4;
2345
2346 p += incr;
2347
2348 /* Second byte */
2349 e |= (*p >> 4) & 0xF;
2350 fhi = (*p & 0xF) << 24;
2351 p += incr;
2352
2353 if (e == 2047) {
2354 PyErr_SetString(
2355 PyExc_ValueError,
2356 "can't unpack IEEE 754 special value "
2357 "on non-IEEE platform");
2358 return -1.0;
2359 }
2360
2361 /* Third byte */
2362 fhi |= *p << 16;
2363 p += incr;
2364
2365 /* Fourth byte */
2366 fhi |= *p << 8;
2367 p += incr;
2368
2369 /* Fifth byte */
2370 fhi |= *p;
2371 p += incr;
2372
2373 /* Sixth byte */
2374 flo = *p << 16;
2375 p += incr;
2376
2377 /* Seventh byte */
2378 flo |= *p << 8;
2379 p += incr;
2380
2381 /* Eighth byte */
2382 flo |= *p;
2383
2384 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2385 x /= 268435456.0; /* 2**28 */
2386
2387 if (e == 0)
2388 e = -1022;
2389 else {
2390 x += 1.0;
2391 e -= 1023;
2392 }
2393 x = ldexp(x, e);
2394
2395 if (sign)
2396 x = -x;
2397
2398 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002399 }
Tim Peters9905b942003-03-20 20:53:32 +00002400 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002401 double x;
2402
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002403 if ((double_format == ieee_little_endian_format && !le)
2404 || (double_format == ieee_big_endian_format && le)) {
2405 char buf[8];
2406 char *d = &buf[7];
2407 int i;
2408
2409 for (i = 0; i < 8; i++) {
2410 *d-- = *p++;
2411 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002412 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002413 }
2414 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002415 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002416 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002417
2418 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002419 }
Tim Peters9905b942003-03-20 20:53:32 +00002420}