blob: daf7ee807ee91f564495b11d7b5a66f5ddeffe84 [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 }
Georg Brandl2ee470f2008-07-16 12:55:28 +0000228 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
229 Py_RETURN_INF(sign);
230 }
Christian Heimes99170a52007-12-19 02:07:34 +0000231#ifdef Py_NAN
232 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000233 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000234 }
235#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000236 PyOS_snprintf(buffer, sizeof(buffer),
237 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000238 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000239 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000240 }
241 /* Since end != s, the platform made *some* kind of sense out
242 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000243 while (*end && isspace(Py_CHARMASK(*end)))
244 end++;
245 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000246 PyOS_snprintf(buffer, sizeof(buffer),
247 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000248 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000249 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000250 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000251 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000252 PyErr_SetString(PyExc_ValueError,
253 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000254 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000255 }
Tim Petersef14d732000-09-23 03:39:17 +0000256 if (x == 0.0) {
257 /* See above -- may have been strtod being anal
258 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000259 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000260 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000261 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000262 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000263 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000264 result = PyFloat_FromDouble(x);
265 error:
266 if (s_buffer)
267 PyMem_FREE(s_buffer);
268 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000269}
270
Guido van Rossum234f9421993-06-17 12:35:49 +0000271static void
Fred Drakefd99de62000-07-09 05:02:18 +0000272float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000273{
Guido van Rossum9475a232001-10-05 20:51:39 +0000274 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000275 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000276 free_list = op;
277 }
278 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000279 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000280}
281
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282double
Fred Drakefd99de62000-07-09 05:02:18 +0000283PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285 PyNumberMethods *nb;
286 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000289 if (op && PyFloat_Check(op))
290 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000291
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000292 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000294 return -1;
295 }
Tim Petersd2364e82001-11-01 20:09:42 +0000296
Christian Heimes90aa7642007-12-19 02:45:37 +0000297 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000298 PyErr_SetString(PyExc_TypeError, "a float is required");
299 return -1;
300 }
301
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303 if (fo == NULL)
304 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 if (!PyFloat_Check(fo)) {
306 PyErr_SetString(PyExc_TypeError,
307 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308 return -1;
309 }
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311 val = PyFloat_AS_DOUBLE(fo);
312 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000313
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315}
316
317/* Methods */
318
Tim Peters97019e42001-11-28 22:43:45 +0000319static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000320format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321{
322 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000323 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000324 int i;
325
326 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000327 We want float numbers to be recognizable as such,
328 i.e., they should contain a decimal point or an exponent.
329 However, %g may print the number as an integer;
330 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000331
Martin v. Löwis737ea822004-06-08 18:52:54 +0000332 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000333 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000334 cp = buf;
335 if (*cp == '-')
336 cp++;
337 for (; *cp != '\0'; cp++) {
338 /* Any non-digit means it's not an integer;
339 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000340 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341 break;
342 }
343 if (*cp == '\0') {
344 *cp++ = '.';
345 *cp++ = '0';
346 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000347 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348 }
Christian Heimes99170a52007-12-19 02:07:34 +0000349 /* Checking the next three chars should be more than enough to
350 * detect inf or nan, even on Windows. We check for inf or nan
351 * at last because they are rare cases.
352 */
353 for (i=0; *cp != '\0' && i<3; cp++, i++) {
354 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
355 continue;
356 /* found something that is neither a digit nor point
357 * it might be a NaN or INF
358 */
359#ifdef Py_NAN
360 if (Py_IS_NAN(ob_fval)) {
361 strcpy(buf, "nan");
362 }
363 else
364#endif
365 if (Py_IS_INFINITY(ob_fval)) {
366 cp = buf;
367 if (*cp == '-')
368 cp++;
369 strcpy(cp, "inf");
370 }
371 break;
372 }
373
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374}
375
Neal Norwitz545686b2006-12-28 04:45:06 +0000376static void
377format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000378{
Neal Norwitz545686b2006-12-28 04:45:06 +0000379 assert(PyFloat_Check(v));
380 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000381}
382
Neil Schemenauer32117e52001-01-04 01:44:34 +0000383/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000384 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000385 set to NULL, and the function invoking this macro returns NULL. If
386 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
387 stored in obj, and returned from the function invoking this macro.
388*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000389#define CONVERT_TO_DOUBLE(obj, dbl) \
390 if (PyFloat_Check(obj)) \
391 dbl = PyFloat_AS_DOUBLE(obj); \
392 else if (convert_to_double(&(obj), &(dbl)) < 0) \
393 return obj;
394
395static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000396convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000397{
398 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000399
Guido van Rossumddefaf32007-01-14 03:31:43 +0000400 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000401 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000402 if (*dbl == -1.0 && PyErr_Occurred()) {
403 *v = NULL;
404 return -1;
405 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000406 }
407 else {
408 Py_INCREF(Py_NotImplemented);
409 *v = Py_NotImplemented;
410 return -1;
411 }
412 return 0;
413}
414
Guido van Rossum57072eb1999-12-23 19:00:28 +0000415/* Precisions used by repr() and str(), respectively.
416
417 The repr() precision (17 significant decimal digits) is the minimal number
418 that is guaranteed to have enough precision so that if the number is read
419 back in the exact same binary value is recreated. This is true for IEEE
420 floating point by design, and also happens to work for all other modern
421 hardware.
422
423 The str() precision is chosen so that in most cases, the rounding noise
424 created by various operations is suppressed, while giving plenty of
425 precision for practical use.
426
427*/
428
429#define PREC_REPR 17
430#define PREC_STR 12
431
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000433float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434{
Christian Heimesb76922a2007-12-11 01:06:40 +0000435 char buf[100];
436 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesb76922a2007-12-11 01:06:40 +0000437
Walter Dörwald1ab83302007-05-18 17:15:44 +0000438 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000439}
440
441static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000442float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000443{
444 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000445 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000446 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447}
448
Tim Peters307fa782004-09-23 08:06:40 +0000449/* Comparison is pretty much a nightmare. When comparing float to float,
450 * we do it as straightforwardly (and long-windedly) as conceivable, so
451 * that, e.g., Python x == y delivers the same result as the platform
452 * C x == y when x and/or y is a NaN.
453 * When mixing float with an integer type, there's no good *uniform* approach.
454 * Converting the double to an integer obviously doesn't work, since we
455 * may lose info from fractional bits. Converting the integer to a double
456 * also has two failure modes: (1) a long int may trigger overflow (too
457 * large to fit in the dynamic range of a C double); (2) even a C long may have
458 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
459 * 63 bits of precision, but a C double probably has only 53), and then
460 * we can falsely claim equality when low-order integer bits are lost by
461 * coercion to double. So this part is painful too.
462 */
463
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000464static PyObject*
465float_richcompare(PyObject *v, PyObject *w, int op)
466{
467 double i, j;
468 int r = 0;
469
Tim Peters307fa782004-09-23 08:06:40 +0000470 assert(PyFloat_Check(v));
471 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000472
Tim Peters307fa782004-09-23 08:06:40 +0000473 /* Switch on the type of w. Set i and j to doubles to be compared,
474 * and op to the richcomp to use.
475 */
476 if (PyFloat_Check(w))
477 j = PyFloat_AS_DOUBLE(w);
478
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000480 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000481 /* If i is an infinity, its magnitude exceeds any
482 * finite integer, so it doesn't matter which int we
483 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000484 */
485 j = 0.0;
486 else
487 goto Unimplemented;
488 }
489
Tim Peters307fa782004-09-23 08:06:40 +0000490 else if (PyLong_Check(w)) {
491 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
492 int wsign = _PyLong_Sign(w);
493 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000494 int exponent;
495
496 if (vsign != wsign) {
497 /* Magnitudes are irrelevant -- the signs alone
498 * determine the outcome.
499 */
500 i = (double)vsign;
501 j = (double)wsign;
502 goto Compare;
503 }
504 /* The signs are the same. */
505 /* Convert w to a double if it fits. In particular, 0 fits. */
506 nbits = _PyLong_NumBits(w);
507 if (nbits == (size_t)-1 && PyErr_Occurred()) {
508 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000509 * to hold the # of bits. Replace with little doubles
510 * that give the same outcome -- w is so large that
511 * its magnitude must exceed the magnitude of any
512 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000513 */
514 PyErr_Clear();
515 i = (double)vsign;
516 assert(wsign != 0);
517 j = wsign * 2.0;
518 goto Compare;
519 }
520 if (nbits <= 48) {
521 j = PyLong_AsDouble(w);
522 /* It's impossible that <= 48 bits overflowed. */
523 assert(j != -1.0 || ! PyErr_Occurred());
524 goto Compare;
525 }
526 assert(wsign != 0); /* else nbits was 0 */
527 assert(vsign != 0); /* if vsign were 0, then since wsign is
528 * not 0, we would have taken the
529 * vsign != wsign branch at the start */
530 /* We want to work with non-negative numbers. */
531 if (vsign < 0) {
532 /* "Multiply both sides" by -1; this also swaps the
533 * comparator.
534 */
535 i = -i;
536 op = _Py_SwappedOp[op];
537 }
538 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000539 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000540 /* exponent is the # of bits in v before the radix point;
541 * we know that nbits (the # of bits in w) > 48 at this point
542 */
543 if (exponent < 0 || (size_t)exponent < nbits) {
544 i = 1.0;
545 j = 2.0;
546 goto Compare;
547 }
548 if ((size_t)exponent > nbits) {
549 i = 2.0;
550 j = 1.0;
551 goto Compare;
552 }
553 /* v and w have the same number of bits before the radix
554 * point. Construct two longs that have the same comparison
555 * outcome.
556 */
557 {
558 double fracpart;
559 double intpart;
560 PyObject *result = NULL;
561 PyObject *one = NULL;
562 PyObject *vv = NULL;
563 PyObject *ww = w;
564
565 if (wsign < 0) {
566 ww = PyNumber_Negative(w);
567 if (ww == NULL)
568 goto Error;
569 }
570 else
571 Py_INCREF(ww);
572
573 fracpart = modf(i, &intpart);
574 vv = PyLong_FromDouble(intpart);
575 if (vv == NULL)
576 goto Error;
577
578 if (fracpart != 0.0) {
579 /* Shift left, and or a 1 bit into vv
580 * to represent the lost fraction.
581 */
582 PyObject *temp;
583
Christian Heimes217cfd12007-12-02 14:31:20 +0000584 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000585 if (one == NULL)
586 goto Error;
587
588 temp = PyNumber_Lshift(ww, one);
589 if (temp == NULL)
590 goto Error;
591 Py_DECREF(ww);
592 ww = temp;
593
594 temp = PyNumber_Lshift(vv, one);
595 if (temp == NULL)
596 goto Error;
597 Py_DECREF(vv);
598 vv = temp;
599
600 temp = PyNumber_Or(vv, one);
601 if (temp == NULL)
602 goto Error;
603 Py_DECREF(vv);
604 vv = temp;
605 }
606
607 r = PyObject_RichCompareBool(vv, ww, op);
608 if (r < 0)
609 goto Error;
610 result = PyBool_FromLong(r);
611 Error:
612 Py_XDECREF(vv);
613 Py_XDECREF(ww);
614 Py_XDECREF(one);
615 return result;
616 }
617 } /* else if (PyLong_Check(w)) */
618
619 else /* w isn't float, int, or long */
620 goto Unimplemented;
621
622 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000623 PyFPE_START_PROTECT("richcompare", return NULL)
624 switch (op) {
625 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000626 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000627 break;
628 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000629 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000630 break;
631 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000632 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633 break;
634 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000635 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000636 break;
637 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000638 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000639 break;
640 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000641 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000642 break;
643 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000644 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000645 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000646
647 Unimplemented:
648 Py_INCREF(Py_NotImplemented);
649 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000650}
651
Guido van Rossum9bfef441993-03-29 10:43:31 +0000652static long
Fred Drakefd99de62000-07-09 05:02:18 +0000653float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000654{
Tim Peters39dce292000-08-15 03:34:48 +0000655 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000656}
657
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000658static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000659float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000661 double a,b;
662 CONVERT_TO_DOUBLE(v, a);
663 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000664 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000665 a = a + b;
666 PyFPE_END_PROTECT(a)
667 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000668}
669
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000670static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000671float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000673 double a,b;
674 CONVERT_TO_DOUBLE(v, a);
675 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000676 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677 a = a - b;
678 PyFPE_END_PROTECT(a)
679 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680}
681
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000683float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000684{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000685 double a,b;
686 CONVERT_TO_DOUBLE(v, a);
687 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000688 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000689 a = a * b;
690 PyFPE_END_PROTECT(a)
691 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000692}
693
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000695float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000697 double a,b;
698 CONVERT_TO_DOUBLE(v, a);
699 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000700#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000701 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000702 PyErr_SetString(PyExc_ZeroDivisionError,
703 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000704 return NULL;
705 }
Christian Heimes53876d92008-04-19 00:31:39 +0000706#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000707 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000708 a = a / b;
709 PyFPE_END_PROTECT(a)
710 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000711}
712
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000713static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000714float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000716 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000717 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000718 CONVERT_TO_DOUBLE(v, vx);
719 CONVERT_TO_DOUBLE(w, wx);
720#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000722 PyErr_SetString(PyExc_ZeroDivisionError,
723 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000724 return NULL;
725 }
Christian Heimes53876d92008-04-19 00:31:39 +0000726#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000727 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000728 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000729 /* note: checking mod*wx < 0 is incorrect -- underflows to
730 0 if wx < sqrt(smallest nonzero double) */
731 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000732 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000733 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000734 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736}
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000739float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000740{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000741 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000742 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000743 CONVERT_TO_DOUBLE(v, vx);
744 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000745 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000746 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000747 return NULL;
748 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000749 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000750 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000751 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000752 exact multiple of wx. But this is fp arithmetic, and fp
753 vx - mod is an approximation; the result is that div may
754 not be an exact integral value after the division, although
755 it will always be very close to one.
756 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000757 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000758 if (mod) {
759 /* ensure the remainder has the same sign as the denominator */
760 if ((wx < 0) != (mod < 0)) {
761 mod += wx;
762 div -= 1.0;
763 }
764 }
765 else {
766 /* the remainder is zero, and in the presence of signed zeroes
767 fmod returns different results across platforms; ensure
768 it has the same sign as the denominator; we'd like to do
769 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000770 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000771 if (wx < 0.0)
772 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000773 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000774 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000775 if (div) {
776 floordiv = floor(div);
777 if (div - floordiv > 0.5)
778 floordiv += 1.0;
779 }
780 else {
781 /* div is zero - get the same sign as the true quotient */
782 div *= div; /* hide "div = +0" from optimizers */
783 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
784 }
785 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000786 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000787}
788
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000790float_floor_div(PyObject *v, PyObject *w)
791{
792 PyObject *t, *r;
793
794 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000795 if (t == NULL || t == Py_NotImplemented)
796 return t;
797 assert(PyTuple_CheckExact(t));
798 r = PyTuple_GET_ITEM(t, 0);
799 Py_INCREF(r);
800 Py_DECREF(t);
801 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000802}
803
804static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000805float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806{
807 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000808
809 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000810 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000811 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000812 return NULL;
813 }
814
Neil Schemenauer32117e52001-01-04 01:44:34 +0000815 CONVERT_TO_DOUBLE(v, iv);
816 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000817
818 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000819 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000820 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000821 }
Tim Peters96685bf2001-08-23 22:31:37 +0000822 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000823 if (iw < 0.0) {
824 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000825 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000826 return NULL;
827 }
828 return PyFloat_FromDouble(0.0);
829 }
Christian Heimes53876d92008-04-19 00:31:39 +0000830 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
831 return PyFloat_FromDouble(1.0);
832 }
Tim Peterse87568d2003-05-24 20:18:24 +0000833 if (iv < 0.0) {
834 /* Whether this is an error is a mess, and bumps into libm
835 * bugs so we have to figure it out ourselves.
836 */
837 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000838 /* Negative numbers raised to fractional powers
839 * become complex.
840 */
841 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000842 }
843 /* iw is an exact integer, albeit perhaps a very large one.
844 * -1 raised to an exact integer should never be exceptional.
845 * Alas, some libms (chiefly glibc as of early 2003) return
846 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
847 * happen to be representable in a *C* integer. That's a
848 * bug; we let that slide in math.pow() (which currently
849 * reflects all platform accidents), but not for Python's **.
850 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000851 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000852 /* Return 1 if iw is even, -1 if iw is odd; there's
853 * no guarantee that any C integral type is big
854 * enough to hold iw, so we have to check this
855 * indirectly.
856 */
857 ix = floor(iw * 0.5) * 2.0;
858 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
859 }
860 /* Else iv != -1.0, and overflow or underflow are possible.
861 * Unless we're to write pow() ourselves, we have to trust
862 * the platform to do this correctly.
863 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000864 }
Tim Peters96685bf2001-08-23 22:31:37 +0000865 errno = 0;
866 PyFPE_START_PROTECT("pow", return NULL)
867 ix = pow(iv, iw);
868 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000869 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000870 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000871 /* We don't expect any errno value other than ERANGE, but
872 * the range of libm bugs appears unbounded.
873 */
874 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
875 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000876 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000877 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000878 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879}
880
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000882float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000883{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000884 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000885}
886
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000887static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000888float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000889{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000890 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000891}
892
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000893static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000894float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000895{
896 return v->ob_fval != 0.0;
897}
898
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000899static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000900float_is_integer(PyObject *v)
901{
902 double x = PyFloat_AsDouble(v);
903 PyObject *o;
904
905 if (x == -1.0 && PyErr_Occurred())
906 return NULL;
907 if (!Py_IS_FINITE(x))
908 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000909 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000910 PyFPE_START_PROTECT("is_integer", return NULL)
911 o = (floor(x) == x) ? Py_True : Py_False;
912 PyFPE_END_PROTECT(x)
913 if (errno != 0) {
914 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
915 PyExc_ValueError);
916 return NULL;
917 }
918 Py_INCREF(o);
919 return o;
920}
921
922#if 0
923static PyObject *
924float_is_inf(PyObject *v)
925{
926 double x = PyFloat_AsDouble(v);
927 if (x == -1.0 && PyErr_Occurred())
928 return NULL;
929 return PyBool_FromLong((long)Py_IS_INFINITY(x));
930}
931
932static PyObject *
933float_is_nan(PyObject *v)
934{
935 double x = PyFloat_AsDouble(v);
936 if (x == -1.0 && PyErr_Occurred())
937 return NULL;
938 return PyBool_FromLong((long)Py_IS_NAN(x));
939}
940
941static PyObject *
942float_is_finite(PyObject *v)
943{
944 double x = PyFloat_AsDouble(v);
945 if (x == -1.0 && PyErr_Occurred())
946 return NULL;
947 return PyBool_FromLong((long)Py_IS_FINITE(x));
948}
949#endif
950
951static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000952float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000953{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000955 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000956
957 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000958 /* Try to get out cheap if this fits in a Python int. The attempt
959 * to cast to long must be protected, as C doesn't define what
960 * happens if the double is too big to fit in a long. Some rare
961 * systems raise an exception then (RISCOS was mentioned as one,
962 * and someone using a non-default option on Sun also bumped into
963 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
964 * still be vulnerable: if a long has more bits of precision than
965 * a double, casting MIN/MAX to double may yield an approximation,
966 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
967 * yield true from the C expression wholepart<=LONG_MAX, despite
968 * that wholepart is actually greater than LONG_MAX.
969 */
970 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
971 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000972 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000973 }
974 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000975}
976
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000977static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000978float_round(PyObject *v, PyObject *args)
979{
980#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
981 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000982 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000983 double flr, cil;
984 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000985 int ndigits = UNDEF_NDIGITS;
986
987 if (!PyArg_ParseTuple(args, "|i", &ndigits))
988 return NULL;
989
990 x = PyFloat_AsDouble(v);
991
992 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000993 f = pow(10.0, ndigits);
994 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000995 }
996
997 flr = floor(x);
998 cil = ceil(x);
999
1000 if (x-flr > 0.5)
1001 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001002 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001003 rounded = fmod(flr, 2) == 0 ? flr : cil;
1004 else
1005 rounded = flr;
1006
1007 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001008 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001009 return PyFloat_FromDouble(rounded);
1010 }
1011
1012 return PyLong_FromDouble(rounded);
1013#undef UNDEF_NDIGITS
1014}
1015
1016static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001017float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001018{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001019 if (PyFloat_CheckExact(v))
1020 Py_INCREF(v);
1021 else
1022 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001023 return v;
1024}
1025
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001026/* turn ASCII hex characters into integer values and vice versa */
1027
1028static char
1029char_from_hex(int x)
1030{
1031 assert(0 <= x && x < 16);
1032 return "0123456789abcdef"[x];
1033}
1034
1035static int
1036hex_from_char(char c) {
1037 int x;
1038 assert(isxdigit(c));
1039 switch(c) {
1040 case '0':
1041 x = 0;
1042 break;
1043 case '1':
1044 x = 1;
1045 break;
1046 case '2':
1047 x = 2;
1048 break;
1049 case '3':
1050 x = 3;
1051 break;
1052 case '4':
1053 x = 4;
1054 break;
1055 case '5':
1056 x = 5;
1057 break;
1058 case '6':
1059 x = 6;
1060 break;
1061 case '7':
1062 x = 7;
1063 break;
1064 case '8':
1065 x = 8;
1066 break;
1067 case '9':
1068 x = 9;
1069 break;
1070 case 'a':
1071 case 'A':
1072 x = 10;
1073 break;
1074 case 'b':
1075 case 'B':
1076 x = 11;
1077 break;
1078 case 'c':
1079 case 'C':
1080 x = 12;
1081 break;
1082 case 'd':
1083 case 'D':
1084 x = 13;
1085 break;
1086 case 'e':
1087 case 'E':
1088 x = 14;
1089 break;
1090 case 'f':
1091 case 'F':
1092 x = 15;
1093 break;
1094 default:
1095 x = -1;
1096 break;
1097 }
1098 return x;
1099}
1100
1101/* convert a float to a hexadecimal string */
1102
1103/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1104 of the form 4k+1. */
1105#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1106
1107static PyObject *
1108float_hex(PyObject *v)
1109{
1110 double x, m;
1111 int e, shift, i, si, esign;
1112 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1113 trailing NUL byte. */
1114 char s[(TOHEX_NBITS-1)/4+3];
1115
1116 CONVERT_TO_DOUBLE(v, x);
1117
1118 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1119 return float_str((PyFloatObject *)v);
1120
1121 if (x == 0.0) {
1122 if(copysign(1.0, x) == -1.0)
1123 return PyUnicode_FromString("-0x0.0p+0");
1124 else
1125 return PyUnicode_FromString("0x0.0p+0");
1126 }
1127
1128 m = frexp(fabs(x), &e);
1129 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1130 m = ldexp(m, shift);
1131 e -= shift;
1132
1133 si = 0;
1134 s[si] = char_from_hex((int)m);
1135 si++;
1136 m -= (int)m;
1137 s[si] = '.';
1138 si++;
1139 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1140 m *= 16.0;
1141 s[si] = char_from_hex((int)m);
1142 si++;
1143 m -= (int)m;
1144 }
1145 s[si] = '\0';
1146
1147 if (e < 0) {
1148 esign = (int)'-';
1149 e = -e;
1150 }
1151 else
1152 esign = (int)'+';
1153
1154 if (x < 0.0)
1155 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1156 else
1157 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
1158}
1159
1160PyDoc_STRVAR(float_hex_doc,
1161"float.hex() -> string\n\
1162\n\
1163Return a hexadecimal representation of a floating-point number.\n\
1164>>> (-0.1).hex()\n\
1165'-0x1.999999999999ap-4'\n\
1166>>> 3.14159.hex()\n\
1167'0x1.921f9f01b866ep+1'");
1168
1169/* Convert a hexadecimal string to a float. */
1170
1171static PyObject *
1172float_fromhex(PyObject *cls, PyObject *arg)
1173{
1174 PyObject *result_as_float, *result;
1175 double x;
1176 long exp, top_exp, lsb, key_digit;
1177 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1178 int half_eps, digit, round_up, sign=1;
1179 Py_ssize_t length, ndigits, fdigits, i;
1180
1181 /*
1182 * For the sake of simplicity and correctness, we impose an artificial
1183 * limit on ndigits, the total number of hex digits in the coefficient
1184 * The limit is chosen to ensure that, writing exp for the exponent,
1185 *
1186 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1187 * guaranteed to overflow (provided it's nonzero)
1188 *
1189 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1190 * guaranteed to underflow to 0.
1191 *
1192 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1193 * overflow in the calculation of exp and top_exp below.
1194 *
1195 * More specifically, ndigits is assumed to satisfy the following
1196 * inequalities:
1197 *
1198 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1199 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1200 *
1201 * If either of these inequalities is not satisfied, a ValueError is
1202 * raised. Otherwise, write x for the value of the hex string, and
1203 * assume x is nonzero. Then
1204 *
1205 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1206 *
1207 * Now if exp > LONG_MAX/2 then:
1208 *
1209 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1210 * = DBL_MAX_EXP
1211 *
1212 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1213 * double, so overflows. If exp < LONG_MIN/2, then
1214 *
1215 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1216 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1217 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1218 *
1219 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1220 * when converted to a C double.
1221 *
1222 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1223 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1224 */
1225
1226 s = PyUnicode_AsStringAndSize(arg, &length);
1227 if (s == NULL)
1228 return NULL;
1229 s_end = s + length;
1230
1231 /********************
1232 * Parse the string *
1233 ********************/
1234
1235 /* leading whitespace and optional sign */
1236 while (isspace(*s))
1237 s++;
1238 if (*s == '-') {
1239 s++;
1240 sign = -1;
1241 }
1242 else if (*s == '+')
1243 s++;
1244
1245 /* infinities and nans */
1246 if (PyOS_mystrnicmp(s, "nan", 4) == 0) {
1247 x = Py_NAN;
1248 goto finished;
1249 }
1250 if (PyOS_mystrnicmp(s, "inf", 4) == 0 ||
1251 PyOS_mystrnicmp(s, "infinity", 9) == 0) {
1252 x = sign*Py_HUGE_VAL;
1253 goto finished;
1254 }
1255
1256 /* [0x] */
1257 s_store = s;
1258 if (*s == '0') {
1259 s++;
1260 if (tolower(*s) == (int)'x')
1261 s++;
1262 else
1263 s = s_store;
1264 }
1265
1266 /* coefficient: <integer> [. <fraction>] */
1267 coeff_start = s;
1268 while (isxdigit(*s))
1269 s++;
1270 s_store = s;
1271 if (*s == '.') {
1272 s++;
1273 while (isxdigit(*s))
1274 s++;
1275 coeff_end = s-1;
1276 }
1277 else
1278 coeff_end = s;
1279
1280 /* ndigits = total # of hex digits; fdigits = # after point */
1281 ndigits = coeff_end - coeff_start;
1282 fdigits = coeff_end - s_store;
1283 if (ndigits == 0)
1284 goto parse_error;
1285 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1286 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1287 goto insane_length_error;
1288
1289 /* [p <exponent>] */
1290 if (tolower(*s) == (int)'p') {
1291 s++;
1292 exp_start = s;
1293 if (*s == '-' || *s == '+')
1294 s++;
1295 if (!isdigit(*s))
1296 goto parse_error;
1297 s++;
1298 while (isdigit(*s))
1299 s++;
1300 exp = strtol(exp_start, NULL, 10);
1301 }
1302 else
1303 exp = 0;
1304
1305 /* optional trailing whitespace leading to the end of the string */
1306 while (isspace(*s))
1307 s++;
1308 if (s != s_end)
1309 goto parse_error;
1310
1311/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1312#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1313 coeff_end-(j) : \
1314 coeff_end-1-(j)))
1315
1316 /*******************************************
1317 * Compute rounded value of the hex string *
1318 *******************************************/
1319
1320 /* Discard leading zeros, and catch extreme overflow and underflow */
1321 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1322 ndigits--;
1323 if (ndigits == 0 || exp < LONG_MIN/2) {
1324 x = sign * 0.0;
1325 goto finished;
1326 }
1327 if (exp > LONG_MAX/2)
1328 goto overflow_error;
1329
1330 /* Adjust exponent for fractional part. */
1331 exp = exp - 4*((long)fdigits);
1332
1333 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1334 top_exp = exp + 4*((long)ndigits - 1);
1335 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1336 top_exp++;
1337
1338 /* catch almost all nonextreme cases of overflow and underflow here */
1339 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1340 x = sign * 0.0;
1341 goto finished;
1342 }
1343 if (top_exp > DBL_MAX_EXP)
1344 goto overflow_error;
1345
1346 /* lsb = exponent of least significant bit of the *rounded* value.
1347 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1348 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1349
1350 x = 0.0;
1351 if (exp >= lsb) {
1352 /* no rounding required */
1353 for (i = ndigits-1; i >= 0; i--)
1354 x = 16.0*x + HEX_DIGIT(i);
1355 x = sign * ldexp(x, (int)(exp));
1356 goto finished;
1357 }
1358 /* rounding required. key_digit is the index of the hex digit
1359 containing the first bit to be rounded away. */
1360 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1361 key_digit = (lsb - exp - 1) / 4;
1362 for (i = ndigits-1; i > key_digit; i--)
1363 x = 16.0*x + HEX_DIGIT(i);
1364 digit = HEX_DIGIT(key_digit);
1365 x = 16.0*x + (double)(digit & (16-2*half_eps));
1366
1367 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1368 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1369 if ((digit & half_eps) != 0) {
1370 round_up = 0;
1371 if ((digit & (3*half_eps-1)) != 0 ||
1372 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1373 round_up = 1;
1374 else
1375 for (i = key_digit-1; i >= 0; i--)
1376 if (HEX_DIGIT(i) != 0) {
1377 round_up = 1;
1378 break;
1379 }
1380 if (round_up == 1) {
1381 x += 2*half_eps;
1382 if (top_exp == DBL_MAX_EXP &&
1383 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1384 /* overflow corner case: pre-rounded value <
1385 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1386 goto overflow_error;
1387 }
1388 }
1389 x = sign * ldexp(x, (int)(exp+4*key_digit));
1390
1391 finished:
1392 result_as_float = Py_BuildValue("(d)", x);
1393 if (result_as_float == NULL)
1394 return NULL;
1395 result = PyObject_CallObject(cls, result_as_float);
1396 Py_DECREF(result_as_float);
1397 return result;
1398
1399 overflow_error:
1400 PyErr_SetString(PyExc_OverflowError,
1401 "hexadecimal value too large to represent as a float");
1402 return NULL;
1403
1404 parse_error:
1405 PyErr_SetString(PyExc_ValueError,
1406 "invalid hexadecimal floating-point string");
1407 return NULL;
1408
1409 insane_length_error:
1410 PyErr_SetString(PyExc_ValueError,
1411 "hexadecimal string too long to convert");
1412 return NULL;
1413}
1414
1415PyDoc_STRVAR(float_fromhex_doc,
1416"float.fromhex(string) -> float\n\
1417\n\
1418Create a floating-point number from a hexadecimal string.\n\
1419>>> float.fromhex('0x1.ffffp10')\n\
14202047.984375\n\
1421>>> float.fromhex('-0x1p-1074')\n\
1422-4.9406564584124654e-324");
1423
1424
Christian Heimes26855632008-01-27 23:50:43 +00001425static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001426float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001427{
1428 double self;
1429 double float_part;
1430 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001431 int i;
1432
Christian Heimes26855632008-01-27 23:50:43 +00001433 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001434 PyObject *py_exponent = NULL;
1435 PyObject *numerator = NULL;
1436 PyObject *denominator = NULL;
1437 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001438 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001439
1440#define INPLACE_UPDATE(obj, call) \
1441 prev = obj; \
1442 obj = call; \
1443 Py_DECREF(prev); \
1444
1445 CONVERT_TO_DOUBLE(v, self);
1446
1447 if (Py_IS_INFINITY(self)) {
1448 PyErr_SetString(PyExc_OverflowError,
1449 "Cannot pass infinity to float.as_integer_ratio.");
1450 return NULL;
1451 }
1452#ifdef Py_NAN
1453 if (Py_IS_NAN(self)) {
1454 PyErr_SetString(PyExc_ValueError,
1455 "Cannot pass nan to float.as_integer_ratio.");
1456 return NULL;
1457 }
1458#endif
1459
Christian Heimes26855632008-01-27 23:50:43 +00001460 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001461 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001462 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001463
1464 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1465 float_part *= 2.0;
1466 exponent--;
1467 }
1468 /* self == float_part * 2**exponent exactly and float_part is integral.
1469 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1470 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001471
Christian Heimes292d3512008-02-03 16:51:08 +00001472 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001473 if (numerator == NULL) goto error;
1474
Christian Heimes292d3512008-02-03 16:51:08 +00001475 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001476 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001477 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001478 if (py_exponent == NULL) goto error;
1479 INPLACE_UPDATE(py_exponent,
1480 long_methods->nb_lshift(denominator, py_exponent));
1481 if (py_exponent == NULL) goto error;
1482 if (exponent > 0) {
1483 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001484 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001485 if (numerator == NULL) goto error;
1486 }
1487 else {
1488 Py_DECREF(denominator);
1489 denominator = py_exponent;
1490 py_exponent = NULL;
1491 }
1492
Christian Heimes292d3512008-02-03 16:51:08 +00001493 /* Returns ints instead of longs where possible */
1494 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1495 if (numerator == NULL) goto error;
1496 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1497 if (denominator == NULL) goto error;
1498
Christian Heimes26855632008-01-27 23:50:43 +00001499 result_pair = PyTuple_Pack(2, numerator, denominator);
1500
1501#undef INPLACE_UPDATE
1502error:
1503 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001504 Py_XDECREF(denominator);
1505 Py_XDECREF(numerator);
1506 return result_pair;
1507}
1508
1509PyDoc_STRVAR(float_as_integer_ratio_doc,
1510"float.as_integer_ratio() -> (int, int)\n"
1511"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001512"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1513"float and with a positive denominator.\n"
1514"Raises OverflowError on infinities and a ValueError on nans.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001515"\n"
1516">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001517"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001518">>> (0.0).as_integer_ratio()\n"
1519"(0, 1)\n"
1520">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001521"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001522
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001523
Jeremy Hylton938ace62002-07-17 16:30:39 +00001524static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001525float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1526
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527static PyObject *
1528float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1529{
1530 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001531 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532
Guido van Rossumbef14172001-08-29 15:47:46 +00001533 if (type != &PyFloat_Type)
1534 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1536 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001537 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001538 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539 return PyNumber_Float(x);
1540}
1541
Guido van Rossumbef14172001-08-29 15:47:46 +00001542/* Wimpy, slow approach to tp_new calls for subtypes of float:
1543 first create a regular float from whatever arguments we got,
1544 then allocate a subtype instance and initialize its ob_fval
1545 from the regular float. The regular float is then thrown away.
1546*/
1547static PyObject *
1548float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1549{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001550 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001551
1552 assert(PyType_IsSubtype(type, &PyFloat_Type));
1553 tmp = float_new(&PyFloat_Type, args, kwds);
1554 if (tmp == NULL)
1555 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001556 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001557 newobj = type->tp_alloc(type, 0);
1558 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001559 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001560 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001561 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001562 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001563 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001564 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001565}
1566
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001567static PyObject *
1568float_getnewargs(PyFloatObject *v)
1569{
1570 return Py_BuildValue("(d)", v->ob_fval);
1571}
1572
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001573/* this is for the benefit of the pack/unpack routines below */
1574
1575typedef enum {
1576 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1577} float_format_type;
1578
1579static float_format_type double_format, float_format;
1580static float_format_type detected_double_format, detected_float_format;
1581
1582static PyObject *
1583float_getformat(PyTypeObject *v, PyObject* arg)
1584{
1585 char* s;
1586 float_format_type r;
1587
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001588 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001589 PyErr_Format(PyExc_TypeError,
1590 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001591 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001592 return NULL;
1593 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001594 s = PyUnicode_AsString(arg);
1595 if (s == NULL)
1596 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597 if (strcmp(s, "double") == 0) {
1598 r = double_format;
1599 }
1600 else if (strcmp(s, "float") == 0) {
1601 r = float_format;
1602 }
1603 else {
1604 PyErr_SetString(PyExc_ValueError,
1605 "__getformat__() argument 1 must be "
1606 "'double' or 'float'");
1607 return NULL;
1608 }
1609
1610 switch (r) {
1611 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001612 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001614 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001616 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617 default:
1618 Py_FatalError("insane float_format or double_format");
1619 return NULL;
1620 }
1621}
1622
1623PyDoc_STRVAR(float_getformat_doc,
1624"float.__getformat__(typestr) -> string\n"
1625"\n"
1626"You probably don't want to use this function. It exists mainly to be\n"
1627"used in Python's test suite.\n"
1628"\n"
1629"typestr must be 'double' or 'float'. This function returns whichever of\n"
1630"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1631"format of floating point numbers used by the C type named by typestr.");
1632
1633static PyObject *
1634float_setformat(PyTypeObject *v, PyObject* args)
1635{
1636 char* typestr;
1637 char* format;
1638 float_format_type f;
1639 float_format_type detected;
1640 float_format_type *p;
1641
1642 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1643 return NULL;
1644
1645 if (strcmp(typestr, "double") == 0) {
1646 p = &double_format;
1647 detected = detected_double_format;
1648 }
1649 else if (strcmp(typestr, "float") == 0) {
1650 p = &float_format;
1651 detected = detected_float_format;
1652 }
1653 else {
1654 PyErr_SetString(PyExc_ValueError,
1655 "__setformat__() argument 1 must "
1656 "be 'double' or 'float'");
1657 return NULL;
1658 }
1659
1660 if (strcmp(format, "unknown") == 0) {
1661 f = unknown_format;
1662 }
1663 else if (strcmp(format, "IEEE, little-endian") == 0) {
1664 f = ieee_little_endian_format;
1665 }
1666 else if (strcmp(format, "IEEE, big-endian") == 0) {
1667 f = ieee_big_endian_format;
1668 }
1669 else {
1670 PyErr_SetString(PyExc_ValueError,
1671 "__setformat__() argument 2 must be "
1672 "'unknown', 'IEEE, little-endian' or "
1673 "'IEEE, big-endian'");
1674 return NULL;
1675
1676 }
1677
1678 if (f != unknown_format && f != detected) {
1679 PyErr_Format(PyExc_ValueError,
1680 "can only set %s format to 'unknown' or the "
1681 "detected platform value", typestr);
1682 return NULL;
1683 }
1684
1685 *p = f;
1686 Py_RETURN_NONE;
1687}
1688
1689PyDoc_STRVAR(float_setformat_doc,
1690"float.__setformat__(typestr, fmt) -> None\n"
1691"\n"
1692"You probably don't want to use this function. It exists mainly to be\n"
1693"used in Python's test suite.\n"
1694"\n"
1695"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1696"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1697"one of the latter two if it appears to match the underlying C reality.\n"
1698"\n"
1699"Overrides the automatic determination of C-level floating point type.\n"
1700"This affects how floats are converted to and from binary strings.");
1701
Guido van Rossumb43daf72007-08-01 18:08:08 +00001702static PyObject *
1703float_getzero(PyObject *v, void *closure)
1704{
1705 return PyFloat_FromDouble(0.0);
1706}
1707
Eric Smith8c663262007-08-25 02:26:07 +00001708static PyObject *
1709float__format__(PyObject *self, PyObject *args)
1710{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001711 PyObject *format_spec;
1712
1713 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1714 return NULL;
1715 return _PyFloat_FormatAdvanced(self,
1716 PyUnicode_AS_UNICODE(format_spec),
1717 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001718}
1719
1720PyDoc_STRVAR(float__format__doc,
1721"float.__format__(format_spec) -> string\n"
1722"\n"
1723"Formats the float according to format_spec.");
1724
1725
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001726static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001727 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001728 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001729 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1730 "Returns the Integral closest to x between 0 and x."},
1731 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1732 "Returns the Integral closest to x, rounding half toward even.\n"
1733 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001734 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1735 float_as_integer_ratio_doc},
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001736 {"fromhex", (PyCFunction)float_fromhex,
1737 METH_O|METH_CLASS, float_fromhex_doc},
1738 {"hex", (PyCFunction)float_hex,
1739 METH_NOARGS, float_hex_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001740 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1741 "Returns True if the float is an integer."},
1742#if 0
1743 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1744 "Returns True if the float is positive or negative infinite."},
1745 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1746 "Returns True if the float is finite, neither infinite nor NaN."},
1747 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1748 "Returns True if the float is not a number (NaN)."},
1749#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001750 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001751 {"__getformat__", (PyCFunction)float_getformat,
1752 METH_O|METH_CLASS, float_getformat_doc},
1753 {"__setformat__", (PyCFunction)float_setformat,
1754 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001755 {"__format__", (PyCFunction)float__format__,
1756 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001757 {NULL, NULL} /* sentinel */
1758};
1759
Guido van Rossumb43daf72007-08-01 18:08:08 +00001760static PyGetSetDef float_getset[] = {
1761 {"real",
1762 (getter)float_float, (setter)NULL,
1763 "the real part of a complex number",
1764 NULL},
1765 {"imag",
1766 (getter)float_getzero, (setter)NULL,
1767 "the imaginary part of a complex number",
1768 NULL},
1769 {NULL} /* Sentinel */
1770};
1771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001772PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773"float(x) -> floating point number\n\
1774\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001775Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776
1777
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001778static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001779 float_add, /*nb_add*/
1780 float_sub, /*nb_subtract*/
1781 float_mul, /*nb_multiply*/
1782 float_rem, /*nb_remainder*/
1783 float_divmod, /*nb_divmod*/
1784 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001785 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001786 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001787 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001788 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001789 0, /*nb_invert*/
1790 0, /*nb_lshift*/
1791 0, /*nb_rshift*/
1792 0, /*nb_and*/
1793 0, /*nb_xor*/
1794 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001795 float_trunc, /*nb_int*/
1796 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001797 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001798 0, /* nb_inplace_add */
1799 0, /* nb_inplace_subtract */
1800 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001801 0, /* nb_inplace_remainder */
1802 0, /* nb_inplace_power */
1803 0, /* nb_inplace_lshift */
1804 0, /* nb_inplace_rshift */
1805 0, /* nb_inplace_and */
1806 0, /* nb_inplace_xor */
1807 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001808 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001809 float_div, /* nb_true_divide */
1810 0, /* nb_inplace_floor_divide */
1811 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001812};
1813
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001814PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001815 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001816 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001817 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001818 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001820 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 0, /* tp_getattr */
1822 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001823 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824 (reprfunc)float_repr, /* tp_repr */
1825 &float_as_number, /* tp_as_number */
1826 0, /* tp_as_sequence */
1827 0, /* tp_as_mapping */
1828 (hashfunc)float_hash, /* tp_hash */
1829 0, /* tp_call */
1830 (reprfunc)float_str, /* tp_str */
1831 PyObject_GenericGetAttr, /* tp_getattro */
1832 0, /* tp_setattro */
1833 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001834 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835 float_doc, /* tp_doc */
1836 0, /* tp_traverse */
1837 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001838 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 0, /* tp_weaklistoffset */
1840 0, /* tp_iter */
1841 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001842 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001844 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 0, /* tp_base */
1846 0, /* tp_dict */
1847 0, /* tp_descr_get */
1848 0, /* tp_descr_set */
1849 0, /* tp_dictoffset */
1850 0, /* tp_init */
1851 0, /* tp_alloc */
1852 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001854
1855void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001856_PyFloat_Init(void)
1857{
1858 /* We attempt to determine if this machine is using IEEE
1859 floating point formats by peering at the bits of some
1860 carefully chosen values. If it looks like we are on an
1861 IEEE platform, the float packing/unpacking routines can
1862 just copy bits, if not they resort to arithmetic & shifts
1863 and masks. The shifts & masks approach works on all finite
1864 values, but what happens to infinities, NaNs and signed
1865 zeroes on packing is an accident, and attempting to unpack
1866 a NaN or an infinity will raise an exception.
1867
1868 Note that if we're on some whacked-out platform which uses
1869 IEEE formats but isn't strictly little-endian or big-
1870 endian, we will fall back to the portable shifts & masks
1871 method. */
1872
1873#if SIZEOF_DOUBLE == 8
1874 {
1875 double x = 9006104071832581.0;
1876 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1877 detected_double_format = ieee_big_endian_format;
1878 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1879 detected_double_format = ieee_little_endian_format;
1880 else
1881 detected_double_format = unknown_format;
1882 }
1883#else
1884 detected_double_format = unknown_format;
1885#endif
1886
1887#if SIZEOF_FLOAT == 4
1888 {
1889 float y = 16711938.0;
1890 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1891 detected_float_format = ieee_big_endian_format;
1892 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1893 detected_float_format = ieee_little_endian_format;
1894 else
1895 detected_float_format = unknown_format;
1896 }
1897#else
1898 detected_float_format = unknown_format;
1899#endif
1900
1901 double_format = detected_double_format;
1902 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001903
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001904 /* Init float info */
1905 if (FloatInfoType.tp_name == 0)
1906 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907}
1908
Georg Brandl2ee470f2008-07-16 12:55:28 +00001909int
1910PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001911{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001912 PyFloatObject *p;
1913 PyFloatBlock *list, *next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001914 int i;
1915 int u; /* remaining unfreed ints per block */
1916 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001917
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001918 list = block_list;
1919 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001920 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001921 while (list != NULL) {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001922 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001923 for (i = 0, p = &list->objects[0];
1924 i < N_FLOATOBJECTS;
1925 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001926 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Georg Brandl2ee470f2008-07-16 12:55:28 +00001927 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001928 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001929 next = list->next;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001930 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001931 list->next = block_list;
1932 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001933 for (i = 0, p = &list->objects[0];
1934 i < N_FLOATOBJECTS;
1935 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001936 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001937 Py_REFCNT(p) == 0) {
1938 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001939 free_list;
1940 free_list = p;
1941 }
1942 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001943 }
1944 else {
Georg Brandl2ee470f2008-07-16 12:55:28 +00001945 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001946 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001947 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001948 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001949 }
Georg Brandl2ee470f2008-07-16 12:55:28 +00001950 return freelist_size;
Christian Heimes15ebc882008-02-04 18:48:49 +00001951}
1952
1953void
1954PyFloat_Fini(void)
1955{
1956 PyFloatObject *p;
1957 PyFloatBlock *list;
Georg Brandl2ee470f2008-07-16 12:55:28 +00001958 int i;
1959 int u; /* total unfreed floats per block */
Christian Heimes15ebc882008-02-04 18:48:49 +00001960
Georg Brandl2ee470f2008-07-16 12:55:28 +00001961 u = PyFloat_ClearFreeList();
Christian Heimes15ebc882008-02-04 18:48:49 +00001962
Guido van Rossum3fce8831999-03-12 19:43:17 +00001963 if (!Py_VerboseFlag)
1964 return;
1965 fprintf(stderr, "# cleanup floats");
Georg Brandl2ee470f2008-07-16 12:55:28 +00001966 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001967 fprintf(stderr, "\n");
1968 }
1969 else {
1970 fprintf(stderr,
Georg Brandl2ee470f2008-07-16 12:55:28 +00001971 ": %d unfreed float%s\n",
1972 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001973 }
1974 if (Py_VerboseFlag > 1) {
1975 list = block_list;
1976 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001977 for (i = 0, p = &list->objects[0];
1978 i < N_FLOATOBJECTS;
1979 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001980 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001981 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001982 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001983 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001984 /* XXX(twouters) cast refcount to
1985 long until %zd is universally
1986 available
1987 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001988 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001989 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001990 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001991 }
1992 }
1993 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001994 }
1995 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001996}
Tim Peters9905b942003-03-20 20:53:32 +00001997
1998/*----------------------------------------------------------------------------
1999 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002000 */
2001int
2002_PyFloat_Pack4(double x, unsigned char *p, int le)
2003{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002004 if (float_format == unknown_format) {
2005 unsigned char sign;
2006 int e;
2007 double f;
2008 unsigned int fbits;
2009 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002010
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002011 if (le) {
2012 p += 3;
2013 incr = -1;
2014 }
Tim Peters9905b942003-03-20 20:53:32 +00002015
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002016 if (x < 0) {
2017 sign = 1;
2018 x = -x;
2019 }
2020 else
2021 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002022
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002023 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002024
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002025 /* Normalize f to be in the range [1.0, 2.0) */
2026 if (0.5 <= f && f < 1.0) {
2027 f *= 2.0;
2028 e--;
2029 }
2030 else if (f == 0.0)
2031 e = 0;
2032 else {
2033 PyErr_SetString(PyExc_SystemError,
2034 "frexp() result out of range");
2035 return -1;
2036 }
2037
2038 if (e >= 128)
2039 goto Overflow;
2040 else if (e < -126) {
2041 /* Gradual underflow */
2042 f = ldexp(f, 126 + e);
2043 e = 0;
2044 }
2045 else if (!(e == 0 && f == 0.0)) {
2046 e += 127;
2047 f -= 1.0; /* Get rid of leading 1 */
2048 }
2049
2050 f *= 8388608.0; /* 2**23 */
2051 fbits = (unsigned int)(f + 0.5); /* Round */
2052 assert(fbits <= 8388608);
2053 if (fbits >> 23) {
2054 /* The carry propagated out of a string of 23 1 bits. */
2055 fbits = 0;
2056 ++e;
2057 if (e >= 255)
2058 goto Overflow;
2059 }
2060
2061 /* First byte */
2062 *p = (sign << 7) | (e >> 1);
2063 p += incr;
2064
2065 /* Second byte */
2066 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2067 p += incr;
2068
2069 /* Third byte */
2070 *p = (fbits >> 8) & 0xFF;
2071 p += incr;
2072
2073 /* Fourth byte */
2074 *p = fbits & 0xFF;
2075
2076 /* Done */
2077 return 0;
2078
Tim Peters9905b942003-03-20 20:53:32 +00002079 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002080 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002081 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002082 const char *s = (char*)&y;
2083 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002084
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002085 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2086 goto Overflow;
2087
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088 if ((float_format == ieee_little_endian_format && !le)
2089 || (float_format == ieee_big_endian_format && le)) {
2090 p += 3;
2091 incr = -1;
2092 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002093
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002094 for (i = 0; i < 4; i++) {
2095 *p = *s++;
2096 p += incr;
2097 }
2098 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002099 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002100 Overflow:
2101 PyErr_SetString(PyExc_OverflowError,
2102 "float too large to pack with f format");
2103 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002104}
2105
2106int
2107_PyFloat_Pack8(double x, unsigned char *p, int le)
2108{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002109 if (double_format == unknown_format) {
2110 unsigned char sign;
2111 int e;
2112 double f;
2113 unsigned int fhi, flo;
2114 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002115
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002116 if (le) {
2117 p += 7;
2118 incr = -1;
2119 }
Tim Peters9905b942003-03-20 20:53:32 +00002120
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002121 if (x < 0) {
2122 sign = 1;
2123 x = -x;
2124 }
2125 else
2126 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002127
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002128 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002129
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002130 /* Normalize f to be in the range [1.0, 2.0) */
2131 if (0.5 <= f && f < 1.0) {
2132 f *= 2.0;
2133 e--;
2134 }
2135 else if (f == 0.0)
2136 e = 0;
2137 else {
2138 PyErr_SetString(PyExc_SystemError,
2139 "frexp() result out of range");
2140 return -1;
2141 }
2142
2143 if (e >= 1024)
2144 goto Overflow;
2145 else if (e < -1022) {
2146 /* Gradual underflow */
2147 f = ldexp(f, 1022 + e);
2148 e = 0;
2149 }
2150 else if (!(e == 0 && f == 0.0)) {
2151 e += 1023;
2152 f -= 1.0; /* Get rid of leading 1 */
2153 }
2154
2155 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2156 f *= 268435456.0; /* 2**28 */
2157 fhi = (unsigned int)f; /* Truncate */
2158 assert(fhi < 268435456);
2159
2160 f -= (double)fhi;
2161 f *= 16777216.0; /* 2**24 */
2162 flo = (unsigned int)(f + 0.5); /* Round */
2163 assert(flo <= 16777216);
2164 if (flo >> 24) {
2165 /* The carry propagated out of a string of 24 1 bits. */
2166 flo = 0;
2167 ++fhi;
2168 if (fhi >> 28) {
2169 /* And it also progagated out of the next 28 bits. */
2170 fhi = 0;
2171 ++e;
2172 if (e >= 2047)
2173 goto Overflow;
2174 }
2175 }
2176
2177 /* First byte */
2178 *p = (sign << 7) | (e >> 4);
2179 p += incr;
2180
2181 /* Second byte */
2182 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2183 p += incr;
2184
2185 /* Third byte */
2186 *p = (fhi >> 16) & 0xFF;
2187 p += incr;
2188
2189 /* Fourth byte */
2190 *p = (fhi >> 8) & 0xFF;
2191 p += incr;
2192
2193 /* Fifth byte */
2194 *p = fhi & 0xFF;
2195 p += incr;
2196
2197 /* Sixth byte */
2198 *p = (flo >> 16) & 0xFF;
2199 p += incr;
2200
2201 /* Seventh byte */
2202 *p = (flo >> 8) & 0xFF;
2203 p += incr;
2204
2205 /* Eighth byte */
2206 *p = flo & 0xFF;
2207 p += incr;
2208
2209 /* Done */
2210 return 0;
2211
2212 Overflow:
2213 PyErr_SetString(PyExc_OverflowError,
2214 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002215 return -1;
2216 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217 else {
2218 const char *s = (char*)&x;
2219 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002220
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002221 if ((double_format == ieee_little_endian_format && !le)
2222 || (double_format == ieee_big_endian_format && le)) {
2223 p += 7;
2224 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002225 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226
2227 for (i = 0; i < 8; i++) {
2228 *p = *s++;
2229 p += incr;
2230 }
2231 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002232 }
Tim Peters9905b942003-03-20 20:53:32 +00002233}
2234
Neal Norwitz545686b2006-12-28 04:45:06 +00002235/* Should only be used by marshal. */
2236int
2237_PyFloat_Repr(double x, char *p, size_t len)
2238{
2239 format_double(p, len, x, PREC_REPR);
2240 return (int)strlen(p);
2241}
2242
Tim Peters9905b942003-03-20 20:53:32 +00002243double
2244_PyFloat_Unpack4(const unsigned char *p, int le)
2245{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246 if (float_format == unknown_format) {
2247 unsigned char sign;
2248 int e;
2249 unsigned int f;
2250 double x;
2251 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002252
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002253 if (le) {
2254 p += 3;
2255 incr = -1;
2256 }
2257
2258 /* First byte */
2259 sign = (*p >> 7) & 1;
2260 e = (*p & 0x7F) << 1;
2261 p += incr;
2262
2263 /* Second byte */
2264 e |= (*p >> 7) & 1;
2265 f = (*p & 0x7F) << 16;
2266 p += incr;
2267
2268 if (e == 255) {
2269 PyErr_SetString(
2270 PyExc_ValueError,
2271 "can't unpack IEEE 754 special value "
2272 "on non-IEEE platform");
2273 return -1;
2274 }
2275
2276 /* Third byte */
2277 f |= *p << 8;
2278 p += incr;
2279
2280 /* Fourth byte */
2281 f |= *p;
2282
2283 x = (double)f / 8388608.0;
2284
2285 /* XXX This sadly ignores Inf/NaN issues */
2286 if (e == 0)
2287 e = -126;
2288 else {
2289 x += 1.0;
2290 e -= 127;
2291 }
2292 x = ldexp(x, e);
2293
2294 if (sign)
2295 x = -x;
2296
2297 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002298 }
Tim Peters9905b942003-03-20 20:53:32 +00002299 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002300 float x;
2301
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302 if ((float_format == ieee_little_endian_format && !le)
2303 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002304 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305 char *d = &buf[3];
2306 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002307
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308 for (i = 0; i < 4; i++) {
2309 *d-- = *p++;
2310 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002311 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312 }
2313 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002314 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002316
2317 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318 }
Tim Peters9905b942003-03-20 20:53:32 +00002319}
2320
2321double
2322_PyFloat_Unpack8(const unsigned char *p, int le)
2323{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002324 if (double_format == unknown_format) {
2325 unsigned char sign;
2326 int e;
2327 unsigned int fhi, flo;
2328 double x;
2329 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002330
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002331 if (le) {
2332 p += 7;
2333 incr = -1;
2334 }
2335
2336 /* First byte */
2337 sign = (*p >> 7) & 1;
2338 e = (*p & 0x7F) << 4;
2339
2340 p += incr;
2341
2342 /* Second byte */
2343 e |= (*p >> 4) & 0xF;
2344 fhi = (*p & 0xF) << 24;
2345 p += incr;
2346
2347 if (e == 2047) {
2348 PyErr_SetString(
2349 PyExc_ValueError,
2350 "can't unpack IEEE 754 special value "
2351 "on non-IEEE platform");
2352 return -1.0;
2353 }
2354
2355 /* Third byte */
2356 fhi |= *p << 16;
2357 p += incr;
2358
2359 /* Fourth byte */
2360 fhi |= *p << 8;
2361 p += incr;
2362
2363 /* Fifth byte */
2364 fhi |= *p;
2365 p += incr;
2366
2367 /* Sixth byte */
2368 flo = *p << 16;
2369 p += incr;
2370
2371 /* Seventh byte */
2372 flo |= *p << 8;
2373 p += incr;
2374
2375 /* Eighth byte */
2376 flo |= *p;
2377
2378 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2379 x /= 268435456.0; /* 2**28 */
2380
2381 if (e == 0)
2382 e = -1022;
2383 else {
2384 x += 1.0;
2385 e -= 1023;
2386 }
2387 x = ldexp(x, e);
2388
2389 if (sign)
2390 x = -x;
2391
2392 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002393 }
Tim Peters9905b942003-03-20 20:53:32 +00002394 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002395 double x;
2396
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002397 if ((double_format == ieee_little_endian_format && !le)
2398 || (double_format == ieee_big_endian_format && le)) {
2399 char buf[8];
2400 char *d = &buf[7];
2401 int i;
2402
2403 for (i = 0; i < 8; i++) {
2404 *d-- = *p++;
2405 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002406 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002407 }
2408 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002409 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002410 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002411
2412 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002413 }
Tim Peters9905b942003-03-20 20:53:32 +00002414}