blob: 09894152082ce6855c0848ba59e33b95fecf7b26 [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"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Eric Smith8c663262007-08-25 02:26:07 +00009#include "formatter_unicode.h"
10
Guido van Rossum3f5da241990-12-20 15:06:42 +000011#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000012#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Jack Janseneddc1442003-11-20 01:44:59 +000014#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000015extern double fmod(double, double);
16extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000017#endif
18
Guido van Rossum93ad0df1997-05-13 21:00:42 +000019/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000020#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000021#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000022#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000023
Guido van Rossum3fce8831999-03-12 19:43:17 +000024struct _floatblock {
25 struct _floatblock *next;
26 PyFloatObject objects[N_FLOATOBJECTS];
27};
28
29typedef struct _floatblock PyFloatBlock;
30
31static PyFloatBlock *block_list = NULL;
32static PyFloatObject *free_list = NULL;
33
Guido van Rossum93ad0df1997-05-13 21:00:42 +000034static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000035fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000036{
37 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000038 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
39 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000041 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000042 ((PyFloatBlock *)p)->next = block_list;
43 block_list = (PyFloatBlock *)p;
44 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 q = p + N_FLOATOBJECTS;
46 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000047 Py_TYPE(q) = (struct _typeobject *)(q-1);
48 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 return p + N_FLOATOBJECTS - 1;
50}
51
Christian Heimes93852662007-12-01 12:22:32 +000052double
53PyFloat_GetMax(void)
54{
55 return DBL_MAX;
56}
57
58double
59PyFloat_GetMin(void)
60{
61 return DBL_MIN;
62}
63
64PyObject *
65PyFloat_GetInfo(void)
66{
67 PyObject *d, *tmp;
68
69#define SET_FLOAT_CONST(d, key, const) \
70 tmp = PyFloat_FromDouble(const); \
71 if (tmp == NULL) return NULL; \
72 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
73 Py_DECREF(tmp)
74#define SET_INT_CONST(d, key, const) \
Christian Heimes217cfd12007-12-02 14:31:20 +000075 tmp = PyLong_FromLong(const); \
Christian Heimes93852662007-12-01 12:22:32 +000076 if (tmp == NULL) return NULL; \
77 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
78 Py_DECREF(tmp)
79
80 d = PyDict_New();
81
82 SET_FLOAT_CONST(d, "max", DBL_MAX);
83 SET_INT_CONST(d, "max_exp", DBL_MAX_EXP);
84 SET_INT_CONST(d, "max_10_exp", DBL_MAX_10_EXP);
85 SET_FLOAT_CONST(d, "min", DBL_MIN);
86 SET_INT_CONST(d, "min_exp", DBL_MIN_EXP);
87 SET_INT_CONST(d, "min_10_exp", DBL_MIN_10_EXP);
88 SET_INT_CONST(d, "dig", DBL_DIG);
89 SET_INT_CONST(d, "mant_dig", DBL_MANT_DIG);
90 SET_FLOAT_CONST(d, "epsilon", DBL_EPSILON);
91 SET_INT_CONST(d, "radix", FLT_RADIX);
92 SET_INT_CONST(d, "rounds", FLT_ROUNDS);
93
94 return d;
95}
96
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000101 register PyFloatObject *op;
102 if (free_list == NULL) {
103 if ((free_list = fill_free_list()) == NULL)
104 return NULL;
105 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000106 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000107 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000108 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000109 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000110 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000112}
113
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000114PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000115PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000116{
Christian Heimes99170a52007-12-19 02:07:34 +0000117 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000118 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000119 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000120 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000121 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000122 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000123
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000124 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000125 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
126 if (s_buffer == NULL)
127 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000128 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000129 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000130 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000131 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000132 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000133 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000134 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000135 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000136 else if (PyObject_AsCharBuffer(v, &s, &len)) {
137 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000138 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000139 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000140 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000141
Guido van Rossum4c08d552000-03-10 22:55:18 +0000142 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000143 while (*s && isspace(Py_CHARMASK(*s)))
144 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000145 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000146 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000147 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000148 }
Christian Heimes99170a52007-12-19 02:07:34 +0000149 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000150 /* We don't care about overflow or underflow. If the platform supports
151 * them, infinities and signed zeroes (on underflow) are fine.
152 * However, strtod can return 0 for denormalized numbers, where atof
153 * does not. So (alas!) we special-case a zero result. Note that
154 * whether strtod sets errno on underflow is not defined, so we can't
155 * key off errno.
156 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000157 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000158 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000159 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000161 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000162 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000163 if (end > last)
164 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000165 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000166 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000167 char *p = (char*)sp;
168 int sign = 1;
169
170 if (*p == '-') {
171 sign = -1;
172 p++;
173 }
174 if (*p == '+') {
175 p++;
176 }
177 if (PyOS_strnicmp(p, "inf", 4) == 0) {
178 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
179 }
180#ifdef Py_NAN
181 if(PyOS_strnicmp(p, "nan", 4) == 0) {
182 return PyFloat_FromDouble(Py_NAN);
183 }
184#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000185 PyOS_snprintf(buffer, sizeof(buffer),
186 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000187 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000188 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000189 }
190 /* Since end != s, the platform made *some* kind of sense out
191 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 while (*end && isspace(Py_CHARMASK(*end)))
193 end++;
194 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000195 PyOS_snprintf(buffer, sizeof(buffer),
196 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000197 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000198 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000199 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000200 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000201 PyErr_SetString(PyExc_ValueError,
202 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000203 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000204 }
Tim Petersef14d732000-09-23 03:39:17 +0000205 if (x == 0.0) {
206 /* See above -- may have been strtod being anal
207 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000208 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000209 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000210 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000211 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000212 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000213 result = PyFloat_FromDouble(x);
214 error:
215 if (s_buffer)
216 PyMem_FREE(s_buffer);
217 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218}
219
Guido van Rossum234f9421993-06-17 12:35:49 +0000220static void
Fred Drakefd99de62000-07-09 05:02:18 +0000221float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000222{
Guido van Rossum9475a232001-10-05 20:51:39 +0000223 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000224 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000225 free_list = op;
226 }
227 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000228 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000229}
230
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231double
Fred Drakefd99de62000-07-09 05:02:18 +0000232PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 PyNumberMethods *nb;
235 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000236 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000237
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 if (op && PyFloat_Check(op))
239 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000240
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000241 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243 return -1;
244 }
Tim Petersd2364e82001-11-01 20:09:42 +0000245
Christian Heimes90aa7642007-12-19 02:45:37 +0000246 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000247 PyErr_SetString(PyExc_TypeError, "a float is required");
248 return -1;
249 }
250
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000251 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000252 if (fo == NULL)
253 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254 if (!PyFloat_Check(fo)) {
255 PyErr_SetString(PyExc_TypeError,
256 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257 return -1;
258 }
Tim Petersd2364e82001-11-01 20:09:42 +0000259
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000260 val = PyFloat_AS_DOUBLE(fo);
261 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000262
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264}
265
266/* Methods */
267
Tim Peters97019e42001-11-28 22:43:45 +0000268static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000269format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270{
271 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000272 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000273 int i;
274
275 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276 We want float numbers to be recognizable as such,
277 i.e., they should contain a decimal point or an exponent.
278 However, %g may print the number as an integer;
279 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000280
Martin v. Löwis737ea822004-06-08 18:52:54 +0000281 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000282 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283 cp = buf;
284 if (*cp == '-')
285 cp++;
286 for (; *cp != '\0'; cp++) {
287 /* Any non-digit means it's not an integer;
288 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000289 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290 break;
291 }
292 if (*cp == '\0') {
293 *cp++ = '.';
294 *cp++ = '0';
295 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000296 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000297 }
Christian Heimes99170a52007-12-19 02:07:34 +0000298 /* Checking the next three chars should be more than enough to
299 * detect inf or nan, even on Windows. We check for inf or nan
300 * at last because they are rare cases.
301 */
302 for (i=0; *cp != '\0' && i<3; cp++, i++) {
303 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
304 continue;
305 /* found something that is neither a digit nor point
306 * it might be a NaN or INF
307 */
308#ifdef Py_NAN
309 if (Py_IS_NAN(ob_fval)) {
310 strcpy(buf, "nan");
311 }
312 else
313#endif
314 if (Py_IS_INFINITY(ob_fval)) {
315 cp = buf;
316 if (*cp == '-')
317 cp++;
318 strcpy(cp, "inf");
319 }
320 break;
321 }
322
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323}
324
Neal Norwitz545686b2006-12-28 04:45:06 +0000325static void
326format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000327{
Neal Norwitz545686b2006-12-28 04:45:06 +0000328 assert(PyFloat_Check(v));
329 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000330}
331
Christian Heimesb76922a2007-12-11 01:06:40 +0000332#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000333/* The following function is based on Tcl_PrintDouble,
334 * from tclUtil.c.
335 */
336
337#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
338#define is_nan(d) ((d) != (d))
339
340static void
341format_double_repr(char *dst, double value)
342{
343 char *p, c;
344 int exp;
345 int signum;
346 char buffer[30];
347
348 /*
349 * Handle NaN.
350 */
351
352 if (is_nan(value)) {
353 strcpy(dst, "nan");
354 return;
355 }
356
357 /*
358 * Handle infinities.
359 */
360
361 if (is_infinite(value)) {
362 if (value < 0) {
363 strcpy(dst, "-inf");
364 } else {
365 strcpy(dst, "inf");
366 }
367 return;
368 }
369
370 /*
371 * Ordinary (normal and denormal) values.
372 */
373
374 exp = _PyFloat_Digits(buffer, value, &signum)+1;
375 if (signum) {
376 *dst++ = '-';
377 }
378 p = buffer;
379 if (exp < -3 || exp > 17) {
380 /*
381 * E format for numbers < 1e-3 or >= 1e17.
382 */
383
384 *dst++ = *p++;
385 c = *p;
386 if (c != '\0') {
387 *dst++ = '.';
388 while (c != '\0') {
389 *dst++ = c;
390 c = *++p;
391 }
392 }
393 sprintf(dst, "e%+d", exp-1);
394 } else {
395 /*
396 * F format for others.
397 */
398
399 if (exp <= 0) {
400 *dst++ = '0';
401 }
402 c = *p;
403 while (exp-- > 0) {
404 if (c != '\0') {
405 *dst++ = c;
406 c = *++p;
407 } else {
408 *dst++ = '0';
409 }
410 }
411 *dst++ = '.';
412 if (c == '\0') {
413 *dst++ = '0';
414 } else {
415 while (++exp < 0) {
416 *dst++ = '0';
417 }
418 while (c != '\0') {
419 *dst++ = c;
420 c = *++p;
421 }
422 }
423 *dst++ = '\0';
424 }
425}
426
427static void
428format_float_repr(char *buf, PyFloatObject *v)
429{
430 assert(PyFloat_Check(v));
431 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
432}
433
Christian Heimesb76922a2007-12-11 01:06:40 +0000434#endif /* Py_BROKEN_REPR */
435
Neil Schemenauer32117e52001-01-04 01:44:34 +0000436/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000437 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000438 set to NULL, and the function invoking this macro returns NULL. If
439 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
440 stored in obj, and returned from the function invoking this macro.
441*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000442#define CONVERT_TO_DOUBLE(obj, dbl) \
443 if (PyFloat_Check(obj)) \
444 dbl = PyFloat_AS_DOUBLE(obj); \
445 else if (convert_to_double(&(obj), &(dbl)) < 0) \
446 return obj;
447
448static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000449convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000450{
451 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000452
Guido van Rossumddefaf32007-01-14 03:31:43 +0000453 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000454 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000455 if (*dbl == -1.0 && PyErr_Occurred()) {
456 *v = NULL;
457 return -1;
458 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000459 }
460 else {
461 Py_INCREF(Py_NotImplemented);
462 *v = Py_NotImplemented;
463 return -1;
464 }
465 return 0;
466}
467
Guido van Rossum57072eb1999-12-23 19:00:28 +0000468/* Precisions used by repr() and str(), respectively.
469
470 The repr() precision (17 significant decimal digits) is the minimal number
471 that is guaranteed to have enough precision so that if the number is read
472 back in the exact same binary value is recreated. This is true for IEEE
473 floating point by design, and also happens to work for all other modern
474 hardware.
475
476 The str() precision is chosen so that in most cases, the rounding noise
477 created by various operations is suppressed, while giving plenty of
478 precision for practical use.
479
480*/
481
482#define PREC_REPR 17
483#define PREC_STR 12
484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000486float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487{
Christian Heimesb76922a2007-12-11 01:06:40 +0000488#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000489 char buf[30];
490 format_float_repr(buf, v);
Christian Heimesb76922a2007-12-11 01:06:40 +0000491#else
492 char buf[100];
493 format_float(buf, sizeof(buf), v, PREC_REPR);
494#endif
495
Walter Dörwald1ab83302007-05-18 17:15:44 +0000496 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000497}
498
499static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000500float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000501{
502 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000503 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000504 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505}
506
Tim Peters307fa782004-09-23 08:06:40 +0000507/* Comparison is pretty much a nightmare. When comparing float to float,
508 * we do it as straightforwardly (and long-windedly) as conceivable, so
509 * that, e.g., Python x == y delivers the same result as the platform
510 * C x == y when x and/or y is a NaN.
511 * When mixing float with an integer type, there's no good *uniform* approach.
512 * Converting the double to an integer obviously doesn't work, since we
513 * may lose info from fractional bits. Converting the integer to a double
514 * also has two failure modes: (1) a long int may trigger overflow (too
515 * large to fit in the dynamic range of a C double); (2) even a C long may have
516 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
517 * 63 bits of precision, but a C double probably has only 53), and then
518 * we can falsely claim equality when low-order integer bits are lost by
519 * coercion to double. So this part is painful too.
520 */
521
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522static PyObject*
523float_richcompare(PyObject *v, PyObject *w, int op)
524{
525 double i, j;
526 int r = 0;
527
Tim Peters307fa782004-09-23 08:06:40 +0000528 assert(PyFloat_Check(v));
529 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000530
Tim Peters307fa782004-09-23 08:06:40 +0000531 /* Switch on the type of w. Set i and j to doubles to be compared,
532 * and op to the richcomp to use.
533 */
534 if (PyFloat_Check(w))
535 j = PyFloat_AS_DOUBLE(w);
536
Thomas Wouters477c8d52006-05-27 19:21:47 +0000537 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000538 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000539 /* If i is an infinity, its magnitude exceeds any
540 * finite integer, so it doesn't matter which int we
541 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000542 */
543 j = 0.0;
544 else
545 goto Unimplemented;
546 }
547
Tim Peters307fa782004-09-23 08:06:40 +0000548 else if (PyLong_Check(w)) {
549 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
550 int wsign = _PyLong_Sign(w);
551 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000552 int exponent;
553
554 if (vsign != wsign) {
555 /* Magnitudes are irrelevant -- the signs alone
556 * determine the outcome.
557 */
558 i = (double)vsign;
559 j = (double)wsign;
560 goto Compare;
561 }
562 /* The signs are the same. */
563 /* Convert w to a double if it fits. In particular, 0 fits. */
564 nbits = _PyLong_NumBits(w);
565 if (nbits == (size_t)-1 && PyErr_Occurred()) {
566 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000567 * to hold the # of bits. Replace with little doubles
568 * that give the same outcome -- w is so large that
569 * its magnitude must exceed the magnitude of any
570 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000571 */
572 PyErr_Clear();
573 i = (double)vsign;
574 assert(wsign != 0);
575 j = wsign * 2.0;
576 goto Compare;
577 }
578 if (nbits <= 48) {
579 j = PyLong_AsDouble(w);
580 /* It's impossible that <= 48 bits overflowed. */
581 assert(j != -1.0 || ! PyErr_Occurred());
582 goto Compare;
583 }
584 assert(wsign != 0); /* else nbits was 0 */
585 assert(vsign != 0); /* if vsign were 0, then since wsign is
586 * not 0, we would have taken the
587 * vsign != wsign branch at the start */
588 /* We want to work with non-negative numbers. */
589 if (vsign < 0) {
590 /* "Multiply both sides" by -1; this also swaps the
591 * comparator.
592 */
593 i = -i;
594 op = _Py_SwappedOp[op];
595 }
596 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000597 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000598 /* exponent is the # of bits in v before the radix point;
599 * we know that nbits (the # of bits in w) > 48 at this point
600 */
601 if (exponent < 0 || (size_t)exponent < nbits) {
602 i = 1.0;
603 j = 2.0;
604 goto Compare;
605 }
606 if ((size_t)exponent > nbits) {
607 i = 2.0;
608 j = 1.0;
609 goto Compare;
610 }
611 /* v and w have the same number of bits before the radix
612 * point. Construct two longs that have the same comparison
613 * outcome.
614 */
615 {
616 double fracpart;
617 double intpart;
618 PyObject *result = NULL;
619 PyObject *one = NULL;
620 PyObject *vv = NULL;
621 PyObject *ww = w;
622
623 if (wsign < 0) {
624 ww = PyNumber_Negative(w);
625 if (ww == NULL)
626 goto Error;
627 }
628 else
629 Py_INCREF(ww);
630
631 fracpart = modf(i, &intpart);
632 vv = PyLong_FromDouble(intpart);
633 if (vv == NULL)
634 goto Error;
635
636 if (fracpart != 0.0) {
637 /* Shift left, and or a 1 bit into vv
638 * to represent the lost fraction.
639 */
640 PyObject *temp;
641
Christian Heimes217cfd12007-12-02 14:31:20 +0000642 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000643 if (one == NULL)
644 goto Error;
645
646 temp = PyNumber_Lshift(ww, one);
647 if (temp == NULL)
648 goto Error;
649 Py_DECREF(ww);
650 ww = temp;
651
652 temp = PyNumber_Lshift(vv, one);
653 if (temp == NULL)
654 goto Error;
655 Py_DECREF(vv);
656 vv = temp;
657
658 temp = PyNumber_Or(vv, one);
659 if (temp == NULL)
660 goto Error;
661 Py_DECREF(vv);
662 vv = temp;
663 }
664
665 r = PyObject_RichCompareBool(vv, ww, op);
666 if (r < 0)
667 goto Error;
668 result = PyBool_FromLong(r);
669 Error:
670 Py_XDECREF(vv);
671 Py_XDECREF(ww);
672 Py_XDECREF(one);
673 return result;
674 }
675 } /* else if (PyLong_Check(w)) */
676
677 else /* w isn't float, int, or long */
678 goto Unimplemented;
679
680 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000681 PyFPE_START_PROTECT("richcompare", return NULL)
682 switch (op) {
683 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000684 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000685 break;
686 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000687 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000688 break;
689 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000690 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000691 break;
692 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000693 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000694 break;
695 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000696 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000697 break;
698 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000699 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000700 break;
701 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000702 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000703 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000704
705 Unimplemented:
706 Py_INCREF(Py_NotImplemented);
707 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000708}
709
Guido van Rossum9bfef441993-03-29 10:43:31 +0000710static long
Fred Drakefd99de62000-07-09 05:02:18 +0000711float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000712{
Tim Peters39dce292000-08-15 03:34:48 +0000713 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000714}
715
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000717float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000719 double a,b;
720 CONVERT_TO_DOUBLE(v, a);
721 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000722 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000723 a = a + b;
724 PyFPE_END_PROTECT(a)
725 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726}
727
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000729float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000731 double a,b;
732 CONVERT_TO_DOUBLE(v, a);
733 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000734 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000735 a = a - b;
736 PyFPE_END_PROTECT(a)
737 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000738}
739
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000741float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000742{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000743 double a,b;
744 CONVERT_TO_DOUBLE(v, a);
745 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000746 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000747 a = a * b;
748 PyFPE_END_PROTECT(a)
749 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000750}
751
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000753float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000754{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000755 double a,b;
756 CONVERT_TO_DOUBLE(v, a);
757 CONVERT_TO_DOUBLE(w, b);
758 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000759 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760 return NULL;
761 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000762 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000763 a = a / b;
764 PyFPE_END_PROTECT(a)
765 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766}
767
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000768static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000769float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000771 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000772 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000773 CONVERT_TO_DOUBLE(v, vx);
774 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777 return NULL;
778 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000779 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000780 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000781 /* note: checking mod*wx < 0 is incorrect -- underflows to
782 0 if wx < sqrt(smallest nonzero double) */
783 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000784 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000785 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000786 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000787 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000788}
789
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000790static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000791float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000792{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000793 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000794 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000795 CONVERT_TO_DOUBLE(v, vx);
796 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000797 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000798 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000799 return NULL;
800 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000801 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000802 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000803 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000804 exact multiple of wx. But this is fp arithmetic, and fp
805 vx - mod is an approximation; the result is that div may
806 not be an exact integral value after the division, although
807 it will always be very close to one.
808 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000809 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000810 if (mod) {
811 /* ensure the remainder has the same sign as the denominator */
812 if ((wx < 0) != (mod < 0)) {
813 mod += wx;
814 div -= 1.0;
815 }
816 }
817 else {
818 /* the remainder is zero, and in the presence of signed zeroes
819 fmod returns different results across platforms; ensure
820 it has the same sign as the denominator; we'd like to do
821 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000822 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000823 if (wx < 0.0)
824 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000825 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000826 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000827 if (div) {
828 floordiv = floor(div);
829 if (div - floordiv > 0.5)
830 floordiv += 1.0;
831 }
832 else {
833 /* div is zero - get the same sign as the true quotient */
834 div *= div; /* hide "div = +0" from optimizers */
835 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
836 }
837 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000838 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000839}
840
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000841static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000842float_floor_div(PyObject *v, PyObject *w)
843{
844 PyObject *t, *r;
845
846 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000847 if (t == NULL || t == Py_NotImplemented)
848 return t;
849 assert(PyTuple_CheckExact(t));
850 r = PyTuple_GET_ITEM(t, 0);
851 Py_INCREF(r);
852 Py_DECREF(t);
853 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000854}
855
856static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000857float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000858{
859 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000860
861 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000862 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000863 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000864 return NULL;
865 }
866
Neil Schemenauer32117e52001-01-04 01:44:34 +0000867 CONVERT_TO_DOUBLE(v, iv);
868 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000869
870 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000871 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000872 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000873 }
Tim Peters96685bf2001-08-23 22:31:37 +0000874 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000875 if (iw < 0.0) {
876 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000877 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000878 return NULL;
879 }
880 return PyFloat_FromDouble(0.0);
881 }
Tim Peterse87568d2003-05-24 20:18:24 +0000882 if (iv < 0.0) {
883 /* Whether this is an error is a mess, and bumps into libm
884 * bugs so we have to figure it out ourselves.
885 */
886 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000887 /* Negative numbers raised to fractional powers
888 * become complex.
889 */
890 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000891 }
892 /* iw is an exact integer, albeit perhaps a very large one.
893 * -1 raised to an exact integer should never be exceptional.
894 * Alas, some libms (chiefly glibc as of early 2003) return
895 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
896 * happen to be representable in a *C* integer. That's a
897 * bug; we let that slide in math.pow() (which currently
898 * reflects all platform accidents), but not for Python's **.
899 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000900 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000901 /* Return 1 if iw is even, -1 if iw is odd; there's
902 * no guarantee that any C integral type is big
903 * enough to hold iw, so we have to check this
904 * indirectly.
905 */
906 ix = floor(iw * 0.5) * 2.0;
907 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
908 }
909 /* Else iv != -1.0, and overflow or underflow are possible.
910 * Unless we're to write pow() ourselves, we have to trust
911 * the platform to do this correctly.
912 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000913 }
Tim Peters96685bf2001-08-23 22:31:37 +0000914 errno = 0;
915 PyFPE_START_PROTECT("pow", return NULL)
916 ix = pow(iv, iw);
917 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000918 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000919 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000920 /* We don't expect any errno value other than ERANGE, but
921 * the range of libm bugs appears unbounded.
922 */
923 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
924 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000925 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000926 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000927 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000928}
929
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000930static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000931float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000932{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000933 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000934}
935
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000936static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000937float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000938{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000939 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000940}
941
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000942static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000943float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000944{
945 return v->ob_fval != 0.0;
946}
947
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000948static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000949float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000950{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000952 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000953
954 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000955 /* Try to get out cheap if this fits in a Python int. The attempt
956 * to cast to long must be protected, as C doesn't define what
957 * happens if the double is too big to fit in a long. Some rare
958 * systems raise an exception then (RISCOS was mentioned as one,
959 * and someone using a non-default option on Sun also bumped into
960 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
961 * still be vulnerable: if a long has more bits of precision than
962 * a double, casting MIN/MAX to double may yield an approximation,
963 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
964 * yield true from the C expression wholepart<=LONG_MAX, despite
965 * that wholepart is actually greater than LONG_MAX.
966 */
967 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
968 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000969 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000970 }
971 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000972}
973
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000974static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000975float_round(PyObject *v, PyObject *args)
976{
977#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
978 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000979 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000980 double flr, cil;
981 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000982 int ndigits = UNDEF_NDIGITS;
983
984 if (!PyArg_ParseTuple(args, "|i", &ndigits))
985 return NULL;
986
987 x = PyFloat_AsDouble(v);
988
989 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000990 f = pow(10.0, ndigits);
991 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000992 }
993
994 flr = floor(x);
995 cil = ceil(x);
996
997 if (x-flr > 0.5)
998 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000999 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001000 rounded = fmod(flr, 2) == 0 ? flr : cil;
1001 else
1002 rounded = flr;
1003
1004 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001005 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001006 return PyFloat_FromDouble(rounded);
1007 }
1008
1009 return PyLong_FromDouble(rounded);
1010#undef UNDEF_NDIGITS
1011}
1012
1013static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001014float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001015{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001016 if (PyFloat_CheckExact(v))
1017 Py_INCREF(v);
1018 else
1019 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001020 return v;
1021}
1022
1023
Jeremy Hylton938ace62002-07-17 16:30:39 +00001024static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001025float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1026
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027static PyObject *
1028float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1029{
1030 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001031 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032
Guido van Rossumbef14172001-08-29 15:47:46 +00001033 if (type != &PyFloat_Type)
1034 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1036 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001037 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001038 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 return PyNumber_Float(x);
1040}
1041
Guido van Rossumbef14172001-08-29 15:47:46 +00001042/* Wimpy, slow approach to tp_new calls for subtypes of float:
1043 first create a regular float from whatever arguments we got,
1044 then allocate a subtype instance and initialize its ob_fval
1045 from the regular float. The regular float is then thrown away.
1046*/
1047static PyObject *
1048float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1049{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001050 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001051
1052 assert(PyType_IsSubtype(type, &PyFloat_Type));
1053 tmp = float_new(&PyFloat_Type, args, kwds);
1054 if (tmp == NULL)
1055 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001056 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001057 newobj = type->tp_alloc(type, 0);
1058 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001059 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001060 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001061 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001062 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001063 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001064 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001065}
1066
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001067static PyObject *
1068float_getnewargs(PyFloatObject *v)
1069{
1070 return Py_BuildValue("(d)", v->ob_fval);
1071}
1072
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001073/* this is for the benefit of the pack/unpack routines below */
1074
1075typedef enum {
1076 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1077} float_format_type;
1078
1079static float_format_type double_format, float_format;
1080static float_format_type detected_double_format, detected_float_format;
1081
1082static PyObject *
1083float_getformat(PyTypeObject *v, PyObject* arg)
1084{
1085 char* s;
1086 float_format_type r;
1087
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001088 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001089 PyErr_Format(PyExc_TypeError,
1090 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001091 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001092 return NULL;
1093 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001094 s = PyUnicode_AsString(arg);
1095 if (s == NULL)
1096 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001097 if (strcmp(s, "double") == 0) {
1098 r = double_format;
1099 }
1100 else if (strcmp(s, "float") == 0) {
1101 r = float_format;
1102 }
1103 else {
1104 PyErr_SetString(PyExc_ValueError,
1105 "__getformat__() argument 1 must be "
1106 "'double' or 'float'");
1107 return NULL;
1108 }
1109
1110 switch (r) {
1111 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001112 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001113 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001114 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001115 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001116 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001117 default:
1118 Py_FatalError("insane float_format or double_format");
1119 return NULL;
1120 }
1121}
1122
1123PyDoc_STRVAR(float_getformat_doc,
1124"float.__getformat__(typestr) -> string\n"
1125"\n"
1126"You probably don't want to use this function. It exists mainly to be\n"
1127"used in Python's test suite.\n"
1128"\n"
1129"typestr must be 'double' or 'float'. This function returns whichever of\n"
1130"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1131"format of floating point numbers used by the C type named by typestr.");
1132
1133static PyObject *
1134float_setformat(PyTypeObject *v, PyObject* args)
1135{
1136 char* typestr;
1137 char* format;
1138 float_format_type f;
1139 float_format_type detected;
1140 float_format_type *p;
1141
1142 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1143 return NULL;
1144
1145 if (strcmp(typestr, "double") == 0) {
1146 p = &double_format;
1147 detected = detected_double_format;
1148 }
1149 else if (strcmp(typestr, "float") == 0) {
1150 p = &float_format;
1151 detected = detected_float_format;
1152 }
1153 else {
1154 PyErr_SetString(PyExc_ValueError,
1155 "__setformat__() argument 1 must "
1156 "be 'double' or 'float'");
1157 return NULL;
1158 }
1159
1160 if (strcmp(format, "unknown") == 0) {
1161 f = unknown_format;
1162 }
1163 else if (strcmp(format, "IEEE, little-endian") == 0) {
1164 f = ieee_little_endian_format;
1165 }
1166 else if (strcmp(format, "IEEE, big-endian") == 0) {
1167 f = ieee_big_endian_format;
1168 }
1169 else {
1170 PyErr_SetString(PyExc_ValueError,
1171 "__setformat__() argument 2 must be "
1172 "'unknown', 'IEEE, little-endian' or "
1173 "'IEEE, big-endian'");
1174 return NULL;
1175
1176 }
1177
1178 if (f != unknown_format && f != detected) {
1179 PyErr_Format(PyExc_ValueError,
1180 "can only set %s format to 'unknown' or the "
1181 "detected platform value", typestr);
1182 return NULL;
1183 }
1184
1185 *p = f;
1186 Py_RETURN_NONE;
1187}
1188
1189PyDoc_STRVAR(float_setformat_doc,
1190"float.__setformat__(typestr, fmt) -> None\n"
1191"\n"
1192"You probably don't want to use this function. It exists mainly to be\n"
1193"used in Python's test suite.\n"
1194"\n"
1195"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1196"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1197"one of the latter two if it appears to match the underlying C reality.\n"
1198"\n"
1199"Overrides the automatic determination of C-level floating point type.\n"
1200"This affects how floats are converted to and from binary strings.");
1201
Guido van Rossumb43daf72007-08-01 18:08:08 +00001202static PyObject *
1203float_getzero(PyObject *v, void *closure)
1204{
1205 return PyFloat_FromDouble(0.0);
1206}
1207
Eric Smith8c663262007-08-25 02:26:07 +00001208static PyObject *
1209float__format__(PyObject *self, PyObject *args)
1210{
1211 /* when back porting this to 2.6, check type of the format_spec
1212 and call either unicode_long__format__ or
1213 string_long__format__ */
1214 return unicode_float__format__(self, args);
1215}
1216
1217PyDoc_STRVAR(float__format__doc,
1218"float.__format__(format_spec) -> string\n"
1219"\n"
1220"Formats the float according to format_spec.");
1221
1222
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001223static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001224 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1225 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001226 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1227 "Returns the Integral closest to x between 0 and x."},
1228 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1229 "Returns the Integral closest to x, rounding half toward even.\n"
1230 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001231 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001232 {"__getformat__", (PyCFunction)float_getformat,
1233 METH_O|METH_CLASS, float_getformat_doc},
1234 {"__setformat__", (PyCFunction)float_setformat,
1235 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001236 {"__format__", (PyCFunction)float__format__,
1237 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001238 {NULL, NULL} /* sentinel */
1239};
1240
Guido van Rossumb43daf72007-08-01 18:08:08 +00001241static PyGetSetDef float_getset[] = {
1242 {"real",
1243 (getter)float_float, (setter)NULL,
1244 "the real part of a complex number",
1245 NULL},
1246 {"imag",
1247 (getter)float_getzero, (setter)NULL,
1248 "the imaginary part of a complex number",
1249 NULL},
1250 {NULL} /* Sentinel */
1251};
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254"float(x) -> floating point number\n\
1255\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257
1258
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001259static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001260 float_add, /*nb_add*/
1261 float_sub, /*nb_subtract*/
1262 float_mul, /*nb_multiply*/
1263 float_rem, /*nb_remainder*/
1264 float_divmod, /*nb_divmod*/
1265 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001266 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001267 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001268 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001269 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001270 0, /*nb_invert*/
1271 0, /*nb_lshift*/
1272 0, /*nb_rshift*/
1273 0, /*nb_and*/
1274 0, /*nb_xor*/
1275 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001276 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001277 float_trunc, /*nb_int*/
1278 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001279 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001280 0, /* nb_oct */
1281 0, /* nb_hex */
1282 0, /* nb_inplace_add */
1283 0, /* nb_inplace_subtract */
1284 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001285 0, /* nb_inplace_remainder */
1286 0, /* nb_inplace_power */
1287 0, /* nb_inplace_lshift */
1288 0, /* nb_inplace_rshift */
1289 0, /* nb_inplace_and */
1290 0, /* nb_inplace_xor */
1291 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001292 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001293 float_div, /* nb_true_divide */
1294 0, /* nb_inplace_floor_divide */
1295 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001296};
1297
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001298PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001299 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001300 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001301 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001302 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001304 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 0, /* tp_getattr */
1306 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001307 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 (reprfunc)float_repr, /* tp_repr */
1309 &float_as_number, /* tp_as_number */
1310 0, /* tp_as_sequence */
1311 0, /* tp_as_mapping */
1312 (hashfunc)float_hash, /* tp_hash */
1313 0, /* tp_call */
1314 (reprfunc)float_str, /* tp_str */
1315 PyObject_GenericGetAttr, /* tp_getattro */
1316 0, /* tp_setattro */
1317 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001318 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 float_doc, /* tp_doc */
1320 0, /* tp_traverse */
1321 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 0, /* tp_weaklistoffset */
1324 0, /* tp_iter */
1325 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001326 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001328 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 0, /* tp_base */
1330 0, /* tp_dict */
1331 0, /* tp_descr_get */
1332 0, /* tp_descr_set */
1333 0, /* tp_dictoffset */
1334 0, /* tp_init */
1335 0, /* tp_alloc */
1336 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001337};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001338
1339void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001340_PyFloat_Init(void)
1341{
1342 /* We attempt to determine if this machine is using IEEE
1343 floating point formats by peering at the bits of some
1344 carefully chosen values. If it looks like we are on an
1345 IEEE platform, the float packing/unpacking routines can
1346 just copy bits, if not they resort to arithmetic & shifts
1347 and masks. The shifts & masks approach works on all finite
1348 values, but what happens to infinities, NaNs and signed
1349 zeroes on packing is an accident, and attempting to unpack
1350 a NaN or an infinity will raise an exception.
1351
1352 Note that if we're on some whacked-out platform which uses
1353 IEEE formats but isn't strictly little-endian or big-
1354 endian, we will fall back to the portable shifts & masks
1355 method. */
1356
1357#if SIZEOF_DOUBLE == 8
1358 {
1359 double x = 9006104071832581.0;
1360 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1361 detected_double_format = ieee_big_endian_format;
1362 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1363 detected_double_format = ieee_little_endian_format;
1364 else
1365 detected_double_format = unknown_format;
1366 }
1367#else
1368 detected_double_format = unknown_format;
1369#endif
1370
1371#if SIZEOF_FLOAT == 4
1372 {
1373 float y = 16711938.0;
1374 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1375 detected_float_format = ieee_big_endian_format;
1376 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1377 detected_float_format = ieee_little_endian_format;
1378 else
1379 detected_float_format = unknown_format;
1380 }
1381#else
1382 detected_float_format = unknown_format;
1383#endif
1384
1385 double_format = detected_double_format;
1386 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001387
1388#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001389 /* Initialize floating point repr */
1390 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001391#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001392}
1393
1394void
Fred Drakefd99de62000-07-09 05:02:18 +00001395PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001396{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001397 PyFloatObject *p;
1398 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001399 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001400 int bc, bf; /* block count, number of freed blocks */
1401 int frem, fsum; /* remaining unfreed floats per block, total */
1402
1403 bc = 0;
1404 bf = 0;
1405 fsum = 0;
1406 list = block_list;
1407 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001408 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001409 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001410 bc++;
1411 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001412 for (i = 0, p = &list->objects[0];
1413 i < N_FLOATOBJECTS;
1414 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001415 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001416 frem++;
1417 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001418 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001419 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001420 list->next = block_list;
1421 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001422 for (i = 0, p = &list->objects[0];
1423 i < N_FLOATOBJECTS;
1424 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001425 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001426 Py_REFCNT(p) == 0) {
1427 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001428 free_list;
1429 free_list = p;
1430 }
1431 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001432 }
1433 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001434 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001435 bf++;
1436 }
1437 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001438 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001439 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001440 if (!Py_VerboseFlag)
1441 return;
1442 fprintf(stderr, "# cleanup floats");
1443 if (!fsum) {
1444 fprintf(stderr, "\n");
1445 }
1446 else {
1447 fprintf(stderr,
1448 ": %d unfreed float%s in %d out of %d block%s\n",
1449 fsum, fsum == 1 ? "" : "s",
1450 bc - bf, bc, bc == 1 ? "" : "s");
1451 }
1452 if (Py_VerboseFlag > 1) {
1453 list = block_list;
1454 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001455 for (i = 0, p = &list->objects[0];
1456 i < N_FLOATOBJECTS;
1457 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001458 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001459 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001460 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001461 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001462 /* XXX(twouters) cast refcount to
1463 long until %zd is universally
1464 available
1465 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001466 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001467 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001468 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001469 }
1470 }
1471 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001472 }
1473 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001474}
Tim Peters9905b942003-03-20 20:53:32 +00001475
1476/*----------------------------------------------------------------------------
1477 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1478 *
1479 * TODO: On platforms that use the standard IEEE-754 single and double
1480 * formats natively, these routines could simply copy the bytes.
1481 */
1482int
1483_PyFloat_Pack4(double x, unsigned char *p, int le)
1484{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001485 if (float_format == unknown_format) {
1486 unsigned char sign;
1487 int e;
1488 double f;
1489 unsigned int fbits;
1490 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001491
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001492 if (le) {
1493 p += 3;
1494 incr = -1;
1495 }
Tim Peters9905b942003-03-20 20:53:32 +00001496
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001497 if (x < 0) {
1498 sign = 1;
1499 x = -x;
1500 }
1501 else
1502 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001503
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001504 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001505
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001506 /* Normalize f to be in the range [1.0, 2.0) */
1507 if (0.5 <= f && f < 1.0) {
1508 f *= 2.0;
1509 e--;
1510 }
1511 else if (f == 0.0)
1512 e = 0;
1513 else {
1514 PyErr_SetString(PyExc_SystemError,
1515 "frexp() result out of range");
1516 return -1;
1517 }
1518
1519 if (e >= 128)
1520 goto Overflow;
1521 else if (e < -126) {
1522 /* Gradual underflow */
1523 f = ldexp(f, 126 + e);
1524 e = 0;
1525 }
1526 else if (!(e == 0 && f == 0.0)) {
1527 e += 127;
1528 f -= 1.0; /* Get rid of leading 1 */
1529 }
1530
1531 f *= 8388608.0; /* 2**23 */
1532 fbits = (unsigned int)(f + 0.5); /* Round */
1533 assert(fbits <= 8388608);
1534 if (fbits >> 23) {
1535 /* The carry propagated out of a string of 23 1 bits. */
1536 fbits = 0;
1537 ++e;
1538 if (e >= 255)
1539 goto Overflow;
1540 }
1541
1542 /* First byte */
1543 *p = (sign << 7) | (e >> 1);
1544 p += incr;
1545
1546 /* Second byte */
1547 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1548 p += incr;
1549
1550 /* Third byte */
1551 *p = (fbits >> 8) & 0xFF;
1552 p += incr;
1553
1554 /* Fourth byte */
1555 *p = fbits & 0xFF;
1556
1557 /* Done */
1558 return 0;
1559
1560 Overflow:
1561 PyErr_SetString(PyExc_OverflowError,
1562 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001563 return -1;
1564 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001565 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001566 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001567 const char *s = (char*)&y;
1568 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001569
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001570 if ((float_format == ieee_little_endian_format && !le)
1571 || (float_format == ieee_big_endian_format && le)) {
1572 p += 3;
1573 incr = -1;
1574 }
1575
1576 for (i = 0; i < 4; i++) {
1577 *p = *s++;
1578 p += incr;
1579 }
1580 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001581 }
Tim Peters9905b942003-03-20 20:53:32 +00001582}
1583
1584int
1585_PyFloat_Pack8(double x, unsigned char *p, int le)
1586{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001587 if (double_format == unknown_format) {
1588 unsigned char sign;
1589 int e;
1590 double f;
1591 unsigned int fhi, flo;
1592 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001593
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001594 if (le) {
1595 p += 7;
1596 incr = -1;
1597 }
Tim Peters9905b942003-03-20 20:53:32 +00001598
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001599 if (x < 0) {
1600 sign = 1;
1601 x = -x;
1602 }
1603 else
1604 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001605
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001606 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001607
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001608 /* Normalize f to be in the range [1.0, 2.0) */
1609 if (0.5 <= f && f < 1.0) {
1610 f *= 2.0;
1611 e--;
1612 }
1613 else if (f == 0.0)
1614 e = 0;
1615 else {
1616 PyErr_SetString(PyExc_SystemError,
1617 "frexp() result out of range");
1618 return -1;
1619 }
1620
1621 if (e >= 1024)
1622 goto Overflow;
1623 else if (e < -1022) {
1624 /* Gradual underflow */
1625 f = ldexp(f, 1022 + e);
1626 e = 0;
1627 }
1628 else if (!(e == 0 && f == 0.0)) {
1629 e += 1023;
1630 f -= 1.0; /* Get rid of leading 1 */
1631 }
1632
1633 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1634 f *= 268435456.0; /* 2**28 */
1635 fhi = (unsigned int)f; /* Truncate */
1636 assert(fhi < 268435456);
1637
1638 f -= (double)fhi;
1639 f *= 16777216.0; /* 2**24 */
1640 flo = (unsigned int)(f + 0.5); /* Round */
1641 assert(flo <= 16777216);
1642 if (flo >> 24) {
1643 /* The carry propagated out of a string of 24 1 bits. */
1644 flo = 0;
1645 ++fhi;
1646 if (fhi >> 28) {
1647 /* And it also progagated out of the next 28 bits. */
1648 fhi = 0;
1649 ++e;
1650 if (e >= 2047)
1651 goto Overflow;
1652 }
1653 }
1654
1655 /* First byte */
1656 *p = (sign << 7) | (e >> 4);
1657 p += incr;
1658
1659 /* Second byte */
1660 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1661 p += incr;
1662
1663 /* Third byte */
1664 *p = (fhi >> 16) & 0xFF;
1665 p += incr;
1666
1667 /* Fourth byte */
1668 *p = (fhi >> 8) & 0xFF;
1669 p += incr;
1670
1671 /* Fifth byte */
1672 *p = fhi & 0xFF;
1673 p += incr;
1674
1675 /* Sixth byte */
1676 *p = (flo >> 16) & 0xFF;
1677 p += incr;
1678
1679 /* Seventh byte */
1680 *p = (flo >> 8) & 0xFF;
1681 p += incr;
1682
1683 /* Eighth byte */
1684 *p = flo & 0xFF;
1685 p += incr;
1686
1687 /* Done */
1688 return 0;
1689
1690 Overflow:
1691 PyErr_SetString(PyExc_OverflowError,
1692 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001693 return -1;
1694 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001695 else {
1696 const char *s = (char*)&x;
1697 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001698
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001699 if ((double_format == ieee_little_endian_format && !le)
1700 || (double_format == ieee_big_endian_format && le)) {
1701 p += 7;
1702 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001703 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001704
1705 for (i = 0; i < 8; i++) {
1706 *p = *s++;
1707 p += incr;
1708 }
1709 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001710 }
Tim Peters9905b942003-03-20 20:53:32 +00001711}
1712
Neal Norwitz545686b2006-12-28 04:45:06 +00001713/* Should only be used by marshal. */
1714int
1715_PyFloat_Repr(double x, char *p, size_t len)
1716{
1717 format_double(p, len, x, PREC_REPR);
1718 return (int)strlen(p);
1719}
1720
Tim Peters9905b942003-03-20 20:53:32 +00001721double
1722_PyFloat_Unpack4(const unsigned char *p, int le)
1723{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724 if (float_format == unknown_format) {
1725 unsigned char sign;
1726 int e;
1727 unsigned int f;
1728 double x;
1729 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001730
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731 if (le) {
1732 p += 3;
1733 incr = -1;
1734 }
1735
1736 /* First byte */
1737 sign = (*p >> 7) & 1;
1738 e = (*p & 0x7F) << 1;
1739 p += incr;
1740
1741 /* Second byte */
1742 e |= (*p >> 7) & 1;
1743 f = (*p & 0x7F) << 16;
1744 p += incr;
1745
1746 if (e == 255) {
1747 PyErr_SetString(
1748 PyExc_ValueError,
1749 "can't unpack IEEE 754 special value "
1750 "on non-IEEE platform");
1751 return -1;
1752 }
1753
1754 /* Third byte */
1755 f |= *p << 8;
1756 p += incr;
1757
1758 /* Fourth byte */
1759 f |= *p;
1760
1761 x = (double)f / 8388608.0;
1762
1763 /* XXX This sadly ignores Inf/NaN issues */
1764 if (e == 0)
1765 e = -126;
1766 else {
1767 x += 1.0;
1768 e -= 127;
1769 }
1770 x = ldexp(x, e);
1771
1772 if (sign)
1773 x = -x;
1774
1775 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001776 }
Tim Peters9905b942003-03-20 20:53:32 +00001777 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001778 float x;
1779
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001780 if ((float_format == ieee_little_endian_format && !le)
1781 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001782 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001783 char *d = &buf[3];
1784 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001785
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001786 for (i = 0; i < 4; i++) {
1787 *d-- = *p++;
1788 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001789 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001790 }
1791 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001792 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001793 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001794
1795 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001796 }
Tim Peters9905b942003-03-20 20:53:32 +00001797}
1798
1799double
1800_PyFloat_Unpack8(const unsigned char *p, int le)
1801{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001802 if (double_format == unknown_format) {
1803 unsigned char sign;
1804 int e;
1805 unsigned int fhi, flo;
1806 double x;
1807 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001808
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001809 if (le) {
1810 p += 7;
1811 incr = -1;
1812 }
1813
1814 /* First byte */
1815 sign = (*p >> 7) & 1;
1816 e = (*p & 0x7F) << 4;
1817
1818 p += incr;
1819
1820 /* Second byte */
1821 e |= (*p >> 4) & 0xF;
1822 fhi = (*p & 0xF) << 24;
1823 p += incr;
1824
1825 if (e == 2047) {
1826 PyErr_SetString(
1827 PyExc_ValueError,
1828 "can't unpack IEEE 754 special value "
1829 "on non-IEEE platform");
1830 return -1.0;
1831 }
1832
1833 /* Third byte */
1834 fhi |= *p << 16;
1835 p += incr;
1836
1837 /* Fourth byte */
1838 fhi |= *p << 8;
1839 p += incr;
1840
1841 /* Fifth byte */
1842 fhi |= *p;
1843 p += incr;
1844
1845 /* Sixth byte */
1846 flo = *p << 16;
1847 p += incr;
1848
1849 /* Seventh byte */
1850 flo |= *p << 8;
1851 p += incr;
1852
1853 /* Eighth byte */
1854 flo |= *p;
1855
1856 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1857 x /= 268435456.0; /* 2**28 */
1858
1859 if (e == 0)
1860 e = -1022;
1861 else {
1862 x += 1.0;
1863 e -= 1023;
1864 }
1865 x = ldexp(x, e);
1866
1867 if (sign)
1868 x = -x;
1869
1870 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001871 }
Tim Peters9905b942003-03-20 20:53:32 +00001872 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001873 double x;
1874
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001875 if ((double_format == ieee_little_endian_format && !le)
1876 || (double_format == ieee_big_endian_format && le)) {
1877 char buf[8];
1878 char *d = &buf[7];
1879 int i;
1880
1881 for (i = 0; i < 8; i++) {
1882 *d-- = *p++;
1883 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001884 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001885 }
1886 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001887 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001888 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001889
1890 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001891 }
Tim Peters9905b942003-03-20 20:53:32 +00001892}