blob: a6a29e7f93bc7cae202a8eaa1ed9d316ae7c7716 [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
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Jack Janseneddc1442003-11-20 01:44:59 +000012#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000013extern double fmod(double, double);
14extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000015#endif
16
Guido van Rossum93ad0df1997-05-13 21:00:42 +000017/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000018#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000019#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000020#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000021
Guido van Rossum3fce8831999-03-12 19:43:17 +000022struct _floatblock {
23 struct _floatblock *next;
24 PyFloatObject objects[N_FLOATOBJECTS];
25};
26
27typedef struct _floatblock PyFloatBlock;
28
29static PyFloatBlock *block_list = NULL;
30static PyFloatObject *free_list = NULL;
31
Guido van Rossum93ad0df1997-05-13 21:00:42 +000032static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000033fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000034{
35 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000036 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
37 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000038 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000039 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000040 ((PyFloatBlock *)p)->next = block_list;
41 block_list = (PyFloatBlock *)p;
42 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043 q = p + N_FLOATOBJECTS;
44 while (--q > p)
Martin v. Löwis68192102007-07-21 06:55:02 +000045 Py_Type(q) = (struct _typeobject *)(q-1);
46 Py_Type(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000047 return p + N_FLOATOBJECTS - 1;
48}
49
Christian Heimesdfdfaab2007-12-01 11:20:10 +000050double
51PyFloat_GetMax(void)
52{
53 return DBL_MAX;
54}
55
56double
57PyFloat_GetMin(void)
58{
59 return DBL_MIN;
60}
61
62PyObject *
63PyFloat_GetInfo(void)
64{
65 PyObject *d, *tmp;
66
67#define SET_FLOAT_CONST(d, key, const) \
68 tmp = PyFloat_FromDouble(const); \
69 if (tmp == NULL) return NULL; \
70 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
71 Py_DECREF(tmp)
72#define SET_INT_CONST(d, key, const) \
73 tmp = PyInt_FromLong(const); \
74 if (tmp == NULL) return NULL; \
75 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
76 Py_DECREF(tmp)
77
78 d = PyDict_New();
79
80 SET_FLOAT_CONST(d, "max", DBL_MAX);
81 SET_INT_CONST(d, "max_exp", DBL_MAX_EXP);
82 SET_INT_CONST(d, "max_10_exp", DBL_MAX_10_EXP);
83 SET_FLOAT_CONST(d, "min", DBL_MIN);
84 SET_INT_CONST(d, "min_exp", DBL_MIN_EXP);
85 SET_INT_CONST(d, "min_10_exp", DBL_MIN_10_EXP);
86 SET_INT_CONST(d, "dig", DBL_DIG);
87 SET_INT_CONST(d, "mant_dig", DBL_MANT_DIG);
88 SET_FLOAT_CONST(d, "epsilon", DBL_EPSILON);
89 SET_INT_CONST(d, "radix", FLT_RADIX);
90 SET_INT_CONST(d, "rounds", FLT_ROUNDS);
91
92 return d;
93}
94
95
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Guido van Rossum93ad0df1997-05-13 21:00:42 +000099 register PyFloatObject *op;
100 if (free_list == NULL) {
101 if ((free_list = fill_free_list()) == NULL)
102 return NULL;
103 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000104 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000105 op = free_list;
Martin v. Löwis68192102007-07-21 06:55:02 +0000106 free_list = (PyFloatObject *)Py_Type(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000107 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000108 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110}
111
Tim Petersef14d732000-09-23 03:39:17 +0000112/**************************************************************************
113RED_FLAG 22-Sep-2000 tim
114PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
115
1161. If v was a regular string, *pend was set to point to its terminating
117 null byte. That's useless (the caller can find that without any
118 help from this function!).
119
1202. If v was a Unicode string, or an object convertible to a character
121 buffer, *pend was set to point into stack trash (the auto temp
122 vector holding the character buffer). That was downright dangerous.
123
124Since we can't change the interface of a public API function, pend is
125still supported but now *officially* useless: if pend is not NULL,
126*pend is set to NULL.
127**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000128PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000129PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000130{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000131 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000132 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000133 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000134#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000135 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000136#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000137 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000138
Tim Petersef14d732000-09-23 03:39:17 +0000139 if (pend)
140 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000141 if (PyString_Check(v)) {
142 s = PyString_AS_STRING(v);
143 len = PyString_GET_SIZE(v);
144 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000145#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000146 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000147 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000148 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000149 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000150 return NULL;
151 }
Tim Petersef14d732000-09-23 03:39:17 +0000152 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000153 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000154 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000155 NULL))
156 return NULL;
157 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000158 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000159 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000160#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000161 else if (PyObject_AsCharBuffer(v, &s, &len)) {
162 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000163 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000165 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166
Guido van Rossum4c08d552000-03-10 22:55:18 +0000167 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168 while (*s && isspace(Py_CHARMASK(*s)))
169 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000170 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 PyErr_SetString(PyExc_ValueError, "empty string for float()");
172 return NULL;
173 }
Tim Petersef14d732000-09-23 03:39:17 +0000174 /* We don't care about overflow or underflow. If the platform supports
175 * them, infinities and signed zeroes (on underflow) are fine.
176 * However, strtod can return 0 for denormalized numbers, where atof
177 * does not. So (alas!) we special-case a zero result. Note that
178 * whether strtod sets errno on underflow is not defined, so we can't
179 * key off errno.
180 */
Tim Peters858346e2000-09-25 21:01:28 +0000181 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000182 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000183 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000185 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000186 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 if (end > last)
188 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000189 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000190 PyOS_snprintf(buffer, sizeof(buffer),
191 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000192 PyErr_SetString(PyExc_ValueError, buffer);
193 return NULL;
194 }
195 /* Since end != s, the platform made *some* kind of sense out
196 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000197 while (*end && isspace(Py_CHARMASK(*end)))
198 end++;
199 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000200 PyOS_snprintf(buffer, sizeof(buffer),
201 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000202 PyErr_SetString(PyExc_ValueError, buffer);
203 return NULL;
204 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000205 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000206 PyErr_SetString(PyExc_ValueError,
207 "null byte in argument for float()");
208 return NULL;
209 }
Tim Petersef14d732000-09-23 03:39:17 +0000210 if (x == 0.0) {
211 /* See above -- may have been strtod being anal
212 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000213 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000214 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000215 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000216 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 return PyFloat_FromDouble(x);
219}
220
Guido van Rossum234f9421993-06-17 12:35:49 +0000221static void
Fred Drakefd99de62000-07-09 05:02:18 +0000222float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000223{
Guido van Rossum9475a232001-10-05 20:51:39 +0000224 if (PyFloat_CheckExact(op)) {
Martin v. Löwis68192102007-07-21 06:55:02 +0000225 Py_Type(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000226 free_list = op;
227 }
228 else
Martin v. Löwis68192102007-07-21 06:55:02 +0000229 Py_Type(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000230}
231
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232double
Fred Drakefd99de62000-07-09 05:02:18 +0000233PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 PyNumberMethods *nb;
236 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000237 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000238
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000239 if (op && PyFloat_Check(op))
240 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000241
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000242 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244 return -1;
245 }
Tim Petersd2364e82001-11-01 20:09:42 +0000246
Martin v. Löwis68192102007-07-21 06:55:02 +0000247 if ((nb = Py_Type(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000248 PyErr_SetString(PyExc_TypeError, "a float is required");
249 return -1;
250 }
251
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000252 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000253 if (fo == NULL)
254 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000255 if (!PyFloat_Check(fo)) {
256 PyErr_SetString(PyExc_TypeError,
257 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000258 return -1;
259 }
Tim Petersd2364e82001-11-01 20:09:42 +0000260
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000261 val = PyFloat_AS_DOUBLE(fo);
262 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000263
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000265}
266
267/* Methods */
268
Tim Peters97019e42001-11-28 22:43:45 +0000269static void
270format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271{
272 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000273 char format[32];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000274 /* Subroutine for float_repr and float_print.
275 We want float numbers to be recognizable as such,
276 i.e., they should contain a decimal point or an exponent.
277 However, %g may print the number as an integer;
278 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000279
280 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000281 PyOS_snprintf(format, 32, "%%.%ig", precision);
282 PyOS_ascii_formatd(buf, buflen, format, v->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';
296 }
297}
298
Tim Peters97019e42001-11-28 22:43:45 +0000299/* XXX PyFloat_AsStringEx should not be a public API function (for one
300 XXX thing, its signature passes a buffer without a length; for another,
301 XXX it isn't useful outside this file).
302*/
303void
304PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
305{
306 format_float(buf, 100, v, precision);
307}
308
Christian Heimesf15c66e2007-12-11 00:54:34 +0000309#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000310/* The following function is based on Tcl_PrintDouble,
311 * from tclUtil.c.
312 */
313
314#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
315#define is_nan(d) ((d) != (d))
316
317static void
318format_double_repr(char *dst, double value)
319{
320 char *p, c;
321 int exp;
322 int signum;
323 char buffer[30];
324
325 /*
326 * Handle NaN.
327 */
328
329 if (is_nan(value)) {
330 strcpy(dst, "nan");
331 return;
332 }
333
334 /*
335 * Handle infinities.
336 */
337
338 if (is_infinite(value)) {
339 if (value < 0) {
340 strcpy(dst, "-inf");
341 } else {
342 strcpy(dst, "inf");
343 }
344 return;
345 }
346
347 /*
348 * Ordinary (normal and denormal) values.
349 */
350
351 exp = _PyFloat_Digits(buffer, value, &signum)+1;
352 if (signum) {
353 *dst++ = '-';
354 }
355 p = buffer;
356 if (exp < -3 || exp > 17) {
357 /*
358 * E format for numbers < 1e-3 or >= 1e17.
359 */
360
361 *dst++ = *p++;
362 c = *p;
363 if (c != '\0') {
364 *dst++ = '.';
365 while (c != '\0') {
366 *dst++ = c;
367 c = *++p;
368 }
369 }
370 sprintf(dst, "e%+d", exp-1);
371 } else {
372 /*
373 * F format for others.
374 */
375
376 if (exp <= 0) {
377 *dst++ = '0';
378 }
379 c = *p;
380 while (exp-- > 0) {
381 if (c != '\0') {
382 *dst++ = c;
383 c = *++p;
384 } else {
385 *dst++ = '0';
386 }
387 }
388 *dst++ = '.';
389 if (c == '\0') {
390 *dst++ = '0';
391 } else {
392 while (++exp < 0) {
393 *dst++ = '0';
394 }
395 while (c != '\0') {
396 *dst++ = c;
397 c = *++p;
398 }
399 }
400 *dst++ = '\0';
401 }
402}
403
404static void
405format_float_repr(char *buf, PyFloatObject *v)
406{
407 assert(PyFloat_Check(v));
408 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
409}
410
Christian Heimesf15c66e2007-12-11 00:54:34 +0000411#endif /* Py_BROKEN_REPR */
412
Neil Schemenauer32117e52001-01-04 01:44:34 +0000413/* Macro and helper that convert PyObject obj to a C double and store
414 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000415 slot function. If conversion to double raises an exception, obj is
416 set to NULL, and the function invoking this macro returns NULL. If
417 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
418 stored in obj, and returned from the function invoking this macro.
419*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000420#define CONVERT_TO_DOUBLE(obj, dbl) \
421 if (PyFloat_Check(obj)) \
422 dbl = PyFloat_AS_DOUBLE(obj); \
423 else if (convert_to_double(&(obj), &(dbl)) < 0) \
424 return obj;
425
426static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000427convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000428{
429 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000430
Neil Schemenauer32117e52001-01-04 01:44:34 +0000431 if (PyInt_Check(obj)) {
432 *dbl = (double)PyInt_AS_LONG(obj);
433 }
434 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000435 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000436 if (*dbl == -1.0 && PyErr_Occurred()) {
437 *v = NULL;
438 return -1;
439 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000440 }
441 else {
442 Py_INCREF(Py_NotImplemented);
443 *v = Py_NotImplemented;
444 return -1;
445 }
446 return 0;
447}
448
Guido van Rossum57072eb1999-12-23 19:00:28 +0000449/* Precisions used by repr() and str(), respectively.
450
451 The repr() precision (17 significant decimal digits) is the minimal number
452 that is guaranteed to have enough precision so that if the number is read
453 back in the exact same binary value is recreated. This is true for IEEE
454 floating point by design, and also happens to work for all other modern
455 hardware.
456
457 The str() precision is chosen so that in most cases, the rounding noise
458 created by various operations is suppressed, while giving plenty of
459 precision for practical use.
460
461*/
462
463#define PREC_REPR 17
464#define PREC_STR 12
465
Tim Peters97019e42001-11-28 22:43:45 +0000466/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
467 XXX they pass a char buffer without passing a length.
468*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000469void
Fred Drakefd99de62000-07-09 05:02:18 +0000470PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000471{
Tim Peters97019e42001-11-28 22:43:45 +0000472 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000473}
474
Tim Peters72f98e92001-05-08 15:19:57 +0000475void
476PyFloat_AsReprString(char *buf, PyFloatObject *v)
477{
Tim Peters97019e42001-11-28 22:43:45 +0000478 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000479}
480
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000481/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000482static int
Fred Drakefd99de62000-07-09 05:02:18 +0000483float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484{
485 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000486 format_float(buf, sizeof(buf), v,
487 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000488 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000489 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000490 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000491 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492}
493
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000495float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000497#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000498 char buf[30];
499 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000500#else
501 char buf[100];
502 format_float(buf, sizeof(buf), v, PREC_REPR);
503#endif
504
Guido van Rossum57072eb1999-12-23 19:00:28 +0000505 return PyString_FromString(buf);
506}
507
508static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000509float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000510{
511 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000512 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000514}
515
Tim Peters307fa782004-09-23 08:06:40 +0000516/* Comparison is pretty much a nightmare. When comparing float to float,
517 * we do it as straightforwardly (and long-windedly) as conceivable, so
518 * that, e.g., Python x == y delivers the same result as the platform
519 * C x == y when x and/or y is a NaN.
520 * When mixing float with an integer type, there's no good *uniform* approach.
521 * Converting the double to an integer obviously doesn't work, since we
522 * may lose info from fractional bits. Converting the integer to a double
523 * also has two failure modes: (1) a long int may trigger overflow (too
524 * large to fit in the dynamic range of a C double); (2) even a C long may have
525 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
526 * 63 bits of precision, but a C double probably has only 53), and then
527 * we can falsely claim equality when low-order integer bits are lost by
528 * coercion to double. So this part is painful too.
529 */
530
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000531static PyObject*
532float_richcompare(PyObject *v, PyObject *w, int op)
533{
534 double i, j;
535 int r = 0;
536
Tim Peters307fa782004-09-23 08:06:40 +0000537 assert(PyFloat_Check(v));
538 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000539
Tim Peters307fa782004-09-23 08:06:40 +0000540 /* Switch on the type of w. Set i and j to doubles to be compared,
541 * and op to the richcomp to use.
542 */
543 if (PyFloat_Check(w))
544 j = PyFloat_AS_DOUBLE(w);
545
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000546 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000547 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000548 /* If i is an infinity, its magnitude exceeds any
549 * finite integer, so it doesn't matter which int we
550 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000551 */
552 j = 0.0;
553 else
554 goto Unimplemented;
555 }
556
557 else if (PyInt_Check(w)) {
558 long jj = PyInt_AS_LONG(w);
559 /* In the worst realistic case I can imagine, C double is a
560 * Cray single with 48 bits of precision, and long has 64
561 * bits.
562 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000563#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000564 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
565 if (abs >> 48) {
566 /* Needs more than 48 bits. Make it take the
567 * PyLong path.
568 */
569 PyObject *result;
570 PyObject *ww = PyLong_FromLong(jj);
571
572 if (ww == NULL)
573 return NULL;
574 result = float_richcompare(v, ww, op);
575 Py_DECREF(ww);
576 return result;
577 }
578#endif
579 j = (double)jj;
580 assert((long)j == jj);
581 }
582
583 else if (PyLong_Check(w)) {
584 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
585 int wsign = _PyLong_Sign(w);
586 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000587 int exponent;
588
589 if (vsign != wsign) {
590 /* Magnitudes are irrelevant -- the signs alone
591 * determine the outcome.
592 */
593 i = (double)vsign;
594 j = (double)wsign;
595 goto Compare;
596 }
597 /* The signs are the same. */
598 /* Convert w to a double if it fits. In particular, 0 fits. */
599 nbits = _PyLong_NumBits(w);
600 if (nbits == (size_t)-1 && PyErr_Occurred()) {
601 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000602 * to hold the # of bits. Replace with little doubles
603 * that give the same outcome -- w is so large that
604 * its magnitude must exceed the magnitude of any
605 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000606 */
607 PyErr_Clear();
608 i = (double)vsign;
609 assert(wsign != 0);
610 j = wsign * 2.0;
611 goto Compare;
612 }
613 if (nbits <= 48) {
614 j = PyLong_AsDouble(w);
615 /* It's impossible that <= 48 bits overflowed. */
616 assert(j != -1.0 || ! PyErr_Occurred());
617 goto Compare;
618 }
619 assert(wsign != 0); /* else nbits was 0 */
620 assert(vsign != 0); /* if vsign were 0, then since wsign is
621 * not 0, we would have taken the
622 * vsign != wsign branch at the start */
623 /* We want to work with non-negative numbers. */
624 if (vsign < 0) {
625 /* "Multiply both sides" by -1; this also swaps the
626 * comparator.
627 */
628 i = -i;
629 op = _Py_SwappedOp[op];
630 }
631 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000632 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000633 /* exponent is the # of bits in v before the radix point;
634 * we know that nbits (the # of bits in w) > 48 at this point
635 */
636 if (exponent < 0 || (size_t)exponent < nbits) {
637 i = 1.0;
638 j = 2.0;
639 goto Compare;
640 }
641 if ((size_t)exponent > nbits) {
642 i = 2.0;
643 j = 1.0;
644 goto Compare;
645 }
646 /* v and w have the same number of bits before the radix
647 * point. Construct two longs that have the same comparison
648 * outcome.
649 */
650 {
651 double fracpart;
652 double intpart;
653 PyObject *result = NULL;
654 PyObject *one = NULL;
655 PyObject *vv = NULL;
656 PyObject *ww = w;
657
658 if (wsign < 0) {
659 ww = PyNumber_Negative(w);
660 if (ww == NULL)
661 goto Error;
662 }
663 else
664 Py_INCREF(ww);
665
666 fracpart = modf(i, &intpart);
667 vv = PyLong_FromDouble(intpart);
668 if (vv == NULL)
669 goto Error;
670
671 if (fracpart != 0.0) {
672 /* Shift left, and or a 1 bit into vv
673 * to represent the lost fraction.
674 */
675 PyObject *temp;
676
677 one = PyInt_FromLong(1);
678 if (one == NULL)
679 goto Error;
680
681 temp = PyNumber_Lshift(ww, one);
682 if (temp == NULL)
683 goto Error;
684 Py_DECREF(ww);
685 ww = temp;
686
687 temp = PyNumber_Lshift(vv, one);
688 if (temp == NULL)
689 goto Error;
690 Py_DECREF(vv);
691 vv = temp;
692
693 temp = PyNumber_Or(vv, one);
694 if (temp == NULL)
695 goto Error;
696 Py_DECREF(vv);
697 vv = temp;
698 }
699
700 r = PyObject_RichCompareBool(vv, ww, op);
701 if (r < 0)
702 goto Error;
703 result = PyBool_FromLong(r);
704 Error:
705 Py_XDECREF(vv);
706 Py_XDECREF(ww);
707 Py_XDECREF(one);
708 return result;
709 }
710 } /* else if (PyLong_Check(w)) */
711
712 else /* w isn't float, int, or long */
713 goto Unimplemented;
714
715 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000716 PyFPE_START_PROTECT("richcompare", return NULL)
717 switch (op) {
718 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000719 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000720 break;
721 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000722 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000723 break;
724 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000725 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000726 break;
727 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000728 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000729 break;
730 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000731 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000732 break;
733 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000734 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000735 break;
736 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000737 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000738 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000739
740 Unimplemented:
741 Py_INCREF(Py_NotImplemented);
742 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000743}
744
Guido van Rossum9bfef441993-03-29 10:43:31 +0000745static long
Fred Drakefd99de62000-07-09 05:02:18 +0000746float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000747{
Tim Peters39dce292000-08-15 03:34:48 +0000748 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000749}
750
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000751static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000752float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000753{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000754 double a,b;
755 CONVERT_TO_DOUBLE(v, a);
756 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000757 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000758 a = a + b;
759 PyFPE_END_PROTECT(a)
760 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000761}
762
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000763static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000764float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000765{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000766 double a,b;
767 CONVERT_TO_DOUBLE(v, a);
768 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000769 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000770 a = a - b;
771 PyFPE_END_PROTECT(a)
772 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773}
774
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000776float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000778 double a,b;
779 CONVERT_TO_DOUBLE(v, a);
780 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000781 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000782 a = a * b;
783 PyFPE_END_PROTECT(a)
784 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000785}
786
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000787static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000788float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000789{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000790 double a,b;
791 CONVERT_TO_DOUBLE(v, a);
792 CONVERT_TO_DOUBLE(w, b);
793 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000794 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795 return NULL;
796 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000797 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000798 a = a / b;
799 PyFPE_END_PROTECT(a)
800 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801}
802
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000804float_classic_div(PyObject *v, PyObject *w)
805{
806 double a,b;
807 CONVERT_TO_DOUBLE(v, a);
808 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000809 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000810 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
811 return NULL;
812 if (b == 0.0) {
813 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
814 return NULL;
815 }
816 PyFPE_START_PROTECT("divide", return 0)
817 a = a / b;
818 PyFPE_END_PROTECT(a)
819 return PyFloat_FromDouble(a);
820}
821
822static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000823float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000825 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000826 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000827 CONVERT_TO_DOUBLE(v, vx);
828 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000829 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000830 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000831 return NULL;
832 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000833 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000834 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000835 /* note: checking mod*wx < 0 is incorrect -- underflows to
836 0 if wx < sqrt(smallest nonzero double) */
837 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000838 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000839 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000840 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000841 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000842}
843
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000844static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000845float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000846{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000847 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000848 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000849 CONVERT_TO_DOUBLE(v, vx);
850 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000851 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000852 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000853 return NULL;
854 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000855 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000856 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000857 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000858 exact multiple of wx. But this is fp arithmetic, and fp
859 vx - mod is an approximation; the result is that div may
860 not be an exact integral value after the division, although
861 it will always be very close to one.
862 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000863 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000864 if (mod) {
865 /* ensure the remainder has the same sign as the denominator */
866 if ((wx < 0) != (mod < 0)) {
867 mod += wx;
868 div -= 1.0;
869 }
870 }
871 else {
872 /* the remainder is zero, and in the presence of signed zeroes
873 fmod returns different results across platforms; ensure
874 it has the same sign as the denominator; we'd like to do
875 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000876 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000877 if (wx < 0.0)
878 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000879 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000880 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000881 if (div) {
882 floordiv = floor(div);
883 if (div - floordiv > 0.5)
884 floordiv += 1.0;
885 }
886 else {
887 /* div is zero - get the same sign as the true quotient */
888 div *= div; /* hide "div = +0" from optimizers */
889 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
890 }
891 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000892 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000893}
894
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000895static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000896float_floor_div(PyObject *v, PyObject *w)
897{
898 PyObject *t, *r;
899
900 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000901 if (t == NULL || t == Py_NotImplemented)
902 return t;
903 assert(PyTuple_CheckExact(t));
904 r = PyTuple_GET_ITEM(t, 0);
905 Py_INCREF(r);
906 Py_DECREF(t);
907 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000908}
909
910static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000911float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000912{
913 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000914
915 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000916 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000917 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000918 return NULL;
919 }
920
Neil Schemenauer32117e52001-01-04 01:44:34 +0000921 CONVERT_TO_DOUBLE(v, iv);
922 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000923
924 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000925 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000926 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000927 }
Tim Peters96685bf2001-08-23 22:31:37 +0000928 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000929 if (iw < 0.0) {
930 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000931 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000932 return NULL;
933 }
934 return PyFloat_FromDouble(0.0);
935 }
Tim Peterse87568d2003-05-24 20:18:24 +0000936 if (iv < 0.0) {
937 /* Whether this is an error is a mess, and bumps into libm
938 * bugs so we have to figure it out ourselves.
939 */
940 if (iw != floor(iw)) {
941 PyErr_SetString(PyExc_ValueError, "negative number "
942 "cannot be raised to a fractional power");
943 return NULL;
944 }
945 /* iw is an exact integer, albeit perhaps a very large one.
946 * -1 raised to an exact integer should never be exceptional.
947 * Alas, some libms (chiefly glibc as of early 2003) return
948 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
949 * happen to be representable in a *C* integer. That's a
950 * bug; we let that slide in math.pow() (which currently
951 * reflects all platform accidents), but not for Python's **.
952 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000953 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000954 /* Return 1 if iw is even, -1 if iw is odd; there's
955 * no guarantee that any C integral type is big
956 * enough to hold iw, so we have to check this
957 * indirectly.
958 */
959 ix = floor(iw * 0.5) * 2.0;
960 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
961 }
962 /* Else iv != -1.0, and overflow or underflow are possible.
963 * Unless we're to write pow() ourselves, we have to trust
964 * the platform to do this correctly.
965 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000966 }
Tim Peters96685bf2001-08-23 22:31:37 +0000967 errno = 0;
968 PyFPE_START_PROTECT("pow", return NULL)
969 ix = pow(iv, iw);
970 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000971 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000972 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000973 /* We don't expect any errno value other than ERANGE, but
974 * the range of libm bugs appears unbounded.
975 */
Alex Martelli348dc882006-08-23 22:17:59 +0000976 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
977 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000978 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000979 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000980 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000981}
982
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000984float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000985{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000986 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000987}
988
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000990float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000991{
Tim Peters0280cf72001-09-11 21:53:35 +0000992 if (PyFloat_CheckExact(v)) {
993 Py_INCREF(v);
994 return (PyObject *)v;
995 }
996 else
997 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000998}
999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001000static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001001float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001002{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001003 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001004}
1005
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001006static int
Fred Drakefd99de62000-07-09 05:02:18 +00001007float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001008{
1009 return v->ob_fval != 0.0;
1010}
1011
Guido van Rossum234f9421993-06-17 12:35:49 +00001012static int
Fred Drakefd99de62000-07-09 05:02:18 +00001013float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001014{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001015 if (PyInt_Check(*pw)) {
1016 long x = PyInt_AsLong(*pw);
1017 *pw = PyFloat_FromDouble((double)x);
1018 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001019 return 0;
1020 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001021 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001022 double x = PyLong_AsDouble(*pw);
1023 if (x == -1.0 && PyErr_Occurred())
1024 return -1;
1025 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001026 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001027 return 0;
1028 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001029 else if (PyFloat_Check(*pw)) {
1030 Py_INCREF(*pv);
1031 Py_INCREF(*pw);
1032 return 0;
1033 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001034 return 1; /* Can't do it */
1035}
1036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001037static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00001038float_long(PyObject *v)
1039{
1040 double x = PyFloat_AsDouble(v);
1041 return PyLong_FromDouble(x);
1042}
1043
1044static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001045float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001046{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001047 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001048 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001049
1050 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001051 /* Try to get out cheap if this fits in a Python int. The attempt
1052 * to cast to long must be protected, as C doesn't define what
1053 * happens if the double is too big to fit in a long. Some rare
1054 * systems raise an exception then (RISCOS was mentioned as one,
1055 * and someone using a non-default option on Sun also bumped into
1056 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1057 * still be vulnerable: if a long has more bits of precision than
1058 * a double, casting MIN/MAX to double may yield an approximation,
1059 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1060 * yield true from the C expression wholepart<=LONG_MAX, despite
1061 * that wholepart is actually greater than LONG_MAX.
1062 */
1063 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1064 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001065 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001066 }
1067 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001068}
1069
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001070static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001071float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001072{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001073 if (PyFloat_CheckExact(v))
1074 Py_INCREF(v);
1075 else
1076 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001077 return v;
1078}
1079
1080
Jeremy Hylton938ace62002-07-17 16:30:39 +00001081static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001082float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1083
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084static PyObject *
1085float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1086{
1087 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001088 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089
Guido van Rossumbef14172001-08-29 15:47:46 +00001090 if (type != &PyFloat_Type)
1091 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1093 return NULL;
1094 if (PyString_Check(x))
1095 return PyFloat_FromString(x, NULL);
1096 return PyNumber_Float(x);
1097}
1098
Guido van Rossumbef14172001-08-29 15:47:46 +00001099/* Wimpy, slow approach to tp_new calls for subtypes of float:
1100 first create a regular float from whatever arguments we got,
1101 then allocate a subtype instance and initialize its ob_fval
1102 from the regular float. The regular float is then thrown away.
1103*/
1104static PyObject *
1105float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1106{
Anthony Baxter377be112006-04-11 06:54:30 +00001107 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001108
1109 assert(PyType_IsSubtype(type, &PyFloat_Type));
1110 tmp = float_new(&PyFloat_Type, args, kwds);
1111 if (tmp == NULL)
1112 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001113 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001114 newobj = type->tp_alloc(type, 0);
1115 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001116 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001117 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001118 }
Anthony Baxter377be112006-04-11 06:54:30 +00001119 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001120 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001121 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001122}
1123
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001124static PyObject *
1125float_getnewargs(PyFloatObject *v)
1126{
1127 return Py_BuildValue("(d)", v->ob_fval);
1128}
1129
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001130/* this is for the benefit of the pack/unpack routines below */
1131
1132typedef enum {
1133 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1134} float_format_type;
1135
1136static float_format_type double_format, float_format;
1137static float_format_type detected_double_format, detected_float_format;
1138
1139static PyObject *
1140float_getformat(PyTypeObject *v, PyObject* arg)
1141{
1142 char* s;
1143 float_format_type r;
1144
1145 if (!PyString_Check(arg)) {
1146 PyErr_Format(PyExc_TypeError,
1147 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis68192102007-07-21 06:55:02 +00001148 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001149 return NULL;
1150 }
1151 s = PyString_AS_STRING(arg);
1152 if (strcmp(s, "double") == 0) {
1153 r = double_format;
1154 }
1155 else if (strcmp(s, "float") == 0) {
1156 r = float_format;
1157 }
1158 else {
1159 PyErr_SetString(PyExc_ValueError,
1160 "__getformat__() argument 1 must be "
1161 "'double' or 'float'");
1162 return NULL;
1163 }
1164
1165 switch (r) {
1166 case unknown_format:
1167 return PyString_FromString("unknown");
1168 case ieee_little_endian_format:
1169 return PyString_FromString("IEEE, little-endian");
1170 case ieee_big_endian_format:
1171 return PyString_FromString("IEEE, big-endian");
1172 default:
1173 Py_FatalError("insane float_format or double_format");
1174 return NULL;
1175 }
1176}
1177
1178PyDoc_STRVAR(float_getformat_doc,
1179"float.__getformat__(typestr) -> string\n"
1180"\n"
1181"You probably don't want to use this function. It exists mainly to be\n"
1182"used in Python's test suite.\n"
1183"\n"
1184"typestr must be 'double' or 'float'. This function returns whichever of\n"
1185"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1186"format of floating point numbers used by the C type named by typestr.");
1187
1188static PyObject *
1189float_setformat(PyTypeObject *v, PyObject* args)
1190{
1191 char* typestr;
1192 char* format;
1193 float_format_type f;
1194 float_format_type detected;
1195 float_format_type *p;
1196
1197 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1198 return NULL;
1199
1200 if (strcmp(typestr, "double") == 0) {
1201 p = &double_format;
1202 detected = detected_double_format;
1203 }
1204 else if (strcmp(typestr, "float") == 0) {
1205 p = &float_format;
1206 detected = detected_float_format;
1207 }
1208 else {
1209 PyErr_SetString(PyExc_ValueError,
1210 "__setformat__() argument 1 must "
1211 "be 'double' or 'float'");
1212 return NULL;
1213 }
1214
1215 if (strcmp(format, "unknown") == 0) {
1216 f = unknown_format;
1217 }
1218 else if (strcmp(format, "IEEE, little-endian") == 0) {
1219 f = ieee_little_endian_format;
1220 }
1221 else if (strcmp(format, "IEEE, big-endian") == 0) {
1222 f = ieee_big_endian_format;
1223 }
1224 else {
1225 PyErr_SetString(PyExc_ValueError,
1226 "__setformat__() argument 2 must be "
1227 "'unknown', 'IEEE, little-endian' or "
1228 "'IEEE, big-endian'");
1229 return NULL;
1230
1231 }
1232
1233 if (f != unknown_format && f != detected) {
1234 PyErr_Format(PyExc_ValueError,
1235 "can only set %s format to 'unknown' or the "
1236 "detected platform value", typestr);
1237 return NULL;
1238 }
1239
1240 *p = f;
1241 Py_RETURN_NONE;
1242}
1243
1244PyDoc_STRVAR(float_setformat_doc,
1245"float.__setformat__(typestr, fmt) -> None\n"
1246"\n"
1247"You probably don't want to use this function. It exists mainly to be\n"
1248"used in Python's test suite.\n"
1249"\n"
1250"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1251"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1252"one of the latter two if it appears to match the underlying C reality.\n"
1253"\n"
1254"Overrides the automatic determination of C-level floating point type.\n"
1255"This affects how floats are converted to and from binary strings.");
1256
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001257static PyMethodDef float_methods[] = {
1258 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001259 {"__getformat__", (PyCFunction)float_getformat,
1260 METH_O|METH_CLASS, float_getformat_doc},
1261 {"__setformat__", (PyCFunction)float_setformat,
1262 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001263 {NULL, NULL} /* sentinel */
1264};
1265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001266PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267"float(x) -> floating point number\n\
1268\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001269Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270
1271
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001272static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001273 float_add, /*nb_add*/
1274 float_sub, /*nb_subtract*/
1275 float_mul, /*nb_multiply*/
1276 float_classic_div, /*nb_divide*/
1277 float_rem, /*nb_remainder*/
1278 float_divmod, /*nb_divmod*/
1279 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001280 (unaryfunc)float_neg, /*nb_negative*/
1281 (unaryfunc)float_pos, /*nb_positive*/
1282 (unaryfunc)float_abs, /*nb_absolute*/
1283 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001284 0, /*nb_invert*/
1285 0, /*nb_lshift*/
1286 0, /*nb_rshift*/
1287 0, /*nb_and*/
1288 0, /*nb_xor*/
1289 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001290 float_coerce, /*nb_coerce*/
1291 float_int, /*nb_int*/
1292 float_long, /*nb_long*/
1293 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001294 0, /* nb_oct */
1295 0, /* nb_hex */
1296 0, /* nb_inplace_add */
1297 0, /* nb_inplace_subtract */
1298 0, /* nb_inplace_multiply */
1299 0, /* nb_inplace_divide */
1300 0, /* nb_inplace_remainder */
1301 0, /* nb_inplace_power */
1302 0, /* nb_inplace_lshift */
1303 0, /* nb_inplace_rshift */
1304 0, /* nb_inplace_and */
1305 0, /* nb_inplace_xor */
1306 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001307 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001308 float_div, /* nb_true_divide */
1309 0, /* nb_inplace_floor_divide */
1310 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001311};
1312
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001314 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001315 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001316 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001317 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318 (destructor)float_dealloc, /* tp_dealloc */
1319 (printfunc)float_print, /* tp_print */
1320 0, /* tp_getattr */
1321 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001322 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 (reprfunc)float_repr, /* tp_repr */
1324 &float_as_number, /* tp_as_number */
1325 0, /* tp_as_sequence */
1326 0, /* tp_as_mapping */
1327 (hashfunc)float_hash, /* tp_hash */
1328 0, /* tp_call */
1329 (reprfunc)float_str, /* tp_str */
1330 PyObject_GenericGetAttr, /* tp_getattro */
1331 0, /* tp_setattro */
1332 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001333 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1334 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 float_doc, /* tp_doc */
1336 0, /* tp_traverse */
1337 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001338 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 0, /* tp_weaklistoffset */
1340 0, /* tp_iter */
1341 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001342 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343 0, /* tp_members */
1344 0, /* tp_getset */
1345 0, /* tp_base */
1346 0, /* tp_dict */
1347 0, /* tp_descr_get */
1348 0, /* tp_descr_set */
1349 0, /* tp_dictoffset */
1350 0, /* tp_init */
1351 0, /* tp_alloc */
1352 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001353};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001354
1355void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001356_PyFloat_Init(void)
1357{
1358 /* We attempt to determine if this machine is using IEEE
1359 floating point formats by peering at the bits of some
1360 carefully chosen values. If it looks like we are on an
1361 IEEE platform, the float packing/unpacking routines can
1362 just copy bits, if not they resort to arithmetic & shifts
1363 and masks. The shifts & masks approach works on all finite
1364 values, but what happens to infinities, NaNs and signed
1365 zeroes on packing is an accident, and attempting to unpack
1366 a NaN or an infinity will raise an exception.
1367
1368 Note that if we're on some whacked-out platform which uses
1369 IEEE formats but isn't strictly little-endian or big-
1370 endian, we will fall back to the portable shifts & masks
1371 method. */
1372
1373#if SIZEOF_DOUBLE == 8
1374 {
1375 double x = 9006104071832581.0;
1376 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1377 detected_double_format = ieee_big_endian_format;
1378 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1379 detected_double_format = ieee_little_endian_format;
1380 else
1381 detected_double_format = unknown_format;
1382 }
1383#else
1384 detected_double_format = unknown_format;
1385#endif
1386
1387#if SIZEOF_FLOAT == 4
1388 {
1389 float y = 16711938.0;
1390 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1391 detected_float_format = ieee_big_endian_format;
1392 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1393 detected_float_format = ieee_little_endian_format;
1394 else
1395 detected_float_format = unknown_format;
1396 }
1397#else
1398 detected_float_format = unknown_format;
1399#endif
1400
1401 double_format = detected_double_format;
1402 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001403
1404#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001405 /* Initialize floating point repr */
1406 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001407#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001408}
1409
1410void
Fred Drakefd99de62000-07-09 05:02:18 +00001411PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001412{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001413 PyFloatObject *p;
1414 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001415 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001416 int bc, bf; /* block count, number of freed blocks */
1417 int frem, fsum; /* remaining unfreed floats per block, total */
1418
1419 bc = 0;
1420 bf = 0;
1421 fsum = 0;
1422 list = block_list;
1423 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001424 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001425 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001426 bc++;
1427 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001428 for (i = 0, p = &list->objects[0];
1429 i < N_FLOATOBJECTS;
1430 i++, p++) {
Martin v. Löwis68192102007-07-21 06:55:02 +00001431 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001432 frem++;
1433 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001434 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001435 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001436 list->next = block_list;
1437 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001438 for (i = 0, p = &list->objects[0];
1439 i < N_FLOATOBJECTS;
1440 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001441 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis68192102007-07-21 06:55:02 +00001442 Py_Refcnt(p) == 0) {
1443 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001444 free_list;
1445 free_list = p;
1446 }
1447 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001448 }
1449 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001450 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001451 bf++;
1452 }
1453 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001454 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001455 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001456 if (!Py_VerboseFlag)
1457 return;
1458 fprintf(stderr, "# cleanup floats");
1459 if (!fsum) {
1460 fprintf(stderr, "\n");
1461 }
1462 else {
1463 fprintf(stderr,
1464 ": %d unfreed float%s in %d out of %d block%s\n",
1465 fsum, fsum == 1 ? "" : "s",
1466 bc - bf, bc, bc == 1 ? "" : "s");
1467 }
1468 if (Py_VerboseFlag > 1) {
1469 list = block_list;
1470 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001471 for (i = 0, p = &list->objects[0];
1472 i < N_FLOATOBJECTS;
1473 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001474 if (PyFloat_CheckExact(p) &&
Martin v. Löwis68192102007-07-21 06:55:02 +00001475 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001476 char buf[100];
1477 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001478 /* XXX(twouters) cast refcount to
1479 long until %zd is universally
1480 available
1481 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001482 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001483 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis68192102007-07-21 06:55:02 +00001484 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001485 }
1486 }
1487 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001488 }
1489 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001490}
Tim Peters9905b942003-03-20 20:53:32 +00001491
1492/*----------------------------------------------------------------------------
1493 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1494 *
1495 * TODO: On platforms that use the standard IEEE-754 single and double
1496 * formats natively, these routines could simply copy the bytes.
1497 */
1498int
1499_PyFloat_Pack4(double x, unsigned char *p, int le)
1500{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001501 if (float_format == unknown_format) {
1502 unsigned char sign;
1503 int e;
1504 double f;
1505 unsigned int fbits;
1506 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001507
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001508 if (le) {
1509 p += 3;
1510 incr = -1;
1511 }
Tim Peters9905b942003-03-20 20:53:32 +00001512
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001513 if (x < 0) {
1514 sign = 1;
1515 x = -x;
1516 }
1517 else
1518 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001519
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001520 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001521
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001522 /* Normalize f to be in the range [1.0, 2.0) */
1523 if (0.5 <= f && f < 1.0) {
1524 f *= 2.0;
1525 e--;
1526 }
1527 else if (f == 0.0)
1528 e = 0;
1529 else {
1530 PyErr_SetString(PyExc_SystemError,
1531 "frexp() result out of range");
1532 return -1;
1533 }
1534
1535 if (e >= 128)
1536 goto Overflow;
1537 else if (e < -126) {
1538 /* Gradual underflow */
1539 f = ldexp(f, 126 + e);
1540 e = 0;
1541 }
1542 else if (!(e == 0 && f == 0.0)) {
1543 e += 127;
1544 f -= 1.0; /* Get rid of leading 1 */
1545 }
1546
1547 f *= 8388608.0; /* 2**23 */
1548 fbits = (unsigned int)(f + 0.5); /* Round */
1549 assert(fbits <= 8388608);
1550 if (fbits >> 23) {
1551 /* The carry propagated out of a string of 23 1 bits. */
1552 fbits = 0;
1553 ++e;
1554 if (e >= 255)
1555 goto Overflow;
1556 }
1557
1558 /* First byte */
1559 *p = (sign << 7) | (e >> 1);
1560 p += incr;
1561
1562 /* Second byte */
1563 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1564 p += incr;
1565
1566 /* Third byte */
1567 *p = (fbits >> 8) & 0xFF;
1568 p += incr;
1569
1570 /* Fourth byte */
1571 *p = fbits & 0xFF;
1572
1573 /* Done */
1574 return 0;
1575
1576 Overflow:
1577 PyErr_SetString(PyExc_OverflowError,
1578 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001579 return -1;
1580 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001582 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001583 const char *s = (char*)&y;
1584 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001585
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001586 if ((float_format == ieee_little_endian_format && !le)
1587 || (float_format == ieee_big_endian_format && le)) {
1588 p += 3;
1589 incr = -1;
1590 }
1591
1592 for (i = 0; i < 4; i++) {
1593 *p = *s++;
1594 p += incr;
1595 }
1596 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001597 }
Tim Peters9905b942003-03-20 20:53:32 +00001598}
1599
1600int
1601_PyFloat_Pack8(double x, unsigned char *p, int le)
1602{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001603 if (double_format == unknown_format) {
1604 unsigned char sign;
1605 int e;
1606 double f;
1607 unsigned int fhi, flo;
1608 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001609
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001610 if (le) {
1611 p += 7;
1612 incr = -1;
1613 }
Tim Peters9905b942003-03-20 20:53:32 +00001614
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615 if (x < 0) {
1616 sign = 1;
1617 x = -x;
1618 }
1619 else
1620 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001621
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001622 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001623
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 /* Normalize f to be in the range [1.0, 2.0) */
1625 if (0.5 <= f && f < 1.0) {
1626 f *= 2.0;
1627 e--;
1628 }
1629 else if (f == 0.0)
1630 e = 0;
1631 else {
1632 PyErr_SetString(PyExc_SystemError,
1633 "frexp() result out of range");
1634 return -1;
1635 }
1636
1637 if (e >= 1024)
1638 goto Overflow;
1639 else if (e < -1022) {
1640 /* Gradual underflow */
1641 f = ldexp(f, 1022 + e);
1642 e = 0;
1643 }
1644 else if (!(e == 0 && f == 0.0)) {
1645 e += 1023;
1646 f -= 1.0; /* Get rid of leading 1 */
1647 }
1648
1649 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1650 f *= 268435456.0; /* 2**28 */
1651 fhi = (unsigned int)f; /* Truncate */
1652 assert(fhi < 268435456);
1653
1654 f -= (double)fhi;
1655 f *= 16777216.0; /* 2**24 */
1656 flo = (unsigned int)(f + 0.5); /* Round */
1657 assert(flo <= 16777216);
1658 if (flo >> 24) {
1659 /* The carry propagated out of a string of 24 1 bits. */
1660 flo = 0;
1661 ++fhi;
1662 if (fhi >> 28) {
1663 /* And it also progagated out of the next 28 bits. */
1664 fhi = 0;
1665 ++e;
1666 if (e >= 2047)
1667 goto Overflow;
1668 }
1669 }
1670
1671 /* First byte */
1672 *p = (sign << 7) | (e >> 4);
1673 p += incr;
1674
1675 /* Second byte */
1676 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1677 p += incr;
1678
1679 /* Third byte */
1680 *p = (fhi >> 16) & 0xFF;
1681 p += incr;
1682
1683 /* Fourth byte */
1684 *p = (fhi >> 8) & 0xFF;
1685 p += incr;
1686
1687 /* Fifth byte */
1688 *p = fhi & 0xFF;
1689 p += incr;
1690
1691 /* Sixth byte */
1692 *p = (flo >> 16) & 0xFF;
1693 p += incr;
1694
1695 /* Seventh byte */
1696 *p = (flo >> 8) & 0xFF;
1697 p += incr;
1698
1699 /* Eighth byte */
1700 *p = flo & 0xFF;
1701 p += incr;
1702
1703 /* Done */
1704 return 0;
1705
1706 Overflow:
1707 PyErr_SetString(PyExc_OverflowError,
1708 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001709 return -1;
1710 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711 else {
1712 const char *s = (char*)&x;
1713 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001714
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001715 if ((double_format == ieee_little_endian_format && !le)
1716 || (double_format == ieee_big_endian_format && le)) {
1717 p += 7;
1718 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001719 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001720
1721 for (i = 0; i < 8; i++) {
1722 *p = *s++;
1723 p += incr;
1724 }
1725 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001726 }
Tim Peters9905b942003-03-20 20:53:32 +00001727}
1728
1729double
1730_PyFloat_Unpack4(const unsigned char *p, int le)
1731{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001732 if (float_format == unknown_format) {
1733 unsigned char sign;
1734 int e;
1735 unsigned int f;
1736 double x;
1737 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001738
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001739 if (le) {
1740 p += 3;
1741 incr = -1;
1742 }
1743
1744 /* First byte */
1745 sign = (*p >> 7) & 1;
1746 e = (*p & 0x7F) << 1;
1747 p += incr;
1748
1749 /* Second byte */
1750 e |= (*p >> 7) & 1;
1751 f = (*p & 0x7F) << 16;
1752 p += incr;
1753
1754 if (e == 255) {
1755 PyErr_SetString(
1756 PyExc_ValueError,
1757 "can't unpack IEEE 754 special value "
1758 "on non-IEEE platform");
1759 return -1;
1760 }
1761
1762 /* Third byte */
1763 f |= *p << 8;
1764 p += incr;
1765
1766 /* Fourth byte */
1767 f |= *p;
1768
1769 x = (double)f / 8388608.0;
1770
1771 /* XXX This sadly ignores Inf/NaN issues */
1772 if (e == 0)
1773 e = -126;
1774 else {
1775 x += 1.0;
1776 e -= 127;
1777 }
1778 x = ldexp(x, e);
1779
1780 if (sign)
1781 x = -x;
1782
1783 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001784 }
Tim Peters9905b942003-03-20 20:53:32 +00001785 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001786 float x;
1787
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001788 if ((float_format == ieee_little_endian_format && !le)
1789 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001790 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001791 char *d = &buf[3];
1792 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001793
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001794 for (i = 0; i < 4; i++) {
1795 *d-- = *p++;
1796 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001797 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001798 }
1799 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001800 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001801 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001802
1803 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001804 }
Tim Peters9905b942003-03-20 20:53:32 +00001805}
1806
1807double
1808_PyFloat_Unpack8(const unsigned char *p, int le)
1809{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001810 if (double_format == unknown_format) {
1811 unsigned char sign;
1812 int e;
1813 unsigned int fhi, flo;
1814 double x;
1815 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001816
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001817 if (le) {
1818 p += 7;
1819 incr = -1;
1820 }
1821
1822 /* First byte */
1823 sign = (*p >> 7) & 1;
1824 e = (*p & 0x7F) << 4;
1825
1826 p += incr;
1827
1828 /* Second byte */
1829 e |= (*p >> 4) & 0xF;
1830 fhi = (*p & 0xF) << 24;
1831 p += incr;
1832
1833 if (e == 2047) {
1834 PyErr_SetString(
1835 PyExc_ValueError,
1836 "can't unpack IEEE 754 special value "
1837 "on non-IEEE platform");
1838 return -1.0;
1839 }
1840
1841 /* Third byte */
1842 fhi |= *p << 16;
1843 p += incr;
1844
1845 /* Fourth byte */
1846 fhi |= *p << 8;
1847 p += incr;
1848
1849 /* Fifth byte */
1850 fhi |= *p;
1851 p += incr;
1852
1853 /* Sixth byte */
1854 flo = *p << 16;
1855 p += incr;
1856
1857 /* Seventh byte */
1858 flo |= *p << 8;
1859 p += incr;
1860
1861 /* Eighth byte */
1862 flo |= *p;
1863
1864 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1865 x /= 268435456.0; /* 2**28 */
1866
1867 if (e == 0)
1868 e = -1022;
1869 else {
1870 x += 1.0;
1871 e -= 1023;
1872 }
1873 x = ldexp(x, e);
1874
1875 if (sign)
1876 x = -x;
1877
1878 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001879 }
Tim Peters9905b942003-03-20 20:53:32 +00001880 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001881 double x;
1882
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001883 if ((double_format == ieee_little_endian_format && !le)
1884 || (double_format == ieee_big_endian_format && le)) {
1885 char buf[8];
1886 char *d = &buf[7];
1887 int i;
1888
1889 for (i = 0; i < 8; i++) {
1890 *d-- = *p++;
1891 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001892 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001893 }
1894 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001895 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001896 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001897
1898 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001899 }
Tim Peters9905b942003-03-20 20:53:32 +00001900}