blob: c76956a6698cfd1ae31f2c43b60b39e48d71ca2c [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
Neil Schemenauer32117e52001-01-04 01:44:34 +0000309/* Macro and helper that convert PyObject obj to a C double and store
310 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000311 slot function. If conversion to double raises an exception, obj is
312 set to NULL, and the function invoking this macro returns NULL. If
313 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
314 stored in obj, and returned from the function invoking this macro.
315*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000316#define CONVERT_TO_DOUBLE(obj, dbl) \
317 if (PyFloat_Check(obj)) \
318 dbl = PyFloat_AS_DOUBLE(obj); \
319 else if (convert_to_double(&(obj), &(dbl)) < 0) \
320 return obj;
321
322static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000323convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000324{
325 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000326
Neil Schemenauer32117e52001-01-04 01:44:34 +0000327 if (PyInt_Check(obj)) {
328 *dbl = (double)PyInt_AS_LONG(obj);
329 }
330 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000331 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000332 if (*dbl == -1.0 && PyErr_Occurred()) {
333 *v = NULL;
334 return -1;
335 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000336 }
337 else {
338 Py_INCREF(Py_NotImplemented);
339 *v = Py_NotImplemented;
340 return -1;
341 }
342 return 0;
343}
344
Guido van Rossum57072eb1999-12-23 19:00:28 +0000345/* Precisions used by repr() and str(), respectively.
346
347 The repr() precision (17 significant decimal digits) is the minimal number
348 that is guaranteed to have enough precision so that if the number is read
349 back in the exact same binary value is recreated. This is true for IEEE
350 floating point by design, and also happens to work for all other modern
351 hardware.
352
353 The str() precision is chosen so that in most cases, the rounding noise
354 created by various operations is suppressed, while giving plenty of
355 precision for practical use.
356
357*/
358
359#define PREC_REPR 17
360#define PREC_STR 12
361
Tim Peters97019e42001-11-28 22:43:45 +0000362/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
363 XXX they pass a char buffer without passing a length.
364*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000365void
Fred Drakefd99de62000-07-09 05:02:18 +0000366PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000367{
Tim Peters97019e42001-11-28 22:43:45 +0000368 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000369}
370
Tim Peters72f98e92001-05-08 15:19:57 +0000371void
372PyFloat_AsReprString(char *buf, PyFloatObject *v)
373{
Tim Peters97019e42001-11-28 22:43:45 +0000374 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000375}
376
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000377/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000378static int
Fred Drakefd99de62000-07-09 05:02:18 +0000379float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380{
381 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000382 format_float(buf, sizeof(buf), v,
383 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000384 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000386 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000387 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388}
389
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000391float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392{
393 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000394 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000395 return PyString_FromString(buf);
396}
397
398static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000399float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000400{
401 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000402 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Tim Peters307fa782004-09-23 08:06:40 +0000406/* Comparison is pretty much a nightmare. When comparing float to float,
407 * we do it as straightforwardly (and long-windedly) as conceivable, so
408 * that, e.g., Python x == y delivers the same result as the platform
409 * C x == y when x and/or y is a NaN.
410 * When mixing float with an integer type, there's no good *uniform* approach.
411 * Converting the double to an integer obviously doesn't work, since we
412 * may lose info from fractional bits. Converting the integer to a double
413 * also has two failure modes: (1) a long int may trigger overflow (too
414 * large to fit in the dynamic range of a C double); (2) even a C long may have
415 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
416 * 63 bits of precision, but a C double probably has only 53), and then
417 * we can falsely claim equality when low-order integer bits are lost by
418 * coercion to double. So this part is painful too.
419 */
420
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000421static PyObject*
422float_richcompare(PyObject *v, PyObject *w, int op)
423{
424 double i, j;
425 int r = 0;
426
Tim Peters307fa782004-09-23 08:06:40 +0000427 assert(PyFloat_Check(v));
428 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000429
Tim Peters307fa782004-09-23 08:06:40 +0000430 /* Switch on the type of w. Set i and j to doubles to be compared,
431 * and op to the richcomp to use.
432 */
433 if (PyFloat_Check(w))
434 j = PyFloat_AS_DOUBLE(w);
435
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000436 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000437 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000438 /* If i is an infinity, its magnitude exceeds any
439 * finite integer, so it doesn't matter which int we
440 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000441 */
442 j = 0.0;
443 else
444 goto Unimplemented;
445 }
446
447 else if (PyInt_Check(w)) {
448 long jj = PyInt_AS_LONG(w);
449 /* In the worst realistic case I can imagine, C double is a
450 * Cray single with 48 bits of precision, and long has 64
451 * bits.
452 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000453#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000454 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
455 if (abs >> 48) {
456 /* Needs more than 48 bits. Make it take the
457 * PyLong path.
458 */
459 PyObject *result;
460 PyObject *ww = PyLong_FromLong(jj);
461
462 if (ww == NULL)
463 return NULL;
464 result = float_richcompare(v, ww, op);
465 Py_DECREF(ww);
466 return result;
467 }
468#endif
469 j = (double)jj;
470 assert((long)j == jj);
471 }
472
473 else if (PyLong_Check(w)) {
474 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
475 int wsign = _PyLong_Sign(w);
476 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000477 int exponent;
478
479 if (vsign != wsign) {
480 /* Magnitudes are irrelevant -- the signs alone
481 * determine the outcome.
482 */
483 i = (double)vsign;
484 j = (double)wsign;
485 goto Compare;
486 }
487 /* The signs are the same. */
488 /* Convert w to a double if it fits. In particular, 0 fits. */
489 nbits = _PyLong_NumBits(w);
490 if (nbits == (size_t)-1 && PyErr_Occurred()) {
491 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000492 * to hold the # of bits. Replace with little doubles
493 * that give the same outcome -- w is so large that
494 * its magnitude must exceed the magnitude of any
495 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000496 */
497 PyErr_Clear();
498 i = (double)vsign;
499 assert(wsign != 0);
500 j = wsign * 2.0;
501 goto Compare;
502 }
503 if (nbits <= 48) {
504 j = PyLong_AsDouble(w);
505 /* It's impossible that <= 48 bits overflowed. */
506 assert(j != -1.0 || ! PyErr_Occurred());
507 goto Compare;
508 }
509 assert(wsign != 0); /* else nbits was 0 */
510 assert(vsign != 0); /* if vsign were 0, then since wsign is
511 * not 0, we would have taken the
512 * vsign != wsign branch at the start */
513 /* We want to work with non-negative numbers. */
514 if (vsign < 0) {
515 /* "Multiply both sides" by -1; this also swaps the
516 * comparator.
517 */
518 i = -i;
519 op = _Py_SwappedOp[op];
520 }
521 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000522 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000523 /* exponent is the # of bits in v before the radix point;
524 * we know that nbits (the # of bits in w) > 48 at this point
525 */
526 if (exponent < 0 || (size_t)exponent < nbits) {
527 i = 1.0;
528 j = 2.0;
529 goto Compare;
530 }
531 if ((size_t)exponent > nbits) {
532 i = 2.0;
533 j = 1.0;
534 goto Compare;
535 }
536 /* v and w have the same number of bits before the radix
537 * point. Construct two longs that have the same comparison
538 * outcome.
539 */
540 {
541 double fracpart;
542 double intpart;
543 PyObject *result = NULL;
544 PyObject *one = NULL;
545 PyObject *vv = NULL;
546 PyObject *ww = w;
547
548 if (wsign < 0) {
549 ww = PyNumber_Negative(w);
550 if (ww == NULL)
551 goto Error;
552 }
553 else
554 Py_INCREF(ww);
555
556 fracpart = modf(i, &intpart);
557 vv = PyLong_FromDouble(intpart);
558 if (vv == NULL)
559 goto Error;
560
561 if (fracpart != 0.0) {
562 /* Shift left, and or a 1 bit into vv
563 * to represent the lost fraction.
564 */
565 PyObject *temp;
566
567 one = PyInt_FromLong(1);
568 if (one == NULL)
569 goto Error;
570
571 temp = PyNumber_Lshift(ww, one);
572 if (temp == NULL)
573 goto Error;
574 Py_DECREF(ww);
575 ww = temp;
576
577 temp = PyNumber_Lshift(vv, one);
578 if (temp == NULL)
579 goto Error;
580 Py_DECREF(vv);
581 vv = temp;
582
583 temp = PyNumber_Or(vv, one);
584 if (temp == NULL)
585 goto Error;
586 Py_DECREF(vv);
587 vv = temp;
588 }
589
590 r = PyObject_RichCompareBool(vv, ww, op);
591 if (r < 0)
592 goto Error;
593 result = PyBool_FromLong(r);
594 Error:
595 Py_XDECREF(vv);
596 Py_XDECREF(ww);
597 Py_XDECREF(one);
598 return result;
599 }
600 } /* else if (PyLong_Check(w)) */
601
602 else /* w isn't float, int, or long */
603 goto Unimplemented;
604
605 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000606 PyFPE_START_PROTECT("richcompare", return NULL)
607 switch (op) {
608 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000609 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000610 break;
611 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000612 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000613 break;
614 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000615 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000616 break;
617 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000618 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000619 break;
620 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000621 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000622 break;
623 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000624 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000625 break;
626 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000627 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000628 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000629
630 Unimplemented:
631 Py_INCREF(Py_NotImplemented);
632 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633}
634
Guido van Rossum9bfef441993-03-29 10:43:31 +0000635static long
Fred Drakefd99de62000-07-09 05:02:18 +0000636float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000637{
Tim Peters39dce292000-08-15 03:34:48 +0000638 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000639}
640
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000641static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000642float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000644 double a,b;
645 CONVERT_TO_DOUBLE(v, a);
646 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000647 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000648 a = a + b;
649 PyFPE_END_PROTECT(a)
650 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651}
652
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000654float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000656 double a,b;
657 CONVERT_TO_DOUBLE(v, a);
658 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000659 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000660 a = a - b;
661 PyFPE_END_PROTECT(a)
662 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000663}
664
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000666float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000668 double a,b;
669 CONVERT_TO_DOUBLE(v, a);
670 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000671 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000672 a = a * b;
673 PyFPE_END_PROTECT(a)
674 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675}
676
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000678float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000680 double a,b;
681 CONVERT_TO_DOUBLE(v, a);
682 CONVERT_TO_DOUBLE(w, b);
683 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000684 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685 return NULL;
686 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000687 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000688 a = a / b;
689 PyFPE_END_PROTECT(a)
690 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000691}
692
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000693static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000694float_classic_div(PyObject *v, PyObject *w)
695{
696 double a,b;
697 CONVERT_TO_DOUBLE(v, a);
698 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000699 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000700 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
701 return NULL;
702 if (b == 0.0) {
703 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
704 return NULL;
705 }
706 PyFPE_START_PROTECT("divide", return 0)
707 a = a / b;
708 PyFPE_END_PROTECT(a)
709 return PyFloat_FromDouble(a);
710}
711
712static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000713float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000714{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000715 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000716 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000717 CONVERT_TO_DOUBLE(v, vx);
718 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000719 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721 return NULL;
722 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000723 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000724 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000725 /* note: checking mod*wx < 0 is incorrect -- underflows to
726 0 if wx < sqrt(smallest nonzero double) */
727 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000728 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000729 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000730 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000732}
733
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000734static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000735float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000736{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000737 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000738 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000739 CONVERT_TO_DOUBLE(v, vx);
740 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000741 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000743 return NULL;
744 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000745 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000746 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000747 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000748 exact multiple of wx. But this is fp arithmetic, and fp
749 vx - mod is an approximation; the result is that div may
750 not be an exact integral value after the division, although
751 it will always be very close to one.
752 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000753 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000754 if (mod) {
755 /* ensure the remainder has the same sign as the denominator */
756 if ((wx < 0) != (mod < 0)) {
757 mod += wx;
758 div -= 1.0;
759 }
760 }
761 else {
762 /* the remainder is zero, and in the presence of signed zeroes
763 fmod returns different results across platforms; ensure
764 it has the same sign as the denominator; we'd like to do
765 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000766 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000767 if (wx < 0.0)
768 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000769 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000770 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000771 if (div) {
772 floordiv = floor(div);
773 if (div - floordiv > 0.5)
774 floordiv += 1.0;
775 }
776 else {
777 /* div is zero - get the same sign as the true quotient */
778 div *= div; /* hide "div = +0" from optimizers */
779 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
780 }
781 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000782 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000783}
784
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000785static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000786float_floor_div(PyObject *v, PyObject *w)
787{
788 PyObject *t, *r;
789
790 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000791 if (t == NULL || t == Py_NotImplemented)
792 return t;
793 assert(PyTuple_CheckExact(t));
794 r = PyTuple_GET_ITEM(t, 0);
795 Py_INCREF(r);
796 Py_DECREF(t);
797 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000798}
799
800static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000801float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802{
803 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000804
805 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000806 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000807 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000808 return NULL;
809 }
810
Neil Schemenauer32117e52001-01-04 01:44:34 +0000811 CONVERT_TO_DOUBLE(v, iv);
812 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000813
814 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000815 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000816 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000817 }
Tim Peters96685bf2001-08-23 22:31:37 +0000818 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000819 if (iw < 0.0) {
820 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000821 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000822 return NULL;
823 }
824 return PyFloat_FromDouble(0.0);
825 }
Tim Peterse87568d2003-05-24 20:18:24 +0000826 if (iv < 0.0) {
827 /* Whether this is an error is a mess, and bumps into libm
828 * bugs so we have to figure it out ourselves.
829 */
830 if (iw != floor(iw)) {
831 PyErr_SetString(PyExc_ValueError, "negative number "
832 "cannot be raised to a fractional power");
833 return NULL;
834 }
835 /* iw is an exact integer, albeit perhaps a very large one.
836 * -1 raised to an exact integer should never be exceptional.
837 * Alas, some libms (chiefly glibc as of early 2003) return
838 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
839 * happen to be representable in a *C* integer. That's a
840 * bug; we let that slide in math.pow() (which currently
841 * reflects all platform accidents), but not for Python's **.
842 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000843 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000844 /* Return 1 if iw is even, -1 if iw is odd; there's
845 * no guarantee that any C integral type is big
846 * enough to hold iw, so we have to check this
847 * indirectly.
848 */
849 ix = floor(iw * 0.5) * 2.0;
850 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
851 }
852 /* Else iv != -1.0, and overflow or underflow are possible.
853 * Unless we're to write pow() ourselves, we have to trust
854 * the platform to do this correctly.
855 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000856 }
Tim Peters96685bf2001-08-23 22:31:37 +0000857 errno = 0;
858 PyFPE_START_PROTECT("pow", return NULL)
859 ix = pow(iv, iw);
860 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000861 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000862 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000863 /* We don't expect any errno value other than ERANGE, but
864 * the range of libm bugs appears unbounded.
865 */
Alex Martelli348dc882006-08-23 22:17:59 +0000866 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
867 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000868 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000869 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000870 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000871}
872
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000873static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000874float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877}
878
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000880float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000881{
Tim Peters0280cf72001-09-11 21:53:35 +0000882 if (PyFloat_CheckExact(v)) {
883 Py_INCREF(v);
884 return (PyObject *)v;
885 }
886 else
887 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000888}
889
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000890static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000891float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000892{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000893 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000894}
895
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000896static int
Fred Drakefd99de62000-07-09 05:02:18 +0000897float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000898{
899 return v->ob_fval != 0.0;
900}
901
Guido van Rossum234f9421993-06-17 12:35:49 +0000902static int
Fred Drakefd99de62000-07-09 05:02:18 +0000903float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000904{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000905 if (PyInt_Check(*pw)) {
906 long x = PyInt_AsLong(*pw);
907 *pw = PyFloat_FromDouble((double)x);
908 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000909 return 0;
910 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000911 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000912 double x = PyLong_AsDouble(*pw);
913 if (x == -1.0 && PyErr_Occurred())
914 return -1;
915 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000916 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000917 return 0;
918 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000919 else if (PyFloat_Check(*pw)) {
920 Py_INCREF(*pv);
921 Py_INCREF(*pw);
922 return 0;
923 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000924 return 1; /* Can't do it */
925}
926
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000927static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000928float_long(PyObject *v)
929{
930 double x = PyFloat_AsDouble(v);
931 return PyLong_FromDouble(x);
932}
933
934static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000935float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000936{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000937 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000938 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000939
940 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000941 /* Try to get out cheap if this fits in a Python int. The attempt
942 * to cast to long must be protected, as C doesn't define what
943 * happens if the double is too big to fit in a long. Some rare
944 * systems raise an exception then (RISCOS was mentioned as one,
945 * and someone using a non-default option on Sun also bumped into
946 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
947 * still be vulnerable: if a long has more bits of precision than
948 * a double, casting MIN/MAX to double may yield an approximation,
949 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
950 * yield true from the C expression wholepart<=LONG_MAX, despite
951 * that wholepart is actually greater than LONG_MAX.
952 */
953 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
954 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000955 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000956 }
957 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000958}
959
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000960static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000961float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000962{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000963 if (PyFloat_CheckExact(v))
964 Py_INCREF(v);
965 else
966 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000967 return v;
968}
969
970
Jeremy Hylton938ace62002-07-17 16:30:39 +0000971static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000972float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
973
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974static PyObject *
975float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
976{
977 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000978 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979
Guido van Rossumbef14172001-08-29 15:47:46 +0000980 if (type != &PyFloat_Type)
981 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000982 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
983 return NULL;
984 if (PyString_Check(x))
985 return PyFloat_FromString(x, NULL);
986 return PyNumber_Float(x);
987}
988
Guido van Rossumbef14172001-08-29 15:47:46 +0000989/* Wimpy, slow approach to tp_new calls for subtypes of float:
990 first create a regular float from whatever arguments we got,
991 then allocate a subtype instance and initialize its ob_fval
992 from the regular float. The regular float is then thrown away.
993*/
994static PyObject *
995float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
996{
Anthony Baxter377be112006-04-11 06:54:30 +0000997 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000998
999 assert(PyType_IsSubtype(type, &PyFloat_Type));
1000 tmp = float_new(&PyFloat_Type, args, kwds);
1001 if (tmp == NULL)
1002 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001003 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001004 newobj = type->tp_alloc(type, 0);
1005 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001006 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001007 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001008 }
Anthony Baxter377be112006-04-11 06:54:30 +00001009 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001010 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001011 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001012}
1013
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001014static PyObject *
1015float_getnewargs(PyFloatObject *v)
1016{
1017 return Py_BuildValue("(d)", v->ob_fval);
1018}
1019
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001020/* this is for the benefit of the pack/unpack routines below */
1021
1022typedef enum {
1023 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1024} float_format_type;
1025
1026static float_format_type double_format, float_format;
1027static float_format_type detected_double_format, detected_float_format;
1028
1029static PyObject *
1030float_getformat(PyTypeObject *v, PyObject* arg)
1031{
1032 char* s;
1033 float_format_type r;
1034
1035 if (!PyString_Check(arg)) {
1036 PyErr_Format(PyExc_TypeError,
1037 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis68192102007-07-21 06:55:02 +00001038 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001039 return NULL;
1040 }
1041 s = PyString_AS_STRING(arg);
1042 if (strcmp(s, "double") == 0) {
1043 r = double_format;
1044 }
1045 else if (strcmp(s, "float") == 0) {
1046 r = float_format;
1047 }
1048 else {
1049 PyErr_SetString(PyExc_ValueError,
1050 "__getformat__() argument 1 must be "
1051 "'double' or 'float'");
1052 return NULL;
1053 }
1054
1055 switch (r) {
1056 case unknown_format:
1057 return PyString_FromString("unknown");
1058 case ieee_little_endian_format:
1059 return PyString_FromString("IEEE, little-endian");
1060 case ieee_big_endian_format:
1061 return PyString_FromString("IEEE, big-endian");
1062 default:
1063 Py_FatalError("insane float_format or double_format");
1064 return NULL;
1065 }
1066}
1067
1068PyDoc_STRVAR(float_getformat_doc,
1069"float.__getformat__(typestr) -> string\n"
1070"\n"
1071"You probably don't want to use this function. It exists mainly to be\n"
1072"used in Python's test suite.\n"
1073"\n"
1074"typestr must be 'double' or 'float'. This function returns whichever of\n"
1075"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1076"format of floating point numbers used by the C type named by typestr.");
1077
1078static PyObject *
1079float_setformat(PyTypeObject *v, PyObject* args)
1080{
1081 char* typestr;
1082 char* format;
1083 float_format_type f;
1084 float_format_type detected;
1085 float_format_type *p;
1086
1087 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1088 return NULL;
1089
1090 if (strcmp(typestr, "double") == 0) {
1091 p = &double_format;
1092 detected = detected_double_format;
1093 }
1094 else if (strcmp(typestr, "float") == 0) {
1095 p = &float_format;
1096 detected = detected_float_format;
1097 }
1098 else {
1099 PyErr_SetString(PyExc_ValueError,
1100 "__setformat__() argument 1 must "
1101 "be 'double' or 'float'");
1102 return NULL;
1103 }
1104
1105 if (strcmp(format, "unknown") == 0) {
1106 f = unknown_format;
1107 }
1108 else if (strcmp(format, "IEEE, little-endian") == 0) {
1109 f = ieee_little_endian_format;
1110 }
1111 else if (strcmp(format, "IEEE, big-endian") == 0) {
1112 f = ieee_big_endian_format;
1113 }
1114 else {
1115 PyErr_SetString(PyExc_ValueError,
1116 "__setformat__() argument 2 must be "
1117 "'unknown', 'IEEE, little-endian' or "
1118 "'IEEE, big-endian'");
1119 return NULL;
1120
1121 }
1122
1123 if (f != unknown_format && f != detected) {
1124 PyErr_Format(PyExc_ValueError,
1125 "can only set %s format to 'unknown' or the "
1126 "detected platform value", typestr);
1127 return NULL;
1128 }
1129
1130 *p = f;
1131 Py_RETURN_NONE;
1132}
1133
1134PyDoc_STRVAR(float_setformat_doc,
1135"float.__setformat__(typestr, fmt) -> None\n"
1136"\n"
1137"You probably don't want to use this function. It exists mainly to be\n"
1138"used in Python's test suite.\n"
1139"\n"
1140"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1141"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1142"one of the latter two if it appears to match the underlying C reality.\n"
1143"\n"
1144"Overrides the automatic determination of C-level floating point type.\n"
1145"This affects how floats are converted to and from binary strings.");
1146
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001147static PyMethodDef float_methods[] = {
1148 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001149 {"__getformat__", (PyCFunction)float_getformat,
1150 METH_O|METH_CLASS, float_getformat_doc},
1151 {"__setformat__", (PyCFunction)float_setformat,
1152 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001153 {NULL, NULL} /* sentinel */
1154};
1155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001156PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157"float(x) -> floating point number\n\
1158\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160
1161
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001162static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001163 float_add, /*nb_add*/
1164 float_sub, /*nb_subtract*/
1165 float_mul, /*nb_multiply*/
1166 float_classic_div, /*nb_divide*/
1167 float_rem, /*nb_remainder*/
1168 float_divmod, /*nb_divmod*/
1169 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001170 (unaryfunc)float_neg, /*nb_negative*/
1171 (unaryfunc)float_pos, /*nb_positive*/
1172 (unaryfunc)float_abs, /*nb_absolute*/
1173 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001174 0, /*nb_invert*/
1175 0, /*nb_lshift*/
1176 0, /*nb_rshift*/
1177 0, /*nb_and*/
1178 0, /*nb_xor*/
1179 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001180 float_coerce, /*nb_coerce*/
1181 float_int, /*nb_int*/
1182 float_long, /*nb_long*/
1183 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001184 0, /* nb_oct */
1185 0, /* nb_hex */
1186 0, /* nb_inplace_add */
1187 0, /* nb_inplace_subtract */
1188 0, /* nb_inplace_multiply */
1189 0, /* nb_inplace_divide */
1190 0, /* nb_inplace_remainder */
1191 0, /* nb_inplace_power */
1192 0, /* nb_inplace_lshift */
1193 0, /* nb_inplace_rshift */
1194 0, /* nb_inplace_and */
1195 0, /* nb_inplace_xor */
1196 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001197 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001198 float_div, /* nb_true_divide */
1199 0, /* nb_inplace_floor_divide */
1200 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001201};
1202
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001203PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001204 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001205 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001206 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001207 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 (destructor)float_dealloc, /* tp_dealloc */
1209 (printfunc)float_print, /* tp_print */
1210 0, /* tp_getattr */
1211 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001212 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 (reprfunc)float_repr, /* tp_repr */
1214 &float_as_number, /* tp_as_number */
1215 0, /* tp_as_sequence */
1216 0, /* tp_as_mapping */
1217 (hashfunc)float_hash, /* tp_hash */
1218 0, /* tp_call */
1219 (reprfunc)float_str, /* tp_str */
1220 PyObject_GenericGetAttr, /* tp_getattro */
1221 0, /* tp_setattro */
1222 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001223 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1224 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 float_doc, /* tp_doc */
1226 0, /* tp_traverse */
1227 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001228 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 0, /* tp_weaklistoffset */
1230 0, /* tp_iter */
1231 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001232 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233 0, /* tp_members */
1234 0, /* tp_getset */
1235 0, /* tp_base */
1236 0, /* tp_dict */
1237 0, /* tp_descr_get */
1238 0, /* tp_descr_set */
1239 0, /* tp_dictoffset */
1240 0, /* tp_init */
1241 0, /* tp_alloc */
1242 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001243};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001244
1245void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001246_PyFloat_Init(void)
1247{
1248 /* We attempt to determine if this machine is using IEEE
1249 floating point formats by peering at the bits of some
1250 carefully chosen values. If it looks like we are on an
1251 IEEE platform, the float packing/unpacking routines can
1252 just copy bits, if not they resort to arithmetic & shifts
1253 and masks. The shifts & masks approach works on all finite
1254 values, but what happens to infinities, NaNs and signed
1255 zeroes on packing is an accident, and attempting to unpack
1256 a NaN or an infinity will raise an exception.
1257
1258 Note that if we're on some whacked-out platform which uses
1259 IEEE formats but isn't strictly little-endian or big-
1260 endian, we will fall back to the portable shifts & masks
1261 method. */
1262
1263#if SIZEOF_DOUBLE == 8
1264 {
1265 double x = 9006104071832581.0;
1266 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1267 detected_double_format = ieee_big_endian_format;
1268 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1269 detected_double_format = ieee_little_endian_format;
1270 else
1271 detected_double_format = unknown_format;
1272 }
1273#else
1274 detected_double_format = unknown_format;
1275#endif
1276
1277#if SIZEOF_FLOAT == 4
1278 {
1279 float y = 16711938.0;
1280 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1281 detected_float_format = ieee_big_endian_format;
1282 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1283 detected_float_format = ieee_little_endian_format;
1284 else
1285 detected_float_format = unknown_format;
1286 }
1287#else
1288 detected_float_format = unknown_format;
1289#endif
1290
1291 double_format = detected_double_format;
1292 float_format = detected_float_format;
1293}
1294
1295void
Fred Drakefd99de62000-07-09 05:02:18 +00001296PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001297{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001298 PyFloatObject *p;
1299 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001300 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001301 int bc, bf; /* block count, number of freed blocks */
1302 int frem, fsum; /* remaining unfreed floats per block, total */
1303
1304 bc = 0;
1305 bf = 0;
1306 fsum = 0;
1307 list = block_list;
1308 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001309 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001310 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001311 bc++;
1312 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001313 for (i = 0, p = &list->objects[0];
1314 i < N_FLOATOBJECTS;
1315 i++, p++) {
Martin v. Löwis68192102007-07-21 06:55:02 +00001316 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001317 frem++;
1318 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001319 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001320 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001321 list->next = block_list;
1322 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001323 for (i = 0, p = &list->objects[0];
1324 i < N_FLOATOBJECTS;
1325 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001326 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis68192102007-07-21 06:55:02 +00001327 Py_Refcnt(p) == 0) {
1328 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001329 free_list;
1330 free_list = p;
1331 }
1332 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001333 }
1334 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001335 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001336 bf++;
1337 }
1338 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001339 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001340 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001341 if (!Py_VerboseFlag)
1342 return;
1343 fprintf(stderr, "# cleanup floats");
1344 if (!fsum) {
1345 fprintf(stderr, "\n");
1346 }
1347 else {
1348 fprintf(stderr,
1349 ": %d unfreed float%s in %d out of %d block%s\n",
1350 fsum, fsum == 1 ? "" : "s",
1351 bc - bf, bc, bc == 1 ? "" : "s");
1352 }
1353 if (Py_VerboseFlag > 1) {
1354 list = block_list;
1355 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001356 for (i = 0, p = &list->objects[0];
1357 i < N_FLOATOBJECTS;
1358 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001359 if (PyFloat_CheckExact(p) &&
Martin v. Löwis68192102007-07-21 06:55:02 +00001360 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001361 char buf[100];
1362 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001363 /* XXX(twouters) cast refcount to
1364 long until %zd is universally
1365 available
1366 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001367 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001368 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis68192102007-07-21 06:55:02 +00001369 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001370 }
1371 }
1372 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001373 }
1374 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001375}
Tim Peters9905b942003-03-20 20:53:32 +00001376
1377/*----------------------------------------------------------------------------
1378 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1379 *
1380 * TODO: On platforms that use the standard IEEE-754 single and double
1381 * formats natively, these routines could simply copy the bytes.
1382 */
1383int
1384_PyFloat_Pack4(double x, unsigned char *p, int le)
1385{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001386 if (float_format == unknown_format) {
1387 unsigned char sign;
1388 int e;
1389 double f;
1390 unsigned int fbits;
1391 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001392
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001393 if (le) {
1394 p += 3;
1395 incr = -1;
1396 }
Tim Peters9905b942003-03-20 20:53:32 +00001397
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001398 if (x < 0) {
1399 sign = 1;
1400 x = -x;
1401 }
1402 else
1403 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001404
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001405 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001406
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001407 /* Normalize f to be in the range [1.0, 2.0) */
1408 if (0.5 <= f && f < 1.0) {
1409 f *= 2.0;
1410 e--;
1411 }
1412 else if (f == 0.0)
1413 e = 0;
1414 else {
1415 PyErr_SetString(PyExc_SystemError,
1416 "frexp() result out of range");
1417 return -1;
1418 }
1419
1420 if (e >= 128)
1421 goto Overflow;
1422 else if (e < -126) {
1423 /* Gradual underflow */
1424 f = ldexp(f, 126 + e);
1425 e = 0;
1426 }
1427 else if (!(e == 0 && f == 0.0)) {
1428 e += 127;
1429 f -= 1.0; /* Get rid of leading 1 */
1430 }
1431
1432 f *= 8388608.0; /* 2**23 */
1433 fbits = (unsigned int)(f + 0.5); /* Round */
1434 assert(fbits <= 8388608);
1435 if (fbits >> 23) {
1436 /* The carry propagated out of a string of 23 1 bits. */
1437 fbits = 0;
1438 ++e;
1439 if (e >= 255)
1440 goto Overflow;
1441 }
1442
1443 /* First byte */
1444 *p = (sign << 7) | (e >> 1);
1445 p += incr;
1446
1447 /* Second byte */
1448 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1449 p += incr;
1450
1451 /* Third byte */
1452 *p = (fbits >> 8) & 0xFF;
1453 p += incr;
1454
1455 /* Fourth byte */
1456 *p = fbits & 0xFF;
1457
1458 /* Done */
1459 return 0;
1460
1461 Overflow:
1462 PyErr_SetString(PyExc_OverflowError,
1463 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001464 return -1;
1465 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001466 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001467 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001468 const char *s = (char*)&y;
1469 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001470
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001471 if ((float_format == ieee_little_endian_format && !le)
1472 || (float_format == ieee_big_endian_format && le)) {
1473 p += 3;
1474 incr = -1;
1475 }
1476
1477 for (i = 0; i < 4; i++) {
1478 *p = *s++;
1479 p += incr;
1480 }
1481 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001482 }
Tim Peters9905b942003-03-20 20:53:32 +00001483}
1484
1485int
1486_PyFloat_Pack8(double x, unsigned char *p, int le)
1487{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001488 if (double_format == unknown_format) {
1489 unsigned char sign;
1490 int e;
1491 double f;
1492 unsigned int fhi, flo;
1493 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001494
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001495 if (le) {
1496 p += 7;
1497 incr = -1;
1498 }
Tim Peters9905b942003-03-20 20:53:32 +00001499
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001500 if (x < 0) {
1501 sign = 1;
1502 x = -x;
1503 }
1504 else
1505 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001506
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001507 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001508
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001509 /* Normalize f to be in the range [1.0, 2.0) */
1510 if (0.5 <= f && f < 1.0) {
1511 f *= 2.0;
1512 e--;
1513 }
1514 else if (f == 0.0)
1515 e = 0;
1516 else {
1517 PyErr_SetString(PyExc_SystemError,
1518 "frexp() result out of range");
1519 return -1;
1520 }
1521
1522 if (e >= 1024)
1523 goto Overflow;
1524 else if (e < -1022) {
1525 /* Gradual underflow */
1526 f = ldexp(f, 1022 + e);
1527 e = 0;
1528 }
1529 else if (!(e == 0 && f == 0.0)) {
1530 e += 1023;
1531 f -= 1.0; /* Get rid of leading 1 */
1532 }
1533
1534 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1535 f *= 268435456.0; /* 2**28 */
1536 fhi = (unsigned int)f; /* Truncate */
1537 assert(fhi < 268435456);
1538
1539 f -= (double)fhi;
1540 f *= 16777216.0; /* 2**24 */
1541 flo = (unsigned int)(f + 0.5); /* Round */
1542 assert(flo <= 16777216);
1543 if (flo >> 24) {
1544 /* The carry propagated out of a string of 24 1 bits. */
1545 flo = 0;
1546 ++fhi;
1547 if (fhi >> 28) {
1548 /* And it also progagated out of the next 28 bits. */
1549 fhi = 0;
1550 ++e;
1551 if (e >= 2047)
1552 goto Overflow;
1553 }
1554 }
1555
1556 /* First byte */
1557 *p = (sign << 7) | (e >> 4);
1558 p += incr;
1559
1560 /* Second byte */
1561 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1562 p += incr;
1563
1564 /* Third byte */
1565 *p = (fhi >> 16) & 0xFF;
1566 p += incr;
1567
1568 /* Fourth byte */
1569 *p = (fhi >> 8) & 0xFF;
1570 p += incr;
1571
1572 /* Fifth byte */
1573 *p = fhi & 0xFF;
1574 p += incr;
1575
1576 /* Sixth byte */
1577 *p = (flo >> 16) & 0xFF;
1578 p += incr;
1579
1580 /* Seventh byte */
1581 *p = (flo >> 8) & 0xFF;
1582 p += incr;
1583
1584 /* Eighth byte */
1585 *p = flo & 0xFF;
1586 p += incr;
1587
1588 /* Done */
1589 return 0;
1590
1591 Overflow:
1592 PyErr_SetString(PyExc_OverflowError,
1593 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001594 return -1;
1595 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001596 else {
1597 const char *s = (char*)&x;
1598 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001599
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001600 if ((double_format == ieee_little_endian_format && !le)
1601 || (double_format == ieee_big_endian_format && le)) {
1602 p += 7;
1603 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001604 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001605
1606 for (i = 0; i < 8; i++) {
1607 *p = *s++;
1608 p += incr;
1609 }
1610 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001611 }
Tim Peters9905b942003-03-20 20:53:32 +00001612}
1613
1614double
1615_PyFloat_Unpack4(const unsigned char *p, int le)
1616{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617 if (float_format == unknown_format) {
1618 unsigned char sign;
1619 int e;
1620 unsigned int f;
1621 double x;
1622 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001623
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 if (le) {
1625 p += 3;
1626 incr = -1;
1627 }
1628
1629 /* First byte */
1630 sign = (*p >> 7) & 1;
1631 e = (*p & 0x7F) << 1;
1632 p += incr;
1633
1634 /* Second byte */
1635 e |= (*p >> 7) & 1;
1636 f = (*p & 0x7F) << 16;
1637 p += incr;
1638
1639 if (e == 255) {
1640 PyErr_SetString(
1641 PyExc_ValueError,
1642 "can't unpack IEEE 754 special value "
1643 "on non-IEEE platform");
1644 return -1;
1645 }
1646
1647 /* Third byte */
1648 f |= *p << 8;
1649 p += incr;
1650
1651 /* Fourth byte */
1652 f |= *p;
1653
1654 x = (double)f / 8388608.0;
1655
1656 /* XXX This sadly ignores Inf/NaN issues */
1657 if (e == 0)
1658 e = -126;
1659 else {
1660 x += 1.0;
1661 e -= 127;
1662 }
1663 x = ldexp(x, e);
1664
1665 if (sign)
1666 x = -x;
1667
1668 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001669 }
Tim Peters9905b942003-03-20 20:53:32 +00001670 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001671 float x;
1672
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673 if ((float_format == ieee_little_endian_format && !le)
1674 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001675 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676 char *d = &buf[3];
1677 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001678
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001679 for (i = 0; i < 4; i++) {
1680 *d-- = *p++;
1681 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001682 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683 }
1684 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001685 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001686 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001687
1688 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001689 }
Tim Peters9905b942003-03-20 20:53:32 +00001690}
1691
1692double
1693_PyFloat_Unpack8(const unsigned char *p, int le)
1694{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001695 if (double_format == unknown_format) {
1696 unsigned char sign;
1697 int e;
1698 unsigned int fhi, flo;
1699 double x;
1700 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001701
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001702 if (le) {
1703 p += 7;
1704 incr = -1;
1705 }
1706
1707 /* First byte */
1708 sign = (*p >> 7) & 1;
1709 e = (*p & 0x7F) << 4;
1710
1711 p += incr;
1712
1713 /* Second byte */
1714 e |= (*p >> 4) & 0xF;
1715 fhi = (*p & 0xF) << 24;
1716 p += incr;
1717
1718 if (e == 2047) {
1719 PyErr_SetString(
1720 PyExc_ValueError,
1721 "can't unpack IEEE 754 special value "
1722 "on non-IEEE platform");
1723 return -1.0;
1724 }
1725
1726 /* Third byte */
1727 fhi |= *p << 16;
1728 p += incr;
1729
1730 /* Fourth byte */
1731 fhi |= *p << 8;
1732 p += incr;
1733
1734 /* Fifth byte */
1735 fhi |= *p;
1736 p += incr;
1737
1738 /* Sixth byte */
1739 flo = *p << 16;
1740 p += incr;
1741
1742 /* Seventh byte */
1743 flo |= *p << 8;
1744 p += incr;
1745
1746 /* Eighth byte */
1747 flo |= *p;
1748
1749 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1750 x /= 268435456.0; /* 2**28 */
1751
1752 if (e == 0)
1753 e = -1022;
1754 else {
1755 x += 1.0;
1756 e -= 1023;
1757 }
1758 x = ldexp(x, e);
1759
1760 if (sign)
1761 x = -x;
1762
1763 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001764 }
Tim Peters9905b942003-03-20 20:53:32 +00001765 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001766 double x;
1767
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001768 if ((double_format == ieee_little_endian_format && !le)
1769 || (double_format == ieee_big_endian_format && le)) {
1770 char buf[8];
1771 char *d = &buf[7];
1772 int i;
1773
1774 for (i = 0; i < 8; i++) {
1775 *d-- = *p++;
1776 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001777 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001778 }
1779 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001780 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001781 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001782
1783 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001784 }
Tim Peters9905b942003-03-20 20:53:32 +00001785}