blob: 48d29d7042c3902c22016ac4a905b30f5016b334 [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)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000117 const char *s, *last, *end;
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 }
Tim Petersef14d732000-09-23 03:39:17 +0000149 /* We don't care about overflow or underflow. If the platform supports
150 * them, infinities and signed zeroes (on underflow) are fine.
151 * However, strtod can return 0 for denormalized numbers, where atof
152 * does not. So (alas!) we special-case a zero result. Note that
153 * whether strtod sets errno on underflow is not defined, so we can't
154 * key off errno.
155 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000156 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000157 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000158 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000161 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162 if (end > last)
163 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000164 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000165 PyOS_snprintf(buffer, sizeof(buffer),
166 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000167 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000169 }
170 /* Since end != s, the platform made *some* kind of sense out
171 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172 while (*end && isspace(Py_CHARMASK(*end)))
173 end++;
174 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000175 PyOS_snprintf(buffer, sizeof(buffer),
176 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000178 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000180 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 PyErr_SetString(PyExc_ValueError,
182 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000183 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184 }
Tim Petersef14d732000-09-23 03:39:17 +0000185 if (x == 0.0) {
186 /* See above -- may have been strtod being anal
187 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000188 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000189 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000190 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000191 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000193 result = PyFloat_FromDouble(x);
194 error:
195 if (s_buffer)
196 PyMem_FREE(s_buffer);
197 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000198}
199
Guido van Rossum234f9421993-06-17 12:35:49 +0000200static void
Fred Drakefd99de62000-07-09 05:02:18 +0000201float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000202{
Guido van Rossum9475a232001-10-05 20:51:39 +0000203 if (PyFloat_CheckExact(op)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000204 Py_Type(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000205 free_list = op;
206 }
207 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000208 Py_Type(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000209}
210
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211double
Fred Drakefd99de62000-07-09 05:02:18 +0000212PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 PyNumberMethods *nb;
215 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000216 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000217
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218 if (op && PyFloat_Check(op))
219 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000220
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000221 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223 return -1;
224 }
Tim Petersd2364e82001-11-01 20:09:42 +0000225
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000226 if ((nb = Py_Type(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000227 PyErr_SetString(PyExc_TypeError, "a float is required");
228 return -1;
229 }
230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232 if (fo == NULL)
233 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (!PyFloat_Check(fo)) {
235 PyErr_SetString(PyExc_TypeError,
236 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000237 return -1;
238 }
Tim Petersd2364e82001-11-01 20:09:42 +0000239
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 val = PyFloat_AS_DOUBLE(fo);
241 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000242
Guido van Rossumb6775db1994-08-01 11:34:53 +0000243 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244}
245
246/* Methods */
247
Tim Peters97019e42001-11-28 22:43:45 +0000248static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000249format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250{
251 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000252 char format[32];
Guido van Rossum04dbf3b2007-08-07 19:51:00 +0000253 /* Subroutine for float_repr, float_str, and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254 We want float numbers to be recognizable as such,
255 i.e., they should contain a decimal point or an exponent.
256 However, %g may print the number as an integer;
257 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000258
Martin v. Löwis737ea822004-06-08 18:52:54 +0000259 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000260 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261 cp = buf;
262 if (*cp == '-')
263 cp++;
264 for (; *cp != '\0'; cp++) {
265 /* Any non-digit means it's not an integer;
266 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000267 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268 break;
269 }
270 if (*cp == '\0') {
271 *cp++ = '.';
272 *cp++ = '0';
273 *cp++ = '\0';
274 }
275}
276
Neal Norwitz545686b2006-12-28 04:45:06 +0000277static void
278format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000279{
Neal Norwitz545686b2006-12-28 04:45:06 +0000280 assert(PyFloat_Check(v));
281 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000282}
283
Christian Heimesb76922a2007-12-11 01:06:40 +0000284#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000285/* The following function is based on Tcl_PrintDouble,
286 * from tclUtil.c.
287 */
288
289#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
290#define is_nan(d) ((d) != (d))
291
292static void
293format_double_repr(char *dst, double value)
294{
295 char *p, c;
296 int exp;
297 int signum;
298 char buffer[30];
299
300 /*
301 * Handle NaN.
302 */
303
304 if (is_nan(value)) {
305 strcpy(dst, "nan");
306 return;
307 }
308
309 /*
310 * Handle infinities.
311 */
312
313 if (is_infinite(value)) {
314 if (value < 0) {
315 strcpy(dst, "-inf");
316 } else {
317 strcpy(dst, "inf");
318 }
319 return;
320 }
321
322 /*
323 * Ordinary (normal and denormal) values.
324 */
325
326 exp = _PyFloat_Digits(buffer, value, &signum)+1;
327 if (signum) {
328 *dst++ = '-';
329 }
330 p = buffer;
331 if (exp < -3 || exp > 17) {
332 /*
333 * E format for numbers < 1e-3 or >= 1e17.
334 */
335
336 *dst++ = *p++;
337 c = *p;
338 if (c != '\0') {
339 *dst++ = '.';
340 while (c != '\0') {
341 *dst++ = c;
342 c = *++p;
343 }
344 }
345 sprintf(dst, "e%+d", exp-1);
346 } else {
347 /*
348 * F format for others.
349 */
350
351 if (exp <= 0) {
352 *dst++ = '0';
353 }
354 c = *p;
355 while (exp-- > 0) {
356 if (c != '\0') {
357 *dst++ = c;
358 c = *++p;
359 } else {
360 *dst++ = '0';
361 }
362 }
363 *dst++ = '.';
364 if (c == '\0') {
365 *dst++ = '0';
366 } else {
367 while (++exp < 0) {
368 *dst++ = '0';
369 }
370 while (c != '\0') {
371 *dst++ = c;
372 c = *++p;
373 }
374 }
375 *dst++ = '\0';
376 }
377}
378
379static void
380format_float_repr(char *buf, PyFloatObject *v)
381{
382 assert(PyFloat_Check(v));
383 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
384}
385
Christian Heimesb76922a2007-12-11 01:06:40 +0000386#endif /* Py_BROKEN_REPR */
387
Neil Schemenauer32117e52001-01-04 01:44:34 +0000388/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000389 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000390 set to NULL, and the function invoking this macro returns NULL. If
391 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
392 stored in obj, and returned from the function invoking this macro.
393*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000394#define CONVERT_TO_DOUBLE(obj, dbl) \
395 if (PyFloat_Check(obj)) \
396 dbl = PyFloat_AS_DOUBLE(obj); \
397 else if (convert_to_double(&(obj), &(dbl)) < 0) \
398 return obj;
399
400static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000401convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000402{
403 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000404
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000406 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000407 if (*dbl == -1.0 && PyErr_Occurred()) {
408 *v = NULL;
409 return -1;
410 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000411 }
412 else {
413 Py_INCREF(Py_NotImplemented);
414 *v = Py_NotImplemented;
415 return -1;
416 }
417 return 0;
418}
419
Guido van Rossum57072eb1999-12-23 19:00:28 +0000420/* Precisions used by repr() and str(), respectively.
421
422 The repr() precision (17 significant decimal digits) is the minimal number
423 that is guaranteed to have enough precision so that if the number is read
424 back in the exact same binary value is recreated. This is true for IEEE
425 floating point by design, and also happens to work for all other modern
426 hardware.
427
428 The str() precision is chosen so that in most cases, the rounding noise
429 created by various operations is suppressed, while giving plenty of
430 precision for practical use.
431
432*/
433
434#define PREC_REPR 17
435#define PREC_STR 12
436
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000438float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439{
Christian Heimesb76922a2007-12-11 01:06:40 +0000440#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000441 char buf[30];
442 format_float_repr(buf, v);
Christian Heimesb76922a2007-12-11 01:06:40 +0000443#else
444 char buf[100];
445 format_float(buf, sizeof(buf), v, PREC_REPR);
446#endif
447
Walter Dörwald1ab83302007-05-18 17:15:44 +0000448 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000449}
450
451static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000452float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000453{
454 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000455 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000456 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457}
458
Tim Peters307fa782004-09-23 08:06:40 +0000459/* Comparison is pretty much a nightmare. When comparing float to float,
460 * we do it as straightforwardly (and long-windedly) as conceivable, so
461 * that, e.g., Python x == y delivers the same result as the platform
462 * C x == y when x and/or y is a NaN.
463 * When mixing float with an integer type, there's no good *uniform* approach.
464 * Converting the double to an integer obviously doesn't work, since we
465 * may lose info from fractional bits. Converting the integer to a double
466 * also has two failure modes: (1) a long int may trigger overflow (too
467 * large to fit in the dynamic range of a C double); (2) even a C long may have
468 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
469 * 63 bits of precision, but a C double probably has only 53), and then
470 * we can falsely claim equality when low-order integer bits are lost by
471 * coercion to double. So this part is painful too.
472 */
473
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000474static PyObject*
475float_richcompare(PyObject *v, PyObject *w, int op)
476{
477 double i, j;
478 int r = 0;
479
Tim Peters307fa782004-09-23 08:06:40 +0000480 assert(PyFloat_Check(v));
481 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000482
Tim Peters307fa782004-09-23 08:06:40 +0000483 /* Switch on the type of w. Set i and j to doubles to be compared,
484 * and op to the richcomp to use.
485 */
486 if (PyFloat_Check(w))
487 j = PyFloat_AS_DOUBLE(w);
488
Thomas Wouters477c8d52006-05-27 19:21:47 +0000489 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000490 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000491 /* If i is an infinity, its magnitude exceeds any
492 * finite integer, so it doesn't matter which int we
493 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000494 */
495 j = 0.0;
496 else
497 goto Unimplemented;
498 }
499
Tim Peters307fa782004-09-23 08:06:40 +0000500 else if (PyLong_Check(w)) {
501 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
502 int wsign = _PyLong_Sign(w);
503 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000504 int exponent;
505
506 if (vsign != wsign) {
507 /* Magnitudes are irrelevant -- the signs alone
508 * determine the outcome.
509 */
510 i = (double)vsign;
511 j = (double)wsign;
512 goto Compare;
513 }
514 /* The signs are the same. */
515 /* Convert w to a double if it fits. In particular, 0 fits. */
516 nbits = _PyLong_NumBits(w);
517 if (nbits == (size_t)-1 && PyErr_Occurred()) {
518 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000519 * to hold the # of bits. Replace with little doubles
520 * that give the same outcome -- w is so large that
521 * its magnitude must exceed the magnitude of any
522 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000523 */
524 PyErr_Clear();
525 i = (double)vsign;
526 assert(wsign != 0);
527 j = wsign * 2.0;
528 goto Compare;
529 }
530 if (nbits <= 48) {
531 j = PyLong_AsDouble(w);
532 /* It's impossible that <= 48 bits overflowed. */
533 assert(j != -1.0 || ! PyErr_Occurred());
534 goto Compare;
535 }
536 assert(wsign != 0); /* else nbits was 0 */
537 assert(vsign != 0); /* if vsign were 0, then since wsign is
538 * not 0, we would have taken the
539 * vsign != wsign branch at the start */
540 /* We want to work with non-negative numbers. */
541 if (vsign < 0) {
542 /* "Multiply both sides" by -1; this also swaps the
543 * comparator.
544 */
545 i = -i;
546 op = _Py_SwappedOp[op];
547 }
548 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000549 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000550 /* exponent is the # of bits in v before the radix point;
551 * we know that nbits (the # of bits in w) > 48 at this point
552 */
553 if (exponent < 0 || (size_t)exponent < nbits) {
554 i = 1.0;
555 j = 2.0;
556 goto Compare;
557 }
558 if ((size_t)exponent > nbits) {
559 i = 2.0;
560 j = 1.0;
561 goto Compare;
562 }
563 /* v and w have the same number of bits before the radix
564 * point. Construct two longs that have the same comparison
565 * outcome.
566 */
567 {
568 double fracpart;
569 double intpart;
570 PyObject *result = NULL;
571 PyObject *one = NULL;
572 PyObject *vv = NULL;
573 PyObject *ww = w;
574
575 if (wsign < 0) {
576 ww = PyNumber_Negative(w);
577 if (ww == NULL)
578 goto Error;
579 }
580 else
581 Py_INCREF(ww);
582
583 fracpart = modf(i, &intpart);
584 vv = PyLong_FromDouble(intpart);
585 if (vv == NULL)
586 goto Error;
587
588 if (fracpart != 0.0) {
589 /* Shift left, and or a 1 bit into vv
590 * to represent the lost fraction.
591 */
592 PyObject *temp;
593
Christian Heimes217cfd12007-12-02 14:31:20 +0000594 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000595 if (one == NULL)
596 goto Error;
597
598 temp = PyNumber_Lshift(ww, one);
599 if (temp == NULL)
600 goto Error;
601 Py_DECREF(ww);
602 ww = temp;
603
604 temp = PyNumber_Lshift(vv, one);
605 if (temp == NULL)
606 goto Error;
607 Py_DECREF(vv);
608 vv = temp;
609
610 temp = PyNumber_Or(vv, one);
611 if (temp == NULL)
612 goto Error;
613 Py_DECREF(vv);
614 vv = temp;
615 }
616
617 r = PyObject_RichCompareBool(vv, ww, op);
618 if (r < 0)
619 goto Error;
620 result = PyBool_FromLong(r);
621 Error:
622 Py_XDECREF(vv);
623 Py_XDECREF(ww);
624 Py_XDECREF(one);
625 return result;
626 }
627 } /* else if (PyLong_Check(w)) */
628
629 else /* w isn't float, int, or long */
630 goto Unimplemented;
631
632 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633 PyFPE_START_PROTECT("richcompare", return NULL)
634 switch (op) {
635 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000636 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000637 break;
638 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000639 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000640 break;
641 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000642 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000643 break;
644 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000645 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000646 break;
647 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000648 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000649 break;
650 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000651 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000652 break;
653 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000654 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000655 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000656
657 Unimplemented:
658 Py_INCREF(Py_NotImplemented);
659 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000660}
661
Guido van Rossum9bfef441993-03-29 10:43:31 +0000662static long
Fred Drakefd99de62000-07-09 05:02:18 +0000663float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000664{
Tim Peters39dce292000-08-15 03:34:48 +0000665 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000666}
667
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000668static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000669float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000670{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000671 double a,b;
672 CONVERT_TO_DOUBLE(v, a);
673 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000674 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000675 a = a + b;
676 PyFPE_END_PROTECT(a)
677 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678}
679
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000680static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000681float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000682{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000683 double a,b;
684 CONVERT_TO_DOUBLE(v, a);
685 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000686 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000687 a = a - b;
688 PyFPE_END_PROTECT(a)
689 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000690}
691
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000693float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000695 double a,b;
696 CONVERT_TO_DOUBLE(v, a);
697 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000698 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000699 a = a * b;
700 PyFPE_END_PROTECT(a)
701 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702}
703
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000705float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000706{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000707 double a,b;
708 CONVERT_TO_DOUBLE(v, a);
709 CONVERT_TO_DOUBLE(w, b);
710 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712 return NULL;
713 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000714 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000715 a = a / b;
716 PyFPE_END_PROTECT(a)
717 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718}
719
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000721float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000723 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000724 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000725 CONVERT_TO_DOUBLE(v, vx);
726 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729 return NULL;
730 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000731 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000732 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000733 /* note: checking mod*wx < 0 is incorrect -- underflows to
734 0 if wx < sqrt(smallest nonzero double) */
735 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000736 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000737 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000738 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000739 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000740}
741
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000743float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000744{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000745 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000746 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000747 CONVERT_TO_DOUBLE(v, vx);
748 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000749 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000750 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000751 return NULL;
752 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000753 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000754 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000755 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000756 exact multiple of wx. But this is fp arithmetic, and fp
757 vx - mod is an approximation; the result is that div may
758 not be an exact integral value after the division, although
759 it will always be very close to one.
760 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000761 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000762 if (mod) {
763 /* ensure the remainder has the same sign as the denominator */
764 if ((wx < 0) != (mod < 0)) {
765 mod += wx;
766 div -= 1.0;
767 }
768 }
769 else {
770 /* the remainder is zero, and in the presence of signed zeroes
771 fmod returns different results across platforms; ensure
772 it has the same sign as the denominator; we'd like to do
773 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000774 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000775 if (wx < 0.0)
776 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000777 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000778 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000779 if (div) {
780 floordiv = floor(div);
781 if (div - floordiv > 0.5)
782 floordiv += 1.0;
783 }
784 else {
785 /* div is zero - get the same sign as the true quotient */
786 div *= div; /* hide "div = +0" from optimizers */
787 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
788 }
789 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000790 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000791}
792
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000794float_floor_div(PyObject *v, PyObject *w)
795{
796 PyObject *t, *r;
797
798 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000799 if (t == NULL || t == Py_NotImplemented)
800 return t;
801 assert(PyTuple_CheckExact(t));
802 r = PyTuple_GET_ITEM(t, 0);
803 Py_INCREF(r);
804 Py_DECREF(t);
805 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000806}
807
808static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000809float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810{
811 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000812
813 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000814 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000815 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000816 return NULL;
817 }
818
Neil Schemenauer32117e52001-01-04 01:44:34 +0000819 CONVERT_TO_DOUBLE(v, iv);
820 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000821
822 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000823 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000824 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000825 }
Tim Peters96685bf2001-08-23 22:31:37 +0000826 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000827 if (iw < 0.0) {
828 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000829 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000830 return NULL;
831 }
832 return PyFloat_FromDouble(0.0);
833 }
Tim Peterse87568d2003-05-24 20:18:24 +0000834 if (iv < 0.0) {
835 /* Whether this is an error is a mess, and bumps into libm
836 * bugs so we have to figure it out ourselves.
837 */
838 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000839 /* Negative numbers raised to fractional powers
840 * become complex.
841 */
842 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000843 }
844 /* iw is an exact integer, albeit perhaps a very large one.
845 * -1 raised to an exact integer should never be exceptional.
846 * Alas, some libms (chiefly glibc as of early 2003) return
847 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
848 * happen to be representable in a *C* integer. That's a
849 * bug; we let that slide in math.pow() (which currently
850 * reflects all platform accidents), but not for Python's **.
851 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000852 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000853 /* Return 1 if iw is even, -1 if iw is odd; there's
854 * no guarantee that any C integral type is big
855 * enough to hold iw, so we have to check this
856 * indirectly.
857 */
858 ix = floor(iw * 0.5) * 2.0;
859 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
860 }
861 /* Else iv != -1.0, and overflow or underflow are possible.
862 * Unless we're to write pow() ourselves, we have to trust
863 * the platform to do this correctly.
864 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000865 }
Tim Peters96685bf2001-08-23 22:31:37 +0000866 errno = 0;
867 PyFPE_START_PROTECT("pow", return NULL)
868 ix = pow(iv, iw);
869 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000870 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000871 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000872 /* We don't expect any errno value other than ERANGE, but
873 * the range of libm bugs appears unbounded.
874 */
875 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
876 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000878 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880}
881
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000882static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000883float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000886}
887
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000888static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000889float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000890{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000891 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000892}
893
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000894static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000895float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000896{
897 return v->ob_fval != 0.0;
898}
899
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000900static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000901float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000902{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000903 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000904 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000905
906 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000907 /* Try to get out cheap if this fits in a Python int. The attempt
908 * to cast to long must be protected, as C doesn't define what
909 * happens if the double is too big to fit in a long. Some rare
910 * systems raise an exception then (RISCOS was mentioned as one,
911 * and someone using a non-default option on Sun also bumped into
912 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
913 * still be vulnerable: if a long has more bits of precision than
914 * a double, casting MIN/MAX to double may yield an approximation,
915 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
916 * yield true from the C expression wholepart<=LONG_MAX, despite
917 * that wholepart is actually greater than LONG_MAX.
918 */
919 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
920 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000921 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000922 }
923 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000924}
925
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000926static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000927float_round(PyObject *v, PyObject *args)
928{
929#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
930 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000931 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000932 double flr, cil;
933 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000934 int ndigits = UNDEF_NDIGITS;
935
936 if (!PyArg_ParseTuple(args, "|i", &ndigits))
937 return NULL;
938
939 x = PyFloat_AsDouble(v);
940
941 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000942 f = pow(10.0, ndigits);
943 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000944 }
945
946 flr = floor(x);
947 cil = ceil(x);
948
949 if (x-flr > 0.5)
950 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000951 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000952 rounded = fmod(flr, 2) == 0 ? flr : cil;
953 else
954 rounded = flr;
955
956 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000957 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000958 return PyFloat_FromDouble(rounded);
959 }
960
961 return PyLong_FromDouble(rounded);
962#undef UNDEF_NDIGITS
963}
964
965static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000966float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000967{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000968 if (PyFloat_CheckExact(v))
969 Py_INCREF(v);
970 else
971 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000972 return v;
973}
974
975
Jeremy Hylton938ace62002-07-17 16:30:39 +0000976static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000977float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
978
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979static PyObject *
980float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
981{
982 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000983 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984
Guido van Rossumbef14172001-08-29 15:47:46 +0000985 if (type != &PyFloat_Type)
986 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000987 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
988 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000989 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000990 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000991 return PyNumber_Float(x);
992}
993
Guido van Rossumbef14172001-08-29 15:47:46 +0000994/* Wimpy, slow approach to tp_new calls for subtypes of float:
995 first create a regular float from whatever arguments we got,
996 then allocate a subtype instance and initialize its ob_fval
997 from the regular float. The regular float is then thrown away.
998*/
999static PyObject *
1000float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1001{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001002 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001003
1004 assert(PyType_IsSubtype(type, &PyFloat_Type));
1005 tmp = float_new(&PyFloat_Type, args, kwds);
1006 if (tmp == NULL)
1007 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001008 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001009 newobj = type->tp_alloc(type, 0);
1010 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001011 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001012 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001013 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001014 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001015 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001016 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001017}
1018
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001019static PyObject *
1020float_getnewargs(PyFloatObject *v)
1021{
1022 return Py_BuildValue("(d)", v->ob_fval);
1023}
1024
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001025/* this is for the benefit of the pack/unpack routines below */
1026
1027typedef enum {
1028 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1029} float_format_type;
1030
1031static float_format_type double_format, float_format;
1032static float_format_type detected_double_format, detected_float_format;
1033
1034static PyObject *
1035float_getformat(PyTypeObject *v, PyObject* arg)
1036{
1037 char* s;
1038 float_format_type r;
1039
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001040 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001041 PyErr_Format(PyExc_TypeError,
1042 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001043 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001044 return NULL;
1045 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001046 s = PyUnicode_AsString(arg);
1047 if (s == NULL)
1048 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001049 if (strcmp(s, "double") == 0) {
1050 r = double_format;
1051 }
1052 else if (strcmp(s, "float") == 0) {
1053 r = float_format;
1054 }
1055 else {
1056 PyErr_SetString(PyExc_ValueError,
1057 "__getformat__() argument 1 must be "
1058 "'double' or 'float'");
1059 return NULL;
1060 }
1061
1062 switch (r) {
1063 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001064 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001065 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001066 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001067 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001068 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001069 default:
1070 Py_FatalError("insane float_format or double_format");
1071 return NULL;
1072 }
1073}
1074
1075PyDoc_STRVAR(float_getformat_doc,
1076"float.__getformat__(typestr) -> string\n"
1077"\n"
1078"You probably don't want to use this function. It exists mainly to be\n"
1079"used in Python's test suite.\n"
1080"\n"
1081"typestr must be 'double' or 'float'. This function returns whichever of\n"
1082"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1083"format of floating point numbers used by the C type named by typestr.");
1084
1085static PyObject *
1086float_setformat(PyTypeObject *v, PyObject* args)
1087{
1088 char* typestr;
1089 char* format;
1090 float_format_type f;
1091 float_format_type detected;
1092 float_format_type *p;
1093
1094 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1095 return NULL;
1096
1097 if (strcmp(typestr, "double") == 0) {
1098 p = &double_format;
1099 detected = detected_double_format;
1100 }
1101 else if (strcmp(typestr, "float") == 0) {
1102 p = &float_format;
1103 detected = detected_float_format;
1104 }
1105 else {
1106 PyErr_SetString(PyExc_ValueError,
1107 "__setformat__() argument 1 must "
1108 "be 'double' or 'float'");
1109 return NULL;
1110 }
1111
1112 if (strcmp(format, "unknown") == 0) {
1113 f = unknown_format;
1114 }
1115 else if (strcmp(format, "IEEE, little-endian") == 0) {
1116 f = ieee_little_endian_format;
1117 }
1118 else if (strcmp(format, "IEEE, big-endian") == 0) {
1119 f = ieee_big_endian_format;
1120 }
1121 else {
1122 PyErr_SetString(PyExc_ValueError,
1123 "__setformat__() argument 2 must be "
1124 "'unknown', 'IEEE, little-endian' or "
1125 "'IEEE, big-endian'");
1126 return NULL;
1127
1128 }
1129
1130 if (f != unknown_format && f != detected) {
1131 PyErr_Format(PyExc_ValueError,
1132 "can only set %s format to 'unknown' or the "
1133 "detected platform value", typestr);
1134 return NULL;
1135 }
1136
1137 *p = f;
1138 Py_RETURN_NONE;
1139}
1140
1141PyDoc_STRVAR(float_setformat_doc,
1142"float.__setformat__(typestr, fmt) -> None\n"
1143"\n"
1144"You probably don't want to use this function. It exists mainly to be\n"
1145"used in Python's test suite.\n"
1146"\n"
1147"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1148"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1149"one of the latter two if it appears to match the underlying C reality.\n"
1150"\n"
1151"Overrides the automatic determination of C-level floating point type.\n"
1152"This affects how floats are converted to and from binary strings.");
1153
Guido van Rossumb43daf72007-08-01 18:08:08 +00001154static PyObject *
1155float_getzero(PyObject *v, void *closure)
1156{
1157 return PyFloat_FromDouble(0.0);
1158}
1159
Eric Smith8c663262007-08-25 02:26:07 +00001160static PyObject *
1161float__format__(PyObject *self, PyObject *args)
1162{
1163 /* when back porting this to 2.6, check type of the format_spec
1164 and call either unicode_long__format__ or
1165 string_long__format__ */
1166 return unicode_float__format__(self, args);
1167}
1168
1169PyDoc_STRVAR(float__format__doc,
1170"float.__format__(format_spec) -> string\n"
1171"\n"
1172"Formats the float according to format_spec.");
1173
1174
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001175static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001176 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1177 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001178 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1179 "Returns the Integral closest to x between 0 and x."},
1180 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1181 "Returns the Integral closest to x, rounding half toward even.\n"
1182 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001183 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001184 {"__getformat__", (PyCFunction)float_getformat,
1185 METH_O|METH_CLASS, float_getformat_doc},
1186 {"__setformat__", (PyCFunction)float_setformat,
1187 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001188 {"__format__", (PyCFunction)float__format__,
1189 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001190 {NULL, NULL} /* sentinel */
1191};
1192
Guido van Rossumb43daf72007-08-01 18:08:08 +00001193static PyGetSetDef float_getset[] = {
1194 {"real",
1195 (getter)float_float, (setter)NULL,
1196 "the real part of a complex number",
1197 NULL},
1198 {"imag",
1199 (getter)float_getzero, (setter)NULL,
1200 "the imaginary part of a complex number",
1201 NULL},
1202 {NULL} /* Sentinel */
1203};
1204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001205PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206"float(x) -> floating point number\n\
1207\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209
1210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001211static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001212 float_add, /*nb_add*/
1213 float_sub, /*nb_subtract*/
1214 float_mul, /*nb_multiply*/
1215 float_rem, /*nb_remainder*/
1216 float_divmod, /*nb_divmod*/
1217 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001218 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001219 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001220 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001221 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001222 0, /*nb_invert*/
1223 0, /*nb_lshift*/
1224 0, /*nb_rshift*/
1225 0, /*nb_and*/
1226 0, /*nb_xor*/
1227 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001228 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001229 float_trunc, /*nb_int*/
1230 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001231 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001232 0, /* nb_oct */
1233 0, /* nb_hex */
1234 0, /* nb_inplace_add */
1235 0, /* nb_inplace_subtract */
1236 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001237 0, /* nb_inplace_remainder */
1238 0, /* nb_inplace_power */
1239 0, /* nb_inplace_lshift */
1240 0, /* nb_inplace_rshift */
1241 0, /* nb_inplace_and */
1242 0, /* nb_inplace_xor */
1243 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001244 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001245 float_div, /* nb_true_divide */
1246 0, /* nb_inplace_floor_divide */
1247 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001248};
1249
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001250PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001251 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001252 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001253 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001254 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001256 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257 0, /* tp_getattr */
1258 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001259 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 (reprfunc)float_repr, /* tp_repr */
1261 &float_as_number, /* tp_as_number */
1262 0, /* tp_as_sequence */
1263 0, /* tp_as_mapping */
1264 (hashfunc)float_hash, /* tp_hash */
1265 0, /* tp_call */
1266 (reprfunc)float_str, /* tp_str */
1267 PyObject_GenericGetAttr, /* tp_getattro */
1268 0, /* tp_setattro */
1269 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001270 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 float_doc, /* tp_doc */
1272 0, /* tp_traverse */
1273 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001274 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 0, /* tp_weaklistoffset */
1276 0, /* tp_iter */
1277 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001278 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001280 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281 0, /* tp_base */
1282 0, /* tp_dict */
1283 0, /* tp_descr_get */
1284 0, /* tp_descr_set */
1285 0, /* tp_dictoffset */
1286 0, /* tp_init */
1287 0, /* tp_alloc */
1288 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001289};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001290
1291void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001292_PyFloat_Init(void)
1293{
1294 /* We attempt to determine if this machine is using IEEE
1295 floating point formats by peering at the bits of some
1296 carefully chosen values. If it looks like we are on an
1297 IEEE platform, the float packing/unpacking routines can
1298 just copy bits, if not they resort to arithmetic & shifts
1299 and masks. The shifts & masks approach works on all finite
1300 values, but what happens to infinities, NaNs and signed
1301 zeroes on packing is an accident, and attempting to unpack
1302 a NaN or an infinity will raise an exception.
1303
1304 Note that if we're on some whacked-out platform which uses
1305 IEEE formats but isn't strictly little-endian or big-
1306 endian, we will fall back to the portable shifts & masks
1307 method. */
1308
1309#if SIZEOF_DOUBLE == 8
1310 {
1311 double x = 9006104071832581.0;
1312 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1313 detected_double_format = ieee_big_endian_format;
1314 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1315 detected_double_format = ieee_little_endian_format;
1316 else
1317 detected_double_format = unknown_format;
1318 }
1319#else
1320 detected_double_format = unknown_format;
1321#endif
1322
1323#if SIZEOF_FLOAT == 4
1324 {
1325 float y = 16711938.0;
1326 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1327 detected_float_format = ieee_big_endian_format;
1328 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1329 detected_float_format = ieee_little_endian_format;
1330 else
1331 detected_float_format = unknown_format;
1332 }
1333#else
1334 detected_float_format = unknown_format;
1335#endif
1336
1337 double_format = detected_double_format;
1338 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001339
1340#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001341 /* Initialize floating point repr */
1342 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001343#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001344}
1345
1346void
Fred Drakefd99de62000-07-09 05:02:18 +00001347PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001348{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001349 PyFloatObject *p;
1350 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001351 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001352 int bc, bf; /* block count, number of freed blocks */
1353 int frem, fsum; /* remaining unfreed floats per block, total */
1354
1355 bc = 0;
1356 bf = 0;
1357 fsum = 0;
1358 list = block_list;
1359 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001360 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001361 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001362 bc++;
1363 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001364 for (i = 0, p = &list->objects[0];
1365 i < N_FLOATOBJECTS;
1366 i++, p++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001367 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001368 frem++;
1369 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001370 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001371 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001372 list->next = block_list;
1373 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001374 for (i = 0, p = &list->objects[0];
1375 i < N_FLOATOBJECTS;
1376 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001377 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001378 Py_Refcnt(p) == 0) {
1379 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001380 free_list;
1381 free_list = p;
1382 }
1383 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001384 }
1385 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001386 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001387 bf++;
1388 }
1389 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001390 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001391 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001392 if (!Py_VerboseFlag)
1393 return;
1394 fprintf(stderr, "# cleanup floats");
1395 if (!fsum) {
1396 fprintf(stderr, "\n");
1397 }
1398 else {
1399 fprintf(stderr,
1400 ": %d unfreed float%s in %d out of %d block%s\n",
1401 fsum, fsum == 1 ? "" : "s",
1402 bc - bf, bc, bc == 1 ? "" : "s");
1403 }
1404 if (Py_VerboseFlag > 1) {
1405 list = block_list;
1406 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001407 for (i = 0, p = &list->objects[0];
1408 i < N_FLOATOBJECTS;
1409 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001410 if (PyFloat_CheckExact(p) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001411 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001412 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001413 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001414 /* XXX(twouters) cast refcount to
1415 long until %zd is universally
1416 available
1417 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001418 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001419 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001420 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001421 }
1422 }
1423 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001424 }
1425 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001426}
Tim Peters9905b942003-03-20 20:53:32 +00001427
1428/*----------------------------------------------------------------------------
1429 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1430 *
1431 * TODO: On platforms that use the standard IEEE-754 single and double
1432 * formats natively, these routines could simply copy the bytes.
1433 */
1434int
1435_PyFloat_Pack4(double x, unsigned char *p, int le)
1436{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001437 if (float_format == unknown_format) {
1438 unsigned char sign;
1439 int e;
1440 double f;
1441 unsigned int fbits;
1442 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001443
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001444 if (le) {
1445 p += 3;
1446 incr = -1;
1447 }
Tim Peters9905b942003-03-20 20:53:32 +00001448
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001449 if (x < 0) {
1450 sign = 1;
1451 x = -x;
1452 }
1453 else
1454 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001455
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001456 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001457
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001458 /* Normalize f to be in the range [1.0, 2.0) */
1459 if (0.5 <= f && f < 1.0) {
1460 f *= 2.0;
1461 e--;
1462 }
1463 else if (f == 0.0)
1464 e = 0;
1465 else {
1466 PyErr_SetString(PyExc_SystemError,
1467 "frexp() result out of range");
1468 return -1;
1469 }
1470
1471 if (e >= 128)
1472 goto Overflow;
1473 else if (e < -126) {
1474 /* Gradual underflow */
1475 f = ldexp(f, 126 + e);
1476 e = 0;
1477 }
1478 else if (!(e == 0 && f == 0.0)) {
1479 e += 127;
1480 f -= 1.0; /* Get rid of leading 1 */
1481 }
1482
1483 f *= 8388608.0; /* 2**23 */
1484 fbits = (unsigned int)(f + 0.5); /* Round */
1485 assert(fbits <= 8388608);
1486 if (fbits >> 23) {
1487 /* The carry propagated out of a string of 23 1 bits. */
1488 fbits = 0;
1489 ++e;
1490 if (e >= 255)
1491 goto Overflow;
1492 }
1493
1494 /* First byte */
1495 *p = (sign << 7) | (e >> 1);
1496 p += incr;
1497
1498 /* Second byte */
1499 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1500 p += incr;
1501
1502 /* Third byte */
1503 *p = (fbits >> 8) & 0xFF;
1504 p += incr;
1505
1506 /* Fourth byte */
1507 *p = fbits & 0xFF;
1508
1509 /* Done */
1510 return 0;
1511
1512 Overflow:
1513 PyErr_SetString(PyExc_OverflowError,
1514 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001515 return -1;
1516 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001517 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001518 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001519 const char *s = (char*)&y;
1520 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001521
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001522 if ((float_format == ieee_little_endian_format && !le)
1523 || (float_format == ieee_big_endian_format && le)) {
1524 p += 3;
1525 incr = -1;
1526 }
1527
1528 for (i = 0; i < 4; i++) {
1529 *p = *s++;
1530 p += incr;
1531 }
1532 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001533 }
Tim Peters9905b942003-03-20 20:53:32 +00001534}
1535
1536int
1537_PyFloat_Pack8(double x, unsigned char *p, int le)
1538{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001539 if (double_format == unknown_format) {
1540 unsigned char sign;
1541 int e;
1542 double f;
1543 unsigned int fhi, flo;
1544 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001545
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001546 if (le) {
1547 p += 7;
1548 incr = -1;
1549 }
Tim Peters9905b942003-03-20 20:53:32 +00001550
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001551 if (x < 0) {
1552 sign = 1;
1553 x = -x;
1554 }
1555 else
1556 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001557
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001558 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001559
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001560 /* Normalize f to be in the range [1.0, 2.0) */
1561 if (0.5 <= f && f < 1.0) {
1562 f *= 2.0;
1563 e--;
1564 }
1565 else if (f == 0.0)
1566 e = 0;
1567 else {
1568 PyErr_SetString(PyExc_SystemError,
1569 "frexp() result out of range");
1570 return -1;
1571 }
1572
1573 if (e >= 1024)
1574 goto Overflow;
1575 else if (e < -1022) {
1576 /* Gradual underflow */
1577 f = ldexp(f, 1022 + e);
1578 e = 0;
1579 }
1580 else if (!(e == 0 && f == 0.0)) {
1581 e += 1023;
1582 f -= 1.0; /* Get rid of leading 1 */
1583 }
1584
1585 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1586 f *= 268435456.0; /* 2**28 */
1587 fhi = (unsigned int)f; /* Truncate */
1588 assert(fhi < 268435456);
1589
1590 f -= (double)fhi;
1591 f *= 16777216.0; /* 2**24 */
1592 flo = (unsigned int)(f + 0.5); /* Round */
1593 assert(flo <= 16777216);
1594 if (flo >> 24) {
1595 /* The carry propagated out of a string of 24 1 bits. */
1596 flo = 0;
1597 ++fhi;
1598 if (fhi >> 28) {
1599 /* And it also progagated out of the next 28 bits. */
1600 fhi = 0;
1601 ++e;
1602 if (e >= 2047)
1603 goto Overflow;
1604 }
1605 }
1606
1607 /* First byte */
1608 *p = (sign << 7) | (e >> 4);
1609 p += incr;
1610
1611 /* Second byte */
1612 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1613 p += incr;
1614
1615 /* Third byte */
1616 *p = (fhi >> 16) & 0xFF;
1617 p += incr;
1618
1619 /* Fourth byte */
1620 *p = (fhi >> 8) & 0xFF;
1621 p += incr;
1622
1623 /* Fifth byte */
1624 *p = fhi & 0xFF;
1625 p += incr;
1626
1627 /* Sixth byte */
1628 *p = (flo >> 16) & 0xFF;
1629 p += incr;
1630
1631 /* Seventh byte */
1632 *p = (flo >> 8) & 0xFF;
1633 p += incr;
1634
1635 /* Eighth byte */
1636 *p = flo & 0xFF;
1637 p += incr;
1638
1639 /* Done */
1640 return 0;
1641
1642 Overflow:
1643 PyErr_SetString(PyExc_OverflowError,
1644 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001645 return -1;
1646 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001647 else {
1648 const char *s = (char*)&x;
1649 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001650
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651 if ((double_format == ieee_little_endian_format && !le)
1652 || (double_format == ieee_big_endian_format && le)) {
1653 p += 7;
1654 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001655 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001656
1657 for (i = 0; i < 8; i++) {
1658 *p = *s++;
1659 p += incr;
1660 }
1661 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001662 }
Tim Peters9905b942003-03-20 20:53:32 +00001663}
1664
Neal Norwitz545686b2006-12-28 04:45:06 +00001665/* Should only be used by marshal. */
1666int
1667_PyFloat_Repr(double x, char *p, size_t len)
1668{
1669 format_double(p, len, x, PREC_REPR);
1670 return (int)strlen(p);
1671}
1672
Tim Peters9905b942003-03-20 20:53:32 +00001673double
1674_PyFloat_Unpack4(const unsigned char *p, int le)
1675{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676 if (float_format == unknown_format) {
1677 unsigned char sign;
1678 int e;
1679 unsigned int f;
1680 double x;
1681 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001682
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683 if (le) {
1684 p += 3;
1685 incr = -1;
1686 }
1687
1688 /* First byte */
1689 sign = (*p >> 7) & 1;
1690 e = (*p & 0x7F) << 1;
1691 p += incr;
1692
1693 /* Second byte */
1694 e |= (*p >> 7) & 1;
1695 f = (*p & 0x7F) << 16;
1696 p += incr;
1697
1698 if (e == 255) {
1699 PyErr_SetString(
1700 PyExc_ValueError,
1701 "can't unpack IEEE 754 special value "
1702 "on non-IEEE platform");
1703 return -1;
1704 }
1705
1706 /* Third byte */
1707 f |= *p << 8;
1708 p += incr;
1709
1710 /* Fourth byte */
1711 f |= *p;
1712
1713 x = (double)f / 8388608.0;
1714
1715 /* XXX This sadly ignores Inf/NaN issues */
1716 if (e == 0)
1717 e = -126;
1718 else {
1719 x += 1.0;
1720 e -= 127;
1721 }
1722 x = ldexp(x, e);
1723
1724 if (sign)
1725 x = -x;
1726
1727 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001728 }
Tim Peters9905b942003-03-20 20:53:32 +00001729 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001730 float x;
1731
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001732 if ((float_format == ieee_little_endian_format && !le)
1733 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001734 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001735 char *d = &buf[3];
1736 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001737
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001738 for (i = 0; i < 4; i++) {
1739 *d-- = *p++;
1740 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001741 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001742 }
1743 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001744 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001745 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001746
1747 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001748 }
Tim Peters9905b942003-03-20 20:53:32 +00001749}
1750
1751double
1752_PyFloat_Unpack8(const unsigned char *p, int le)
1753{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001754 if (double_format == unknown_format) {
1755 unsigned char sign;
1756 int e;
1757 unsigned int fhi, flo;
1758 double x;
1759 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001760
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001761 if (le) {
1762 p += 7;
1763 incr = -1;
1764 }
1765
1766 /* First byte */
1767 sign = (*p >> 7) & 1;
1768 e = (*p & 0x7F) << 4;
1769
1770 p += incr;
1771
1772 /* Second byte */
1773 e |= (*p >> 4) & 0xF;
1774 fhi = (*p & 0xF) << 24;
1775 p += incr;
1776
1777 if (e == 2047) {
1778 PyErr_SetString(
1779 PyExc_ValueError,
1780 "can't unpack IEEE 754 special value "
1781 "on non-IEEE platform");
1782 return -1.0;
1783 }
1784
1785 /* Third byte */
1786 fhi |= *p << 16;
1787 p += incr;
1788
1789 /* Fourth byte */
1790 fhi |= *p << 8;
1791 p += incr;
1792
1793 /* Fifth byte */
1794 fhi |= *p;
1795 p += incr;
1796
1797 /* Sixth byte */
1798 flo = *p << 16;
1799 p += incr;
1800
1801 /* Seventh byte */
1802 flo |= *p << 8;
1803 p += incr;
1804
1805 /* Eighth byte */
1806 flo |= *p;
1807
1808 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1809 x /= 268435456.0; /* 2**28 */
1810
1811 if (e == 0)
1812 e = -1022;
1813 else {
1814 x += 1.0;
1815 e -= 1023;
1816 }
1817 x = ldexp(x, e);
1818
1819 if (sign)
1820 x = -x;
1821
1822 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001823 }
Tim Peters9905b942003-03-20 20:53:32 +00001824 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001825 double x;
1826
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001827 if ((double_format == ieee_little_endian_format && !le)
1828 || (double_format == ieee_big_endian_format && le)) {
1829 char buf[8];
1830 char *d = &buf[7];
1831 int i;
1832
1833 for (i = 0; i < 8; i++) {
1834 *d-- = *p++;
1835 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001836 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001837 }
1838 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001839 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001840 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001841
1842 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001843 }
Tim Peters9905b942003-03-20 20:53:32 +00001844}