blob: e92dab9da29f3379d572d343d2fe747061e7bc66 [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 Heimes284d9272007-12-10 22:28:56 +0000309/* The following function is based on Tcl_PrintDouble,
310 * from tclUtil.c.
311 */
312
313#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
314#define is_nan(d) ((d) != (d))
315
316static void
317format_double_repr(char *dst, double value)
318{
319 char *p, c;
320 int exp;
321 int signum;
322 char buffer[30];
323
324 /*
325 * Handle NaN.
326 */
327
328 if (is_nan(value)) {
329 strcpy(dst, "nan");
330 return;
331 }
332
333 /*
334 * Handle infinities.
335 */
336
337 if (is_infinite(value)) {
338 if (value < 0) {
339 strcpy(dst, "-inf");
340 } else {
341 strcpy(dst, "inf");
342 }
343 return;
344 }
345
346 /*
347 * Ordinary (normal and denormal) values.
348 */
349
350 exp = _PyFloat_Digits(buffer, value, &signum)+1;
351 if (signum) {
352 *dst++ = '-';
353 }
354 p = buffer;
355 if (exp < -3 || exp > 17) {
356 /*
357 * E format for numbers < 1e-3 or >= 1e17.
358 */
359
360 *dst++ = *p++;
361 c = *p;
362 if (c != '\0') {
363 *dst++ = '.';
364 while (c != '\0') {
365 *dst++ = c;
366 c = *++p;
367 }
368 }
369 sprintf(dst, "e%+d", exp-1);
370 } else {
371 /*
372 * F format for others.
373 */
374
375 if (exp <= 0) {
376 *dst++ = '0';
377 }
378 c = *p;
379 while (exp-- > 0) {
380 if (c != '\0') {
381 *dst++ = c;
382 c = *++p;
383 } else {
384 *dst++ = '0';
385 }
386 }
387 *dst++ = '.';
388 if (c == '\0') {
389 *dst++ = '0';
390 } else {
391 while (++exp < 0) {
392 *dst++ = '0';
393 }
394 while (c != '\0') {
395 *dst++ = c;
396 c = *++p;
397 }
398 }
399 *dst++ = '\0';
400 }
401}
402
403static void
404format_float_repr(char *buf, PyFloatObject *v)
405{
406 assert(PyFloat_Check(v));
407 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
408}
409
Neil Schemenauer32117e52001-01-04 01:44:34 +0000410/* Macro and helper that convert PyObject obj to a C double and store
411 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000412 slot function. If conversion to double raises an exception, obj is
413 set to NULL, and the function invoking this macro returns NULL. If
414 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
415 stored in obj, and returned from the function invoking this macro.
416*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000417#define CONVERT_TO_DOUBLE(obj, dbl) \
418 if (PyFloat_Check(obj)) \
419 dbl = PyFloat_AS_DOUBLE(obj); \
420 else if (convert_to_double(&(obj), &(dbl)) < 0) \
421 return obj;
422
423static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000424convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000425{
426 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000427
Neil Schemenauer32117e52001-01-04 01:44:34 +0000428 if (PyInt_Check(obj)) {
429 *dbl = (double)PyInt_AS_LONG(obj);
430 }
431 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000432 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000433 if (*dbl == -1.0 && PyErr_Occurred()) {
434 *v = NULL;
435 return -1;
436 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000437 }
438 else {
439 Py_INCREF(Py_NotImplemented);
440 *v = Py_NotImplemented;
441 return -1;
442 }
443 return 0;
444}
445
Guido van Rossum57072eb1999-12-23 19:00:28 +0000446/* Precisions used by repr() and str(), respectively.
447
448 The repr() precision (17 significant decimal digits) is the minimal number
449 that is guaranteed to have enough precision so that if the number is read
450 back in the exact same binary value is recreated. This is true for IEEE
451 floating point by design, and also happens to work for all other modern
452 hardware.
453
454 The str() precision is chosen so that in most cases, the rounding noise
455 created by various operations is suppressed, while giving plenty of
456 precision for practical use.
457
458*/
459
460#define PREC_REPR 17
461#define PREC_STR 12
462
Tim Peters97019e42001-11-28 22:43:45 +0000463/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
464 XXX they pass a char buffer without passing a length.
465*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000466void
Fred Drakefd99de62000-07-09 05:02:18 +0000467PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000468{
Tim Peters97019e42001-11-28 22:43:45 +0000469 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000470}
471
Tim Peters72f98e92001-05-08 15:19:57 +0000472void
473PyFloat_AsReprString(char *buf, PyFloatObject *v)
474{
Tim Peters97019e42001-11-28 22:43:45 +0000475 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000476}
477
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000478/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000479static int
Fred Drakefd99de62000-07-09 05:02:18 +0000480float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000481{
482 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000483 format_float(buf, sizeof(buf), v,
484 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000485 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000486 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000487 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000488 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000489}
490
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000492float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493{
Christian Heimes284d9272007-12-10 22:28:56 +0000494 char buf[30];
495 format_float_repr(buf, v);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000496 return PyString_FromString(buf);
497}
498
499static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000500float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000501{
502 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000503 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505}
506
Tim Peters307fa782004-09-23 08:06:40 +0000507/* Comparison is pretty much a nightmare. When comparing float to float,
508 * we do it as straightforwardly (and long-windedly) as conceivable, so
509 * that, e.g., Python x == y delivers the same result as the platform
510 * C x == y when x and/or y is a NaN.
511 * When mixing float with an integer type, there's no good *uniform* approach.
512 * Converting the double to an integer obviously doesn't work, since we
513 * may lose info from fractional bits. Converting the integer to a double
514 * also has two failure modes: (1) a long int may trigger overflow (too
515 * large to fit in the dynamic range of a C double); (2) even a C long may have
516 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
517 * 63 bits of precision, but a C double probably has only 53), and then
518 * we can falsely claim equality when low-order integer bits are lost by
519 * coercion to double. So this part is painful too.
520 */
521
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522static PyObject*
523float_richcompare(PyObject *v, PyObject *w, int op)
524{
525 double i, j;
526 int r = 0;
527
Tim Peters307fa782004-09-23 08:06:40 +0000528 assert(PyFloat_Check(v));
529 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000530
Tim Peters307fa782004-09-23 08:06:40 +0000531 /* Switch on the type of w. Set i and j to doubles to be compared,
532 * and op to the richcomp to use.
533 */
534 if (PyFloat_Check(w))
535 j = PyFloat_AS_DOUBLE(w);
536
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000537 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000538 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000539 /* If i is an infinity, its magnitude exceeds any
540 * finite integer, so it doesn't matter which int we
541 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000542 */
543 j = 0.0;
544 else
545 goto Unimplemented;
546 }
547
548 else if (PyInt_Check(w)) {
549 long jj = PyInt_AS_LONG(w);
550 /* In the worst realistic case I can imagine, C double is a
551 * Cray single with 48 bits of precision, and long has 64
552 * bits.
553 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000554#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000555 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
556 if (abs >> 48) {
557 /* Needs more than 48 bits. Make it take the
558 * PyLong path.
559 */
560 PyObject *result;
561 PyObject *ww = PyLong_FromLong(jj);
562
563 if (ww == NULL)
564 return NULL;
565 result = float_richcompare(v, ww, op);
566 Py_DECREF(ww);
567 return result;
568 }
569#endif
570 j = (double)jj;
571 assert((long)j == jj);
572 }
573
574 else if (PyLong_Check(w)) {
575 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
576 int wsign = _PyLong_Sign(w);
577 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000578 int exponent;
579
580 if (vsign != wsign) {
581 /* Magnitudes are irrelevant -- the signs alone
582 * determine the outcome.
583 */
584 i = (double)vsign;
585 j = (double)wsign;
586 goto Compare;
587 }
588 /* The signs are the same. */
589 /* Convert w to a double if it fits. In particular, 0 fits. */
590 nbits = _PyLong_NumBits(w);
591 if (nbits == (size_t)-1 && PyErr_Occurred()) {
592 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000593 * to hold the # of bits. Replace with little doubles
594 * that give the same outcome -- w is so large that
595 * its magnitude must exceed the magnitude of any
596 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000597 */
598 PyErr_Clear();
599 i = (double)vsign;
600 assert(wsign != 0);
601 j = wsign * 2.0;
602 goto Compare;
603 }
604 if (nbits <= 48) {
605 j = PyLong_AsDouble(w);
606 /* It's impossible that <= 48 bits overflowed. */
607 assert(j != -1.0 || ! PyErr_Occurred());
608 goto Compare;
609 }
610 assert(wsign != 0); /* else nbits was 0 */
611 assert(vsign != 0); /* if vsign were 0, then since wsign is
612 * not 0, we would have taken the
613 * vsign != wsign branch at the start */
614 /* We want to work with non-negative numbers. */
615 if (vsign < 0) {
616 /* "Multiply both sides" by -1; this also swaps the
617 * comparator.
618 */
619 i = -i;
620 op = _Py_SwappedOp[op];
621 }
622 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000623 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000624 /* exponent is the # of bits in v before the radix point;
625 * we know that nbits (the # of bits in w) > 48 at this point
626 */
627 if (exponent < 0 || (size_t)exponent < nbits) {
628 i = 1.0;
629 j = 2.0;
630 goto Compare;
631 }
632 if ((size_t)exponent > nbits) {
633 i = 2.0;
634 j = 1.0;
635 goto Compare;
636 }
637 /* v and w have the same number of bits before the radix
638 * point. Construct two longs that have the same comparison
639 * outcome.
640 */
641 {
642 double fracpart;
643 double intpart;
644 PyObject *result = NULL;
645 PyObject *one = NULL;
646 PyObject *vv = NULL;
647 PyObject *ww = w;
648
649 if (wsign < 0) {
650 ww = PyNumber_Negative(w);
651 if (ww == NULL)
652 goto Error;
653 }
654 else
655 Py_INCREF(ww);
656
657 fracpart = modf(i, &intpart);
658 vv = PyLong_FromDouble(intpart);
659 if (vv == NULL)
660 goto Error;
661
662 if (fracpart != 0.0) {
663 /* Shift left, and or a 1 bit into vv
664 * to represent the lost fraction.
665 */
666 PyObject *temp;
667
668 one = PyInt_FromLong(1);
669 if (one == NULL)
670 goto Error;
671
672 temp = PyNumber_Lshift(ww, one);
673 if (temp == NULL)
674 goto Error;
675 Py_DECREF(ww);
676 ww = temp;
677
678 temp = PyNumber_Lshift(vv, one);
679 if (temp == NULL)
680 goto Error;
681 Py_DECREF(vv);
682 vv = temp;
683
684 temp = PyNumber_Or(vv, one);
685 if (temp == NULL)
686 goto Error;
687 Py_DECREF(vv);
688 vv = temp;
689 }
690
691 r = PyObject_RichCompareBool(vv, ww, op);
692 if (r < 0)
693 goto Error;
694 result = PyBool_FromLong(r);
695 Error:
696 Py_XDECREF(vv);
697 Py_XDECREF(ww);
698 Py_XDECREF(one);
699 return result;
700 }
701 } /* else if (PyLong_Check(w)) */
702
703 else /* w isn't float, int, or long */
704 goto Unimplemented;
705
706 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000707 PyFPE_START_PROTECT("richcompare", return NULL)
708 switch (op) {
709 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000710 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000711 break;
712 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000713 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000714 break;
715 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000716 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000717 break;
718 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000719 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000720 break;
721 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000722 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000723 break;
724 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000725 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000726 break;
727 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000728 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000729 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000730
731 Unimplemented:
732 Py_INCREF(Py_NotImplemented);
733 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000734}
735
Guido van Rossum9bfef441993-03-29 10:43:31 +0000736static long
Fred Drakefd99de62000-07-09 05:02:18 +0000737float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000738{
Tim Peters39dce292000-08-15 03:34:48 +0000739 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000740}
741
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000743float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000744{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000745 double a,b;
746 CONVERT_TO_DOUBLE(v, a);
747 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000748 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000749 a = a + b;
750 PyFPE_END_PROTECT(a)
751 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752}
753
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000755float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000757 double a,b;
758 CONVERT_TO_DOUBLE(v, a);
759 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000760 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000761 a = a - b;
762 PyFPE_END_PROTECT(a)
763 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764}
765
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000766static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000767float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000769 double a,b;
770 CONVERT_TO_DOUBLE(v, a);
771 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000772 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000773 a = a * b;
774 PyFPE_END_PROTECT(a)
775 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000779float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000781 double a,b;
782 CONVERT_TO_DOUBLE(v, a);
783 CONVERT_TO_DOUBLE(w, b);
784 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000785 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786 return NULL;
787 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000788 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000789 a = a / b;
790 PyFPE_END_PROTECT(a)
791 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792}
793
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000794static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000795float_classic_div(PyObject *v, PyObject *w)
796{
797 double a,b;
798 CONVERT_TO_DOUBLE(v, a);
799 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000800 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000801 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
802 return NULL;
803 if (b == 0.0) {
804 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
805 return NULL;
806 }
807 PyFPE_START_PROTECT("divide", return 0)
808 a = a / b;
809 PyFPE_END_PROTECT(a)
810 return PyFloat_FromDouble(a);
811}
812
813static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000814float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000816 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000817 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000818 CONVERT_TO_DOUBLE(v, vx);
819 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000821 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822 return NULL;
823 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000824 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000825 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000826 /* note: checking mod*wx < 0 is incorrect -- underflows to
827 0 if wx < sqrt(smallest nonzero double) */
828 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000829 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000830 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000831 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000836float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000837{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000838 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000839 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000840 CONVERT_TO_DOUBLE(v, vx);
841 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000842 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000844 return NULL;
845 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000846 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000847 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000848 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000849 exact multiple of wx. But this is fp arithmetic, and fp
850 vx - mod is an approximation; the result is that div may
851 not be an exact integral value after the division, although
852 it will always be very close to one.
853 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000854 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000855 if (mod) {
856 /* ensure the remainder has the same sign as the denominator */
857 if ((wx < 0) != (mod < 0)) {
858 mod += wx;
859 div -= 1.0;
860 }
861 }
862 else {
863 /* the remainder is zero, and in the presence of signed zeroes
864 fmod returns different results across platforms; ensure
865 it has the same sign as the denominator; we'd like to do
866 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000867 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000868 if (wx < 0.0)
869 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000870 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000871 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000872 if (div) {
873 floordiv = floor(div);
874 if (div - floordiv > 0.5)
875 floordiv += 1.0;
876 }
877 else {
878 /* div is zero - get the same sign as the true quotient */
879 div *= div; /* hide "div = +0" from optimizers */
880 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
881 }
882 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000883 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000884}
885
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000886static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000887float_floor_div(PyObject *v, PyObject *w)
888{
889 PyObject *t, *r;
890
891 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000892 if (t == NULL || t == Py_NotImplemented)
893 return t;
894 assert(PyTuple_CheckExact(t));
895 r = PyTuple_GET_ITEM(t, 0);
896 Py_INCREF(r);
897 Py_DECREF(t);
898 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000899}
900
901static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000902float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000903{
904 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000905
906 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000907 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000908 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000909 return NULL;
910 }
911
Neil Schemenauer32117e52001-01-04 01:44:34 +0000912 CONVERT_TO_DOUBLE(v, iv);
913 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000914
915 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000916 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000917 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000918 }
Tim Peters96685bf2001-08-23 22:31:37 +0000919 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000920 if (iw < 0.0) {
921 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000922 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000923 return NULL;
924 }
925 return PyFloat_FromDouble(0.0);
926 }
Tim Peterse87568d2003-05-24 20:18:24 +0000927 if (iv < 0.0) {
928 /* Whether this is an error is a mess, and bumps into libm
929 * bugs so we have to figure it out ourselves.
930 */
931 if (iw != floor(iw)) {
932 PyErr_SetString(PyExc_ValueError, "negative number "
933 "cannot be raised to a fractional power");
934 return NULL;
935 }
936 /* iw is an exact integer, albeit perhaps a very large one.
937 * -1 raised to an exact integer should never be exceptional.
938 * Alas, some libms (chiefly glibc as of early 2003) return
939 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
940 * happen to be representable in a *C* integer. That's a
941 * bug; we let that slide in math.pow() (which currently
942 * reflects all platform accidents), but not for Python's **.
943 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000944 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000945 /* Return 1 if iw is even, -1 if iw is odd; there's
946 * no guarantee that any C integral type is big
947 * enough to hold iw, so we have to check this
948 * indirectly.
949 */
950 ix = floor(iw * 0.5) * 2.0;
951 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
952 }
953 /* Else iv != -1.0, and overflow or underflow are possible.
954 * Unless we're to write pow() ourselves, we have to trust
955 * the platform to do this correctly.
956 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000957 }
Tim Peters96685bf2001-08-23 22:31:37 +0000958 errno = 0;
959 PyFPE_START_PROTECT("pow", return NULL)
960 ix = pow(iv, iw);
961 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000962 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000963 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000964 /* We don't expect any errno value other than ERANGE, but
965 * the range of libm bugs appears unbounded.
966 */
Alex Martelli348dc882006-08-23 22:17:59 +0000967 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
968 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000969 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000970 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000971 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000972}
973
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000974static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000975float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000976{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000977 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000978}
979
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000980static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000981float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000982{
Tim Peters0280cf72001-09-11 21:53:35 +0000983 if (PyFloat_CheckExact(v)) {
984 Py_INCREF(v);
985 return (PyObject *)v;
986 }
987 else
988 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000989}
990
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000991static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000992float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000993{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000994 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000995}
996
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000997static int
Fred Drakefd99de62000-07-09 05:02:18 +0000998float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000999{
1000 return v->ob_fval != 0.0;
1001}
1002
Guido van Rossum234f9421993-06-17 12:35:49 +00001003static int
Fred Drakefd99de62000-07-09 05:02:18 +00001004float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001005{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006 if (PyInt_Check(*pw)) {
1007 long x = PyInt_AsLong(*pw);
1008 *pw = PyFloat_FromDouble((double)x);
1009 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001010 return 0;
1011 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001012 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001013 double x = PyLong_AsDouble(*pw);
1014 if (x == -1.0 && PyErr_Occurred())
1015 return -1;
1016 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001017 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001018 return 0;
1019 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001020 else if (PyFloat_Check(*pw)) {
1021 Py_INCREF(*pv);
1022 Py_INCREF(*pw);
1023 return 0;
1024 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001025 return 1; /* Can't do it */
1026}
1027
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00001029float_long(PyObject *v)
1030{
1031 double x = PyFloat_AsDouble(v);
1032 return PyLong_FromDouble(x);
1033}
1034
1035static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001036float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001037{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001039 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001040
1041 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001042 /* Try to get out cheap if this fits in a Python int. The attempt
1043 * to cast to long must be protected, as C doesn't define what
1044 * happens if the double is too big to fit in a long. Some rare
1045 * systems raise an exception then (RISCOS was mentioned as one,
1046 * and someone using a non-default option on Sun also bumped into
1047 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1048 * still be vulnerable: if a long has more bits of precision than
1049 * a double, casting MIN/MAX to double may yield an approximation,
1050 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1051 * yield true from the C expression wholepart<=LONG_MAX, despite
1052 * that wholepart is actually greater than LONG_MAX.
1053 */
1054 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1055 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001056 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001057 }
1058 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001059}
1060
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001061static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001062float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001064 if (PyFloat_CheckExact(v))
1065 Py_INCREF(v);
1066 else
1067 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001068 return v;
1069}
1070
1071
Jeremy Hylton938ace62002-07-17 16:30:39 +00001072static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001073float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1074
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075static PyObject *
1076float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1077{
1078 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001079 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
Guido van Rossumbef14172001-08-29 15:47:46 +00001081 if (type != &PyFloat_Type)
1082 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1084 return NULL;
1085 if (PyString_Check(x))
1086 return PyFloat_FromString(x, NULL);
1087 return PyNumber_Float(x);
1088}
1089
Guido van Rossumbef14172001-08-29 15:47:46 +00001090/* Wimpy, slow approach to tp_new calls for subtypes of float:
1091 first create a regular float from whatever arguments we got,
1092 then allocate a subtype instance and initialize its ob_fval
1093 from the regular float. The regular float is then thrown away.
1094*/
1095static PyObject *
1096float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1097{
Anthony Baxter377be112006-04-11 06:54:30 +00001098 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001099
1100 assert(PyType_IsSubtype(type, &PyFloat_Type));
1101 tmp = float_new(&PyFloat_Type, args, kwds);
1102 if (tmp == NULL)
1103 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001104 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001105 newobj = type->tp_alloc(type, 0);
1106 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001107 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001108 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001109 }
Anthony Baxter377be112006-04-11 06:54:30 +00001110 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001111 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001112 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001113}
1114
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001115static PyObject *
1116float_getnewargs(PyFloatObject *v)
1117{
1118 return Py_BuildValue("(d)", v->ob_fval);
1119}
1120
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001121/* this is for the benefit of the pack/unpack routines below */
1122
1123typedef enum {
1124 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1125} float_format_type;
1126
1127static float_format_type double_format, float_format;
1128static float_format_type detected_double_format, detected_float_format;
1129
1130static PyObject *
1131float_getformat(PyTypeObject *v, PyObject* arg)
1132{
1133 char* s;
1134 float_format_type r;
1135
1136 if (!PyString_Check(arg)) {
1137 PyErr_Format(PyExc_TypeError,
1138 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis68192102007-07-21 06:55:02 +00001139 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001140 return NULL;
1141 }
1142 s = PyString_AS_STRING(arg);
1143 if (strcmp(s, "double") == 0) {
1144 r = double_format;
1145 }
1146 else if (strcmp(s, "float") == 0) {
1147 r = float_format;
1148 }
1149 else {
1150 PyErr_SetString(PyExc_ValueError,
1151 "__getformat__() argument 1 must be "
1152 "'double' or 'float'");
1153 return NULL;
1154 }
1155
1156 switch (r) {
1157 case unknown_format:
1158 return PyString_FromString("unknown");
1159 case ieee_little_endian_format:
1160 return PyString_FromString("IEEE, little-endian");
1161 case ieee_big_endian_format:
1162 return PyString_FromString("IEEE, big-endian");
1163 default:
1164 Py_FatalError("insane float_format or double_format");
1165 return NULL;
1166 }
1167}
1168
1169PyDoc_STRVAR(float_getformat_doc,
1170"float.__getformat__(typestr) -> string\n"
1171"\n"
1172"You probably don't want to use this function. It exists mainly to be\n"
1173"used in Python's test suite.\n"
1174"\n"
1175"typestr must be 'double' or 'float'. This function returns whichever of\n"
1176"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1177"format of floating point numbers used by the C type named by typestr.");
1178
1179static PyObject *
1180float_setformat(PyTypeObject *v, PyObject* args)
1181{
1182 char* typestr;
1183 char* format;
1184 float_format_type f;
1185 float_format_type detected;
1186 float_format_type *p;
1187
1188 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1189 return NULL;
1190
1191 if (strcmp(typestr, "double") == 0) {
1192 p = &double_format;
1193 detected = detected_double_format;
1194 }
1195 else if (strcmp(typestr, "float") == 0) {
1196 p = &float_format;
1197 detected = detected_float_format;
1198 }
1199 else {
1200 PyErr_SetString(PyExc_ValueError,
1201 "__setformat__() argument 1 must "
1202 "be 'double' or 'float'");
1203 return NULL;
1204 }
1205
1206 if (strcmp(format, "unknown") == 0) {
1207 f = unknown_format;
1208 }
1209 else if (strcmp(format, "IEEE, little-endian") == 0) {
1210 f = ieee_little_endian_format;
1211 }
1212 else if (strcmp(format, "IEEE, big-endian") == 0) {
1213 f = ieee_big_endian_format;
1214 }
1215 else {
1216 PyErr_SetString(PyExc_ValueError,
1217 "__setformat__() argument 2 must be "
1218 "'unknown', 'IEEE, little-endian' or "
1219 "'IEEE, big-endian'");
1220 return NULL;
1221
1222 }
1223
1224 if (f != unknown_format && f != detected) {
1225 PyErr_Format(PyExc_ValueError,
1226 "can only set %s format to 'unknown' or the "
1227 "detected platform value", typestr);
1228 return NULL;
1229 }
1230
1231 *p = f;
1232 Py_RETURN_NONE;
1233}
1234
1235PyDoc_STRVAR(float_setformat_doc,
1236"float.__setformat__(typestr, fmt) -> None\n"
1237"\n"
1238"You probably don't want to use this function. It exists mainly to be\n"
1239"used in Python's test suite.\n"
1240"\n"
1241"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1242"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1243"one of the latter two if it appears to match the underlying C reality.\n"
1244"\n"
1245"Overrides the automatic determination of C-level floating point type.\n"
1246"This affects how floats are converted to and from binary strings.");
1247
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001248static PyMethodDef float_methods[] = {
1249 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001250 {"__getformat__", (PyCFunction)float_getformat,
1251 METH_O|METH_CLASS, float_getformat_doc},
1252 {"__setformat__", (PyCFunction)float_setformat,
1253 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001254 {NULL, NULL} /* sentinel */
1255};
1256
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001257PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258"float(x) -> floating point number\n\
1259\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001260Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001261
1262
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001263static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001264 float_add, /*nb_add*/
1265 float_sub, /*nb_subtract*/
1266 float_mul, /*nb_multiply*/
1267 float_classic_div, /*nb_divide*/
1268 float_rem, /*nb_remainder*/
1269 float_divmod, /*nb_divmod*/
1270 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001271 (unaryfunc)float_neg, /*nb_negative*/
1272 (unaryfunc)float_pos, /*nb_positive*/
1273 (unaryfunc)float_abs, /*nb_absolute*/
1274 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001275 0, /*nb_invert*/
1276 0, /*nb_lshift*/
1277 0, /*nb_rshift*/
1278 0, /*nb_and*/
1279 0, /*nb_xor*/
1280 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001281 float_coerce, /*nb_coerce*/
1282 float_int, /*nb_int*/
1283 float_long, /*nb_long*/
1284 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001285 0, /* nb_oct */
1286 0, /* nb_hex */
1287 0, /* nb_inplace_add */
1288 0, /* nb_inplace_subtract */
1289 0, /* nb_inplace_multiply */
1290 0, /* nb_inplace_divide */
1291 0, /* nb_inplace_remainder */
1292 0, /* nb_inplace_power */
1293 0, /* nb_inplace_lshift */
1294 0, /* nb_inplace_rshift */
1295 0, /* nb_inplace_and */
1296 0, /* nb_inplace_xor */
1297 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001298 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001299 float_div, /* nb_true_divide */
1300 0, /* nb_inplace_floor_divide */
1301 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001302};
1303
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001305 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001306 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001308 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 (destructor)float_dealloc, /* tp_dealloc */
1310 (printfunc)float_print, /* tp_print */
1311 0, /* tp_getattr */
1312 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001313 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 (reprfunc)float_repr, /* tp_repr */
1315 &float_as_number, /* tp_as_number */
1316 0, /* tp_as_sequence */
1317 0, /* tp_as_mapping */
1318 (hashfunc)float_hash, /* tp_hash */
1319 0, /* tp_call */
1320 (reprfunc)float_str, /* tp_str */
1321 PyObject_GenericGetAttr, /* tp_getattro */
1322 0, /* tp_setattro */
1323 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001324 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1325 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 float_doc, /* tp_doc */
1327 0, /* tp_traverse */
1328 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001329 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 0, /* tp_weaklistoffset */
1331 0, /* tp_iter */
1332 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001333 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334 0, /* tp_members */
1335 0, /* tp_getset */
1336 0, /* tp_base */
1337 0, /* tp_dict */
1338 0, /* tp_descr_get */
1339 0, /* tp_descr_set */
1340 0, /* tp_dictoffset */
1341 0, /* tp_init */
1342 0, /* tp_alloc */
1343 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001344};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001345
1346void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001347_PyFloat_Init(void)
1348{
1349 /* We attempt to determine if this machine is using IEEE
1350 floating point formats by peering at the bits of some
1351 carefully chosen values. If it looks like we are on an
1352 IEEE platform, the float packing/unpacking routines can
1353 just copy bits, if not they resort to arithmetic & shifts
1354 and masks. The shifts & masks approach works on all finite
1355 values, but what happens to infinities, NaNs and signed
1356 zeroes on packing is an accident, and attempting to unpack
1357 a NaN or an infinity will raise an exception.
1358
1359 Note that if we're on some whacked-out platform which uses
1360 IEEE formats but isn't strictly little-endian or big-
1361 endian, we will fall back to the portable shifts & masks
1362 method. */
1363
1364#if SIZEOF_DOUBLE == 8
1365 {
1366 double x = 9006104071832581.0;
1367 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1368 detected_double_format = ieee_big_endian_format;
1369 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1370 detected_double_format = ieee_little_endian_format;
1371 else
1372 detected_double_format = unknown_format;
1373 }
1374#else
1375 detected_double_format = unknown_format;
1376#endif
1377
1378#if SIZEOF_FLOAT == 4
1379 {
1380 float y = 16711938.0;
1381 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1382 detected_float_format = ieee_big_endian_format;
1383 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1384 detected_float_format = ieee_little_endian_format;
1385 else
1386 detected_float_format = unknown_format;
1387 }
1388#else
1389 detected_float_format = unknown_format;
1390#endif
1391
1392 double_format = detected_double_format;
1393 float_format = detected_float_format;
Christian Heimes284d9272007-12-10 22:28:56 +00001394
1395 /* Initialize floating point repr */
1396 _PyFloat_DigitsInit();
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001397}
1398
1399void
Fred Drakefd99de62000-07-09 05:02:18 +00001400PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001401{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001402 PyFloatObject *p;
1403 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001404 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001405 int bc, bf; /* block count, number of freed blocks */
1406 int frem, fsum; /* remaining unfreed floats per block, total */
1407
1408 bc = 0;
1409 bf = 0;
1410 fsum = 0;
1411 list = block_list;
1412 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001413 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001414 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001415 bc++;
1416 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001417 for (i = 0, p = &list->objects[0];
1418 i < N_FLOATOBJECTS;
1419 i++, p++) {
Martin v. Löwis68192102007-07-21 06:55:02 +00001420 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001421 frem++;
1422 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001423 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001424 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001425 list->next = block_list;
1426 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001427 for (i = 0, p = &list->objects[0];
1428 i < N_FLOATOBJECTS;
1429 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001430 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis68192102007-07-21 06:55:02 +00001431 Py_Refcnt(p) == 0) {
1432 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001433 free_list;
1434 free_list = p;
1435 }
1436 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001437 }
1438 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001439 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001440 bf++;
1441 }
1442 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001443 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001444 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001445 if (!Py_VerboseFlag)
1446 return;
1447 fprintf(stderr, "# cleanup floats");
1448 if (!fsum) {
1449 fprintf(stderr, "\n");
1450 }
1451 else {
1452 fprintf(stderr,
1453 ": %d unfreed float%s in %d out of %d block%s\n",
1454 fsum, fsum == 1 ? "" : "s",
1455 bc - bf, bc, bc == 1 ? "" : "s");
1456 }
1457 if (Py_VerboseFlag > 1) {
1458 list = block_list;
1459 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001460 for (i = 0, p = &list->objects[0];
1461 i < N_FLOATOBJECTS;
1462 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001463 if (PyFloat_CheckExact(p) &&
Martin v. Löwis68192102007-07-21 06:55:02 +00001464 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001465 char buf[100];
1466 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001467 /* XXX(twouters) cast refcount to
1468 long until %zd is universally
1469 available
1470 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001471 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001472 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis68192102007-07-21 06:55:02 +00001473 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001474 }
1475 }
1476 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001477 }
1478 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001479}
Tim Peters9905b942003-03-20 20:53:32 +00001480
1481/*----------------------------------------------------------------------------
1482 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1483 *
1484 * TODO: On platforms that use the standard IEEE-754 single and double
1485 * formats natively, these routines could simply copy the bytes.
1486 */
1487int
1488_PyFloat_Pack4(double x, unsigned char *p, int le)
1489{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001490 if (float_format == unknown_format) {
1491 unsigned char sign;
1492 int e;
1493 double f;
1494 unsigned int fbits;
1495 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001496
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001497 if (le) {
1498 p += 3;
1499 incr = -1;
1500 }
Tim Peters9905b942003-03-20 20:53:32 +00001501
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001502 if (x < 0) {
1503 sign = 1;
1504 x = -x;
1505 }
1506 else
1507 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001508
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001509 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001510
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001511 /* Normalize f to be in the range [1.0, 2.0) */
1512 if (0.5 <= f && f < 1.0) {
1513 f *= 2.0;
1514 e--;
1515 }
1516 else if (f == 0.0)
1517 e = 0;
1518 else {
1519 PyErr_SetString(PyExc_SystemError,
1520 "frexp() result out of range");
1521 return -1;
1522 }
1523
1524 if (e >= 128)
1525 goto Overflow;
1526 else if (e < -126) {
1527 /* Gradual underflow */
1528 f = ldexp(f, 126 + e);
1529 e = 0;
1530 }
1531 else if (!(e == 0 && f == 0.0)) {
1532 e += 127;
1533 f -= 1.0; /* Get rid of leading 1 */
1534 }
1535
1536 f *= 8388608.0; /* 2**23 */
1537 fbits = (unsigned int)(f + 0.5); /* Round */
1538 assert(fbits <= 8388608);
1539 if (fbits >> 23) {
1540 /* The carry propagated out of a string of 23 1 bits. */
1541 fbits = 0;
1542 ++e;
1543 if (e >= 255)
1544 goto Overflow;
1545 }
1546
1547 /* First byte */
1548 *p = (sign << 7) | (e >> 1);
1549 p += incr;
1550
1551 /* Second byte */
1552 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1553 p += incr;
1554
1555 /* Third byte */
1556 *p = (fbits >> 8) & 0xFF;
1557 p += incr;
1558
1559 /* Fourth byte */
1560 *p = fbits & 0xFF;
1561
1562 /* Done */
1563 return 0;
1564
1565 Overflow:
1566 PyErr_SetString(PyExc_OverflowError,
1567 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001568 return -1;
1569 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001570 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001571 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001572 const char *s = (char*)&y;
1573 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001574
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001575 if ((float_format == ieee_little_endian_format && !le)
1576 || (float_format == ieee_big_endian_format && le)) {
1577 p += 3;
1578 incr = -1;
1579 }
1580
1581 for (i = 0; i < 4; i++) {
1582 *p = *s++;
1583 p += incr;
1584 }
1585 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001586 }
Tim Peters9905b942003-03-20 20:53:32 +00001587}
1588
1589int
1590_PyFloat_Pack8(double x, unsigned char *p, int le)
1591{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001592 if (double_format == unknown_format) {
1593 unsigned char sign;
1594 int e;
1595 double f;
1596 unsigned int fhi, flo;
1597 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001598
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001599 if (le) {
1600 p += 7;
1601 incr = -1;
1602 }
Tim Peters9905b942003-03-20 20:53:32 +00001603
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001604 if (x < 0) {
1605 sign = 1;
1606 x = -x;
1607 }
1608 else
1609 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001610
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001612
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613 /* Normalize f to be in the range [1.0, 2.0) */
1614 if (0.5 <= f && f < 1.0) {
1615 f *= 2.0;
1616 e--;
1617 }
1618 else if (f == 0.0)
1619 e = 0;
1620 else {
1621 PyErr_SetString(PyExc_SystemError,
1622 "frexp() result out of range");
1623 return -1;
1624 }
1625
1626 if (e >= 1024)
1627 goto Overflow;
1628 else if (e < -1022) {
1629 /* Gradual underflow */
1630 f = ldexp(f, 1022 + e);
1631 e = 0;
1632 }
1633 else if (!(e == 0 && f == 0.0)) {
1634 e += 1023;
1635 f -= 1.0; /* Get rid of leading 1 */
1636 }
1637
1638 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1639 f *= 268435456.0; /* 2**28 */
1640 fhi = (unsigned int)f; /* Truncate */
1641 assert(fhi < 268435456);
1642
1643 f -= (double)fhi;
1644 f *= 16777216.0; /* 2**24 */
1645 flo = (unsigned int)(f + 0.5); /* Round */
1646 assert(flo <= 16777216);
1647 if (flo >> 24) {
1648 /* The carry propagated out of a string of 24 1 bits. */
1649 flo = 0;
1650 ++fhi;
1651 if (fhi >> 28) {
1652 /* And it also progagated out of the next 28 bits. */
1653 fhi = 0;
1654 ++e;
1655 if (e >= 2047)
1656 goto Overflow;
1657 }
1658 }
1659
1660 /* First byte */
1661 *p = (sign << 7) | (e >> 4);
1662 p += incr;
1663
1664 /* Second byte */
1665 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1666 p += incr;
1667
1668 /* Third byte */
1669 *p = (fhi >> 16) & 0xFF;
1670 p += incr;
1671
1672 /* Fourth byte */
1673 *p = (fhi >> 8) & 0xFF;
1674 p += incr;
1675
1676 /* Fifth byte */
1677 *p = fhi & 0xFF;
1678 p += incr;
1679
1680 /* Sixth byte */
1681 *p = (flo >> 16) & 0xFF;
1682 p += incr;
1683
1684 /* Seventh byte */
1685 *p = (flo >> 8) & 0xFF;
1686 p += incr;
1687
1688 /* Eighth byte */
1689 *p = flo & 0xFF;
1690 p += incr;
1691
1692 /* Done */
1693 return 0;
1694
1695 Overflow:
1696 PyErr_SetString(PyExc_OverflowError,
1697 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001698 return -1;
1699 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001700 else {
1701 const char *s = (char*)&x;
1702 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001703
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001704 if ((double_format == ieee_little_endian_format && !le)
1705 || (double_format == ieee_big_endian_format && le)) {
1706 p += 7;
1707 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001708 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001709
1710 for (i = 0; i < 8; i++) {
1711 *p = *s++;
1712 p += incr;
1713 }
1714 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001715 }
Tim Peters9905b942003-03-20 20:53:32 +00001716}
1717
1718double
1719_PyFloat_Unpack4(const unsigned char *p, int le)
1720{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721 if (float_format == unknown_format) {
1722 unsigned char sign;
1723 int e;
1724 unsigned int f;
1725 double x;
1726 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001727
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001728 if (le) {
1729 p += 3;
1730 incr = -1;
1731 }
1732
1733 /* First byte */
1734 sign = (*p >> 7) & 1;
1735 e = (*p & 0x7F) << 1;
1736 p += incr;
1737
1738 /* Second byte */
1739 e |= (*p >> 7) & 1;
1740 f = (*p & 0x7F) << 16;
1741 p += incr;
1742
1743 if (e == 255) {
1744 PyErr_SetString(
1745 PyExc_ValueError,
1746 "can't unpack IEEE 754 special value "
1747 "on non-IEEE platform");
1748 return -1;
1749 }
1750
1751 /* Third byte */
1752 f |= *p << 8;
1753 p += incr;
1754
1755 /* Fourth byte */
1756 f |= *p;
1757
1758 x = (double)f / 8388608.0;
1759
1760 /* XXX This sadly ignores Inf/NaN issues */
1761 if (e == 0)
1762 e = -126;
1763 else {
1764 x += 1.0;
1765 e -= 127;
1766 }
1767 x = ldexp(x, e);
1768
1769 if (sign)
1770 x = -x;
1771
1772 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001773 }
Tim Peters9905b942003-03-20 20:53:32 +00001774 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001775 float x;
1776
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777 if ((float_format == ieee_little_endian_format && !le)
1778 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001779 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001780 char *d = &buf[3];
1781 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001782
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001783 for (i = 0; i < 4; i++) {
1784 *d-- = *p++;
1785 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001786 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001787 }
1788 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001789 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001790 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001791
1792 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001793 }
Tim Peters9905b942003-03-20 20:53:32 +00001794}
1795
1796double
1797_PyFloat_Unpack8(const unsigned char *p, int le)
1798{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001799 if (double_format == unknown_format) {
1800 unsigned char sign;
1801 int e;
1802 unsigned int fhi, flo;
1803 double x;
1804 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001805
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001806 if (le) {
1807 p += 7;
1808 incr = -1;
1809 }
1810
1811 /* First byte */
1812 sign = (*p >> 7) & 1;
1813 e = (*p & 0x7F) << 4;
1814
1815 p += incr;
1816
1817 /* Second byte */
1818 e |= (*p >> 4) & 0xF;
1819 fhi = (*p & 0xF) << 24;
1820 p += incr;
1821
1822 if (e == 2047) {
1823 PyErr_SetString(
1824 PyExc_ValueError,
1825 "can't unpack IEEE 754 special value "
1826 "on non-IEEE platform");
1827 return -1.0;
1828 }
1829
1830 /* Third byte */
1831 fhi |= *p << 16;
1832 p += incr;
1833
1834 /* Fourth byte */
1835 fhi |= *p << 8;
1836 p += incr;
1837
1838 /* Fifth byte */
1839 fhi |= *p;
1840 p += incr;
1841
1842 /* Sixth byte */
1843 flo = *p << 16;
1844 p += incr;
1845
1846 /* Seventh byte */
1847 flo |= *p << 8;
1848 p += incr;
1849
1850 /* Eighth byte */
1851 flo |= *p;
1852
1853 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1854 x /= 268435456.0; /* 2**28 */
1855
1856 if (e == 0)
1857 e = -1022;
1858 else {
1859 x += 1.0;
1860 e -= 1023;
1861 }
1862 x = ldexp(x, e);
1863
1864 if (sign)
1865 x = -x;
1866
1867 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001868 }
Tim Peters9905b942003-03-20 20:53:32 +00001869 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001870 double x;
1871
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001872 if ((double_format == ieee_little_endian_format && !le)
1873 || (double_format == ieee_big_endian_format && le)) {
1874 char buf[8];
1875 char *d = &buf[7];
1876 int i;
1877
1878 for (i = 0; i < 8; i++) {
1879 *d-- = *p++;
1880 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001881 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001882 }
1883 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001884 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001885 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001886
1887 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001888 }
Tim Peters9905b942003-03-20 20:53:32 +00001889}