blob: d3b7c9efecfbf07cfea36312cb28aced50ae4697 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Eric Smith8c663262007-08-25 02:26:07 +00009#include "formatter_unicode.h"
10
Guido van Rossum3f5da241990-12-20 15:06:42 +000011#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000012#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Jack Janseneddc1442003-11-20 01:44:59 +000014#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000015extern double fmod(double, double);
16extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000017#endif
18
Guido van Rossum93ad0df1997-05-13 21:00:42 +000019/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000020#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000021#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000022#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000023
Guido van Rossum3fce8831999-03-12 19:43:17 +000024struct _floatblock {
25 struct _floatblock *next;
26 PyFloatObject objects[N_FLOATOBJECTS];
27};
28
29typedef struct _floatblock PyFloatBlock;
30
31static PyFloatBlock *block_list = NULL;
32static PyFloatObject *free_list = NULL;
33
Guido van Rossum93ad0df1997-05-13 21:00:42 +000034static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000035fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000036{
37 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000038 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
39 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000041 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000042 ((PyFloatBlock *)p)->next = block_list;
43 block_list = (PyFloatBlock *)p;
44 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 q = p + N_FLOATOBJECTS;
46 while (--q > p)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000047 Py_Type(q) = (struct _typeobject *)(q-1);
48 Py_Type(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 return p + N_FLOATOBJECTS - 1;
50}
51
Christian Heimes93852662007-12-01 12:22:32 +000052double
53PyFloat_GetMax(void)
54{
55 return DBL_MAX;
56}
57
58double
59PyFloat_GetMin(void)
60{
61 return DBL_MIN;
62}
63
64PyObject *
65PyFloat_GetInfo(void)
66{
67 PyObject *d, *tmp;
68
69#define SET_FLOAT_CONST(d, key, const) \
70 tmp = PyFloat_FromDouble(const); \
71 if (tmp == NULL) return NULL; \
72 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
73 Py_DECREF(tmp)
74#define SET_INT_CONST(d, key, const) \
75 tmp = PyInt_FromLong(const); \
76 if (tmp == NULL) return NULL; \
77 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
78 Py_DECREF(tmp)
79
80 d = PyDict_New();
81
82 SET_FLOAT_CONST(d, "max", DBL_MAX);
83 SET_INT_CONST(d, "max_exp", DBL_MAX_EXP);
84 SET_INT_CONST(d, "max_10_exp", DBL_MAX_10_EXP);
85 SET_FLOAT_CONST(d, "min", DBL_MIN);
86 SET_INT_CONST(d, "min_exp", DBL_MIN_EXP);
87 SET_INT_CONST(d, "min_10_exp", DBL_MIN_10_EXP);
88 SET_INT_CONST(d, "dig", DBL_DIG);
89 SET_INT_CONST(d, "mant_dig", DBL_MANT_DIG);
90 SET_FLOAT_CONST(d, "epsilon", DBL_EPSILON);
91 SET_INT_CONST(d, "radix", FLT_RADIX);
92 SET_INT_CONST(d, "rounds", FLT_ROUNDS);
93
94 return d;
95}
96
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000101 register PyFloatObject *op;
102 if (free_list == NULL) {
103 if ((free_list = fill_free_list()) == NULL)
104 return NULL;
105 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000106 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000107 op = free_list;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000108 free_list = (PyFloatObject *)Py_Type(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000109 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000110 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000112}
113
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000114PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000115PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000116{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000117 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000118 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000119 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000120 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000121 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000122 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000123
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000124 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000125 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
126 if (s_buffer == NULL)
127 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000128 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000129 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000130 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000131 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000132 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000133 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000134 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000135 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000136 else if (PyObject_AsCharBuffer(v, &s, &len)) {
137 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000138 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000139 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000140 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000141
Guido van Rossum4c08d552000-03-10 22:55:18 +0000142 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000143 while (*s && isspace(Py_CHARMASK(*s)))
144 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000145 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000146 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000147 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000148 }
Tim Petersef14d732000-09-23 03:39:17 +0000149 /* We don't care about overflow or underflow. If the platform supports
150 * them, infinities and signed zeroes (on underflow) are fine.
151 * However, strtod can return 0 for denormalized numbers, where atof
152 * does not. So (alas!) we special-case a zero result. Note that
153 * whether strtod sets errno on underflow is not defined, so we can't
154 * key off errno.
155 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000156 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000157 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000158 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000160 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000161 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162 if (end > last)
163 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000164 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000165 PyOS_snprintf(buffer, sizeof(buffer),
166 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000167 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000169 }
170 /* Since end != s, the platform made *some* kind of sense out
171 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172 while (*end && isspace(Py_CHARMASK(*end)))
173 end++;
174 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000175 PyOS_snprintf(buffer, sizeof(buffer),
176 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000178 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000180 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 PyErr_SetString(PyExc_ValueError,
182 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000183 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184 }
Tim Petersef14d732000-09-23 03:39:17 +0000185 if (x == 0.0) {
186 /* See above -- may have been strtod being anal
187 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000188 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000189 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000190 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000191 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000193 result = PyFloat_FromDouble(x);
194 error:
195 if (s_buffer)
196 PyMem_FREE(s_buffer);
197 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000198}
199
Guido van Rossum234f9421993-06-17 12:35:49 +0000200static void
Fred Drakefd99de62000-07-09 05:02:18 +0000201float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000202{
Guido van Rossum9475a232001-10-05 20:51:39 +0000203 if (PyFloat_CheckExact(op)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000204 Py_Type(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000205 free_list = op;
206 }
207 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000208 Py_Type(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000209}
210
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211double
Fred Drakefd99de62000-07-09 05:02:18 +0000212PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 PyNumberMethods *nb;
215 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000216 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000217
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218 if (op && PyFloat_Check(op))
219 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000220
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000221 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223 return -1;
224 }
Tim Petersd2364e82001-11-01 20:09:42 +0000225
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000226 if ((nb = Py_Type(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000227 PyErr_SetString(PyExc_TypeError, "a float is required");
228 return -1;
229 }
230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232 if (fo == NULL)
233 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (!PyFloat_Check(fo)) {
235 PyErr_SetString(PyExc_TypeError,
236 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000237 return -1;
238 }
Tim Petersd2364e82001-11-01 20:09:42 +0000239
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 val = PyFloat_AS_DOUBLE(fo);
241 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000242
Guido van Rossumb6775db1994-08-01 11:34:53 +0000243 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244}
245
246/* Methods */
247
Tim Peters97019e42001-11-28 22:43:45 +0000248static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000249format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250{
251 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000252 char format[32];
Guido van Rossum04dbf3b2007-08-07 19:51:00 +0000253 /* Subroutine for float_repr, float_str, and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254 We want float numbers to be recognizable as such,
255 i.e., they should contain a decimal point or an exponent.
256 However, %g may print the number as an integer;
257 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000258
Martin v. Löwis737ea822004-06-08 18:52:54 +0000259 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000260 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261 cp = buf;
262 if (*cp == '-')
263 cp++;
264 for (; *cp != '\0'; cp++) {
265 /* Any non-digit means it's not an integer;
266 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000267 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268 break;
269 }
270 if (*cp == '\0') {
271 *cp++ = '.';
272 *cp++ = '0';
273 *cp++ = '\0';
274 }
275}
276
Neal Norwitz545686b2006-12-28 04:45:06 +0000277static void
278format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000279{
Neal Norwitz545686b2006-12-28 04:45:06 +0000280 assert(PyFloat_Check(v));
281 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000282}
283
Neil Schemenauer32117e52001-01-04 01:44:34 +0000284/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000285 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000286 set to NULL, and the function invoking this macro returns NULL. If
287 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
288 stored in obj, and returned from the function invoking this macro.
289*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000290#define CONVERT_TO_DOUBLE(obj, dbl) \
291 if (PyFloat_Check(obj)) \
292 dbl = PyFloat_AS_DOUBLE(obj); \
293 else if (convert_to_double(&(obj), &(dbl)) < 0) \
294 return obj;
295
296static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000297convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000298{
299 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000300
Guido van Rossumddefaf32007-01-14 03:31:43 +0000301 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000302 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000303 if (*dbl == -1.0 && PyErr_Occurred()) {
304 *v = NULL;
305 return -1;
306 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000307 }
308 else {
309 Py_INCREF(Py_NotImplemented);
310 *v = Py_NotImplemented;
311 return -1;
312 }
313 return 0;
314}
315
Guido van Rossum57072eb1999-12-23 19:00:28 +0000316/* Precisions used by repr() and str(), respectively.
317
318 The repr() precision (17 significant decimal digits) is the minimal number
319 that is guaranteed to have enough precision so that if the number is read
320 back in the exact same binary value is recreated. This is true for IEEE
321 floating point by design, and also happens to work for all other modern
322 hardware.
323
324 The str() precision is chosen so that in most cases, the rounding noise
325 created by various operations is suppressed, while giving plenty of
326 precision for practical use.
327
328*/
329
330#define PREC_REPR 17
331#define PREC_STR 12
332
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000334float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335{
336 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000337 format_float(buf, sizeof(buf), v, PREC_REPR);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000338 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000339}
340
341static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000342float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000343{
344 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000345 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000346 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347}
348
Tim Peters307fa782004-09-23 08:06:40 +0000349/* Comparison is pretty much a nightmare. When comparing float to float,
350 * we do it as straightforwardly (and long-windedly) as conceivable, so
351 * that, e.g., Python x == y delivers the same result as the platform
352 * C x == y when x and/or y is a NaN.
353 * When mixing float with an integer type, there's no good *uniform* approach.
354 * Converting the double to an integer obviously doesn't work, since we
355 * may lose info from fractional bits. Converting the integer to a double
356 * also has two failure modes: (1) a long int may trigger overflow (too
357 * large to fit in the dynamic range of a C double); (2) even a C long may have
358 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
359 * 63 bits of precision, but a C double probably has only 53), and then
360 * we can falsely claim equality when low-order integer bits are lost by
361 * coercion to double. So this part is painful too.
362 */
363
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000364static PyObject*
365float_richcompare(PyObject *v, PyObject *w, int op)
366{
367 double i, j;
368 int r = 0;
369
Tim Peters307fa782004-09-23 08:06:40 +0000370 assert(PyFloat_Check(v));
371 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000372
Tim Peters307fa782004-09-23 08:06:40 +0000373 /* Switch on the type of w. Set i and j to doubles to be compared,
374 * and op to the richcomp to use.
375 */
376 if (PyFloat_Check(w))
377 j = PyFloat_AS_DOUBLE(w);
378
Thomas Wouters477c8d52006-05-27 19:21:47 +0000379 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000380 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000381 /* If i is an infinity, its magnitude exceeds any
382 * finite integer, so it doesn't matter which int we
383 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000384 */
385 j = 0.0;
386 else
387 goto Unimplemented;
388 }
389
Tim Peters307fa782004-09-23 08:06:40 +0000390 else if (PyLong_Check(w)) {
391 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
392 int wsign = _PyLong_Sign(w);
393 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000394 int exponent;
395
396 if (vsign != wsign) {
397 /* Magnitudes are irrelevant -- the signs alone
398 * determine the outcome.
399 */
400 i = (double)vsign;
401 j = (double)wsign;
402 goto Compare;
403 }
404 /* The signs are the same. */
405 /* Convert w to a double if it fits. In particular, 0 fits. */
406 nbits = _PyLong_NumBits(w);
407 if (nbits == (size_t)-1 && PyErr_Occurred()) {
408 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000409 * to hold the # of bits. Replace with little doubles
410 * that give the same outcome -- w is so large that
411 * its magnitude must exceed the magnitude of any
412 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000413 */
414 PyErr_Clear();
415 i = (double)vsign;
416 assert(wsign != 0);
417 j = wsign * 2.0;
418 goto Compare;
419 }
420 if (nbits <= 48) {
421 j = PyLong_AsDouble(w);
422 /* It's impossible that <= 48 bits overflowed. */
423 assert(j != -1.0 || ! PyErr_Occurred());
424 goto Compare;
425 }
426 assert(wsign != 0); /* else nbits was 0 */
427 assert(vsign != 0); /* if vsign were 0, then since wsign is
428 * not 0, we would have taken the
429 * vsign != wsign branch at the start */
430 /* We want to work with non-negative numbers. */
431 if (vsign < 0) {
432 /* "Multiply both sides" by -1; this also swaps the
433 * comparator.
434 */
435 i = -i;
436 op = _Py_SwappedOp[op];
437 }
438 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000439 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000440 /* exponent is the # of bits in v before the radix point;
441 * we know that nbits (the # of bits in w) > 48 at this point
442 */
443 if (exponent < 0 || (size_t)exponent < nbits) {
444 i = 1.0;
445 j = 2.0;
446 goto Compare;
447 }
448 if ((size_t)exponent > nbits) {
449 i = 2.0;
450 j = 1.0;
451 goto Compare;
452 }
453 /* v and w have the same number of bits before the radix
454 * point. Construct two longs that have the same comparison
455 * outcome.
456 */
457 {
458 double fracpart;
459 double intpart;
460 PyObject *result = NULL;
461 PyObject *one = NULL;
462 PyObject *vv = NULL;
463 PyObject *ww = w;
464
465 if (wsign < 0) {
466 ww = PyNumber_Negative(w);
467 if (ww == NULL)
468 goto Error;
469 }
470 else
471 Py_INCREF(ww);
472
473 fracpart = modf(i, &intpart);
474 vv = PyLong_FromDouble(intpart);
475 if (vv == NULL)
476 goto Error;
477
478 if (fracpart != 0.0) {
479 /* Shift left, and or a 1 bit into vv
480 * to represent the lost fraction.
481 */
482 PyObject *temp;
483
484 one = PyInt_FromLong(1);
485 if (one == NULL)
486 goto Error;
487
488 temp = PyNumber_Lshift(ww, one);
489 if (temp == NULL)
490 goto Error;
491 Py_DECREF(ww);
492 ww = temp;
493
494 temp = PyNumber_Lshift(vv, one);
495 if (temp == NULL)
496 goto Error;
497 Py_DECREF(vv);
498 vv = temp;
499
500 temp = PyNumber_Or(vv, one);
501 if (temp == NULL)
502 goto Error;
503 Py_DECREF(vv);
504 vv = temp;
505 }
506
507 r = PyObject_RichCompareBool(vv, ww, op);
508 if (r < 0)
509 goto Error;
510 result = PyBool_FromLong(r);
511 Error:
512 Py_XDECREF(vv);
513 Py_XDECREF(ww);
514 Py_XDECREF(one);
515 return result;
516 }
517 } /* else if (PyLong_Check(w)) */
518
519 else /* w isn't float, int, or long */
520 goto Unimplemented;
521
522 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000523 PyFPE_START_PROTECT("richcompare", return NULL)
524 switch (op) {
525 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000526 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000527 break;
528 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000529 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000530 break;
531 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000532 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000533 break;
534 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000535 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000536 break;
537 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000538 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000539 break;
540 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000541 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000542 break;
543 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000544 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000545 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000546
547 Unimplemented:
548 Py_INCREF(Py_NotImplemented);
549 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000550}
551
Guido van Rossum9bfef441993-03-29 10:43:31 +0000552static long
Fred Drakefd99de62000-07-09 05:02:18 +0000553float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000554{
Tim Peters39dce292000-08-15 03:34:48 +0000555 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000556}
557
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000559float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561 double a,b;
562 CONVERT_TO_DOUBLE(v, a);
563 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000564 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565 a = a + b;
566 PyFPE_END_PROTECT(a)
567 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568}
569
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000571float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000572{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573 double a,b;
574 CONVERT_TO_DOUBLE(v, a);
575 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000576 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000577 a = a - b;
578 PyFPE_END_PROTECT(a)
579 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580}
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000583float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000585 double a,b;
586 CONVERT_TO_DOUBLE(v, a);
587 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000588 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000589 a = a * b;
590 PyFPE_END_PROTECT(a)
591 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000592}
593
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000594static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000595float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000596{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000597 double a,b;
598 CONVERT_TO_DOUBLE(v, a);
599 CONVERT_TO_DOUBLE(w, b);
600 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000601 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602 return NULL;
603 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000604 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000605 a = a / b;
606 PyFPE_END_PROTECT(a)
607 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000608}
609
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000611float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000613 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000614 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000615 CONVERT_TO_DOUBLE(v, vx);
616 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000619 return NULL;
620 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000621 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000622 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000623 /* note: checking mod*wx < 0 is incorrect -- underflows to
624 0 if wx < sqrt(smallest nonzero double) */
625 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000626 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000627 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000628 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000630}
631
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000632static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000633float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000634{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000635 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000636 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000637 CONVERT_TO_DOUBLE(v, vx);
638 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000639 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000641 return NULL;
642 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000643 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000644 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000645 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000646 exact multiple of wx. But this is fp arithmetic, and fp
647 vx - mod is an approximation; the result is that div may
648 not be an exact integral value after the division, although
649 it will always be very close to one.
650 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000651 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000652 if (mod) {
653 /* ensure the remainder has the same sign as the denominator */
654 if ((wx < 0) != (mod < 0)) {
655 mod += wx;
656 div -= 1.0;
657 }
658 }
659 else {
660 /* the remainder is zero, and in the presence of signed zeroes
661 fmod returns different results across platforms; ensure
662 it has the same sign as the denominator; we'd like to do
663 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000664 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000665 if (wx < 0.0)
666 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000667 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000668 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000669 if (div) {
670 floordiv = floor(div);
671 if (div - floordiv > 0.5)
672 floordiv += 1.0;
673 }
674 else {
675 /* div is zero - get the same sign as the true quotient */
676 div *= div; /* hide "div = +0" from optimizers */
677 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
678 }
679 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000680 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000681}
682
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000684float_floor_div(PyObject *v, PyObject *w)
685{
686 PyObject *t, *r;
687
688 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000689 if (t == NULL || t == Py_NotImplemented)
690 return t;
691 assert(PyTuple_CheckExact(t));
692 r = PyTuple_GET_ITEM(t, 0);
693 Py_INCREF(r);
694 Py_DECREF(t);
695 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000696}
697
698static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000699float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700{
701 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000702
703 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000704 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000705 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000706 return NULL;
707 }
708
Neil Schemenauer32117e52001-01-04 01:44:34 +0000709 CONVERT_TO_DOUBLE(v, iv);
710 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000711
712 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000713 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000714 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000715 }
Tim Peters96685bf2001-08-23 22:31:37 +0000716 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000717 if (iw < 0.0) {
718 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000719 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000720 return NULL;
721 }
722 return PyFloat_FromDouble(0.0);
723 }
Tim Peterse87568d2003-05-24 20:18:24 +0000724 if (iv < 0.0) {
725 /* Whether this is an error is a mess, and bumps into libm
726 * bugs so we have to figure it out ourselves.
727 */
728 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000729 /* Negative numbers raised to fractional powers
730 * become complex.
731 */
732 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000733 }
734 /* iw is an exact integer, albeit perhaps a very large one.
735 * -1 raised to an exact integer should never be exceptional.
736 * Alas, some libms (chiefly glibc as of early 2003) return
737 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
738 * happen to be representable in a *C* integer. That's a
739 * bug; we let that slide in math.pow() (which currently
740 * reflects all platform accidents), but not for Python's **.
741 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000743 /* Return 1 if iw is even, -1 if iw is odd; there's
744 * no guarantee that any C integral type is big
745 * enough to hold iw, so we have to check this
746 * indirectly.
747 */
748 ix = floor(iw * 0.5) * 2.0;
749 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
750 }
751 /* Else iv != -1.0, and overflow or underflow are possible.
752 * Unless we're to write pow() ourselves, we have to trust
753 * the platform to do this correctly.
754 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000755 }
Tim Peters96685bf2001-08-23 22:31:37 +0000756 errno = 0;
757 PyFPE_START_PROTECT("pow", return NULL)
758 ix = pow(iv, iw);
759 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000760 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000761 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000762 /* We don't expect any errno value other than ERANGE, but
763 * the range of libm bugs appears unbounded.
764 */
765 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
766 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000768 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770}
771
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000772static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000773float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000779float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000780{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000781 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000782}
783
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000784static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000785float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000786{
787 return v->ob_fval != 0.0;
788}
789
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000790static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000791float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000792{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000794 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000795
796 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000797 /* Try to get out cheap if this fits in a Python int. The attempt
798 * to cast to long must be protected, as C doesn't define what
799 * happens if the double is too big to fit in a long. Some rare
800 * systems raise an exception then (RISCOS was mentioned as one,
801 * and someone using a non-default option on Sun also bumped into
802 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
803 * still be vulnerable: if a long has more bits of precision than
804 * a double, casting MIN/MAX to double may yield an approximation,
805 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
806 * yield true from the C expression wholepart<=LONG_MAX, despite
807 * that wholepart is actually greater than LONG_MAX.
808 */
809 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
810 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000811 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000812 }
813 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000814}
815
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000816static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000817float_round(PyObject *v, PyObject *args)
818{
819#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
820 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000821 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000822 double flr, cil;
823 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000824 int ndigits = UNDEF_NDIGITS;
825
826 if (!PyArg_ParseTuple(args, "|i", &ndigits))
827 return NULL;
828
829 x = PyFloat_AsDouble(v);
830
831 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000832 f = pow(10.0, ndigits);
833 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000834 }
835
836 flr = floor(x);
837 cil = ceil(x);
838
839 if (x-flr > 0.5)
840 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000841 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000842 rounded = fmod(flr, 2) == 0 ? flr : cil;
843 else
844 rounded = flr;
845
846 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000847 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000848 return PyFloat_FromDouble(rounded);
849 }
850
851 return PyLong_FromDouble(rounded);
852#undef UNDEF_NDIGITS
853}
854
855static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000856float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000857{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000858 if (PyFloat_CheckExact(v))
859 Py_INCREF(v);
860 else
861 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000862 return v;
863}
864
865
Jeremy Hylton938ace62002-07-17 16:30:39 +0000866static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000867float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
868
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869static PyObject *
870float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
871{
872 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000873 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874
Guido van Rossumbef14172001-08-29 15:47:46 +0000875 if (type != &PyFloat_Type)
876 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
878 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000879 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000880 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881 return PyNumber_Float(x);
882}
883
Guido van Rossumbef14172001-08-29 15:47:46 +0000884/* Wimpy, slow approach to tp_new calls for subtypes of float:
885 first create a regular float from whatever arguments we got,
886 then allocate a subtype instance and initialize its ob_fval
887 from the regular float. The regular float is then thrown away.
888*/
889static PyObject *
890float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
891{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000892 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000893
894 assert(PyType_IsSubtype(type, &PyFloat_Type));
895 tmp = float_new(&PyFloat_Type, args, kwds);
896 if (tmp == NULL)
897 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000898 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000899 newobj = type->tp_alloc(type, 0);
900 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000901 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000902 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000903 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000904 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000905 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000906 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000907}
908
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000909static PyObject *
910float_getnewargs(PyFloatObject *v)
911{
912 return Py_BuildValue("(d)", v->ob_fval);
913}
914
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000915/* this is for the benefit of the pack/unpack routines below */
916
917typedef enum {
918 unknown_format, ieee_big_endian_format, ieee_little_endian_format
919} float_format_type;
920
921static float_format_type double_format, float_format;
922static float_format_type detected_double_format, detected_float_format;
923
924static PyObject *
925float_getformat(PyTypeObject *v, PyObject* arg)
926{
927 char* s;
928 float_format_type r;
929
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000930 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000931 PyErr_Format(PyExc_TypeError,
932 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000933 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000934 return NULL;
935 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000936 s = PyUnicode_AsString(arg);
937 if (s == NULL)
938 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000939 if (strcmp(s, "double") == 0) {
940 r = double_format;
941 }
942 else if (strcmp(s, "float") == 0) {
943 r = float_format;
944 }
945 else {
946 PyErr_SetString(PyExc_ValueError,
947 "__getformat__() argument 1 must be "
948 "'double' or 'float'");
949 return NULL;
950 }
951
952 switch (r) {
953 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000954 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000955 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000956 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000957 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000958 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000959 default:
960 Py_FatalError("insane float_format or double_format");
961 return NULL;
962 }
963}
964
965PyDoc_STRVAR(float_getformat_doc,
966"float.__getformat__(typestr) -> string\n"
967"\n"
968"You probably don't want to use this function. It exists mainly to be\n"
969"used in Python's test suite.\n"
970"\n"
971"typestr must be 'double' or 'float'. This function returns whichever of\n"
972"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
973"format of floating point numbers used by the C type named by typestr.");
974
975static PyObject *
976float_setformat(PyTypeObject *v, PyObject* args)
977{
978 char* typestr;
979 char* format;
980 float_format_type f;
981 float_format_type detected;
982 float_format_type *p;
983
984 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
985 return NULL;
986
987 if (strcmp(typestr, "double") == 0) {
988 p = &double_format;
989 detected = detected_double_format;
990 }
991 else if (strcmp(typestr, "float") == 0) {
992 p = &float_format;
993 detected = detected_float_format;
994 }
995 else {
996 PyErr_SetString(PyExc_ValueError,
997 "__setformat__() argument 1 must "
998 "be 'double' or 'float'");
999 return NULL;
1000 }
1001
1002 if (strcmp(format, "unknown") == 0) {
1003 f = unknown_format;
1004 }
1005 else if (strcmp(format, "IEEE, little-endian") == 0) {
1006 f = ieee_little_endian_format;
1007 }
1008 else if (strcmp(format, "IEEE, big-endian") == 0) {
1009 f = ieee_big_endian_format;
1010 }
1011 else {
1012 PyErr_SetString(PyExc_ValueError,
1013 "__setformat__() argument 2 must be "
1014 "'unknown', 'IEEE, little-endian' or "
1015 "'IEEE, big-endian'");
1016 return NULL;
1017
1018 }
1019
1020 if (f != unknown_format && f != detected) {
1021 PyErr_Format(PyExc_ValueError,
1022 "can only set %s format to 'unknown' or the "
1023 "detected platform value", typestr);
1024 return NULL;
1025 }
1026
1027 *p = f;
1028 Py_RETURN_NONE;
1029}
1030
1031PyDoc_STRVAR(float_setformat_doc,
1032"float.__setformat__(typestr, fmt) -> None\n"
1033"\n"
1034"You probably don't want to use this function. It exists mainly to be\n"
1035"used in Python's test suite.\n"
1036"\n"
1037"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1038"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1039"one of the latter two if it appears to match the underlying C reality.\n"
1040"\n"
1041"Overrides the automatic determination of C-level floating point type.\n"
1042"This affects how floats are converted to and from binary strings.");
1043
Guido van Rossumb43daf72007-08-01 18:08:08 +00001044static PyObject *
1045float_getzero(PyObject *v, void *closure)
1046{
1047 return PyFloat_FromDouble(0.0);
1048}
1049
Eric Smith8c663262007-08-25 02:26:07 +00001050static PyObject *
1051float__format__(PyObject *self, PyObject *args)
1052{
1053 /* when back porting this to 2.6, check type of the format_spec
1054 and call either unicode_long__format__ or
1055 string_long__format__ */
1056 return unicode_float__format__(self, args);
1057}
1058
1059PyDoc_STRVAR(float__format__doc,
1060"float.__format__(format_spec) -> string\n"
1061"\n"
1062"Formats the float according to format_spec.");
1063
1064
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001065static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001066 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1067 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001068 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1069 "Returns the Integral closest to x between 0 and x."},
1070 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1071 "Returns the Integral closest to x, rounding half toward even.\n"
1072 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001073 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001074 {"__getformat__", (PyCFunction)float_getformat,
1075 METH_O|METH_CLASS, float_getformat_doc},
1076 {"__setformat__", (PyCFunction)float_setformat,
1077 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001078 {"__format__", (PyCFunction)float__format__,
1079 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001080 {NULL, NULL} /* sentinel */
1081};
1082
Guido van Rossumb43daf72007-08-01 18:08:08 +00001083static PyGetSetDef float_getset[] = {
1084 {"real",
1085 (getter)float_float, (setter)NULL,
1086 "the real part of a complex number",
1087 NULL},
1088 {"imag",
1089 (getter)float_getzero, (setter)NULL,
1090 "the imaginary part of a complex number",
1091 NULL},
1092 {NULL} /* Sentinel */
1093};
1094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001095PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096"float(x) -> floating point number\n\
1097\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001098Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099
1100
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001101static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001102 float_add, /*nb_add*/
1103 float_sub, /*nb_subtract*/
1104 float_mul, /*nb_multiply*/
1105 float_rem, /*nb_remainder*/
1106 float_divmod, /*nb_divmod*/
1107 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001108 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001109 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001110 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001111 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001112 0, /*nb_invert*/
1113 0, /*nb_lshift*/
1114 0, /*nb_rshift*/
1115 0, /*nb_and*/
1116 0, /*nb_xor*/
1117 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001118 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001119 float_trunc, /*nb_int*/
1120 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001121 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001122 0, /* nb_oct */
1123 0, /* nb_hex */
1124 0, /* nb_inplace_add */
1125 0, /* nb_inplace_subtract */
1126 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001127 0, /* nb_inplace_remainder */
1128 0, /* nb_inplace_power */
1129 0, /* nb_inplace_lshift */
1130 0, /* nb_inplace_rshift */
1131 0, /* nb_inplace_and */
1132 0, /* nb_inplace_xor */
1133 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001134 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001135 float_div, /* nb_true_divide */
1136 0, /* nb_inplace_floor_divide */
1137 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001138};
1139
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001140PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001141 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001142 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001143 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001144 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001146 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 0, /* tp_getattr */
1148 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001149 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 (reprfunc)float_repr, /* tp_repr */
1151 &float_as_number, /* tp_as_number */
1152 0, /* tp_as_sequence */
1153 0, /* tp_as_mapping */
1154 (hashfunc)float_hash, /* tp_hash */
1155 0, /* tp_call */
1156 (reprfunc)float_str, /* tp_str */
1157 PyObject_GenericGetAttr, /* tp_getattro */
1158 0, /* tp_setattro */
1159 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001160 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 float_doc, /* tp_doc */
1162 0, /* tp_traverse */
1163 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001164 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 0, /* tp_weaklistoffset */
1166 0, /* tp_iter */
1167 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001168 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001170 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 0, /* tp_base */
1172 0, /* tp_dict */
1173 0, /* tp_descr_get */
1174 0, /* tp_descr_set */
1175 0, /* tp_dictoffset */
1176 0, /* tp_init */
1177 0, /* tp_alloc */
1178 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001179};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001180
1181void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001182_PyFloat_Init(void)
1183{
1184 /* We attempt to determine if this machine is using IEEE
1185 floating point formats by peering at the bits of some
1186 carefully chosen values. If it looks like we are on an
1187 IEEE platform, the float packing/unpacking routines can
1188 just copy bits, if not they resort to arithmetic & shifts
1189 and masks. The shifts & masks approach works on all finite
1190 values, but what happens to infinities, NaNs and signed
1191 zeroes on packing is an accident, and attempting to unpack
1192 a NaN or an infinity will raise an exception.
1193
1194 Note that if we're on some whacked-out platform which uses
1195 IEEE formats but isn't strictly little-endian or big-
1196 endian, we will fall back to the portable shifts & masks
1197 method. */
1198
1199#if SIZEOF_DOUBLE == 8
1200 {
1201 double x = 9006104071832581.0;
1202 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1203 detected_double_format = ieee_big_endian_format;
1204 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1205 detected_double_format = ieee_little_endian_format;
1206 else
1207 detected_double_format = unknown_format;
1208 }
1209#else
1210 detected_double_format = unknown_format;
1211#endif
1212
1213#if SIZEOF_FLOAT == 4
1214 {
1215 float y = 16711938.0;
1216 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1217 detected_float_format = ieee_big_endian_format;
1218 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1219 detected_float_format = ieee_little_endian_format;
1220 else
1221 detected_float_format = unknown_format;
1222 }
1223#else
1224 detected_float_format = unknown_format;
1225#endif
1226
1227 double_format = detected_double_format;
1228 float_format = detected_float_format;
1229}
1230
1231void
Fred Drakefd99de62000-07-09 05:02:18 +00001232PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001233{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001234 PyFloatObject *p;
1235 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001236 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001237 int bc, bf; /* block count, number of freed blocks */
1238 int frem, fsum; /* remaining unfreed floats per block, total */
1239
1240 bc = 0;
1241 bf = 0;
1242 fsum = 0;
1243 list = block_list;
1244 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001245 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001246 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001247 bc++;
1248 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001249 for (i = 0, p = &list->objects[0];
1250 i < N_FLOATOBJECTS;
1251 i++, p++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001252 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001253 frem++;
1254 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001255 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001256 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001257 list->next = block_list;
1258 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001259 for (i = 0, p = &list->objects[0];
1260 i < N_FLOATOBJECTS;
1261 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001262 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001263 Py_Refcnt(p) == 0) {
1264 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001265 free_list;
1266 free_list = p;
1267 }
1268 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001269 }
1270 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001271 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001272 bf++;
1273 }
1274 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001275 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001276 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001277 if (!Py_VerboseFlag)
1278 return;
1279 fprintf(stderr, "# cleanup floats");
1280 if (!fsum) {
1281 fprintf(stderr, "\n");
1282 }
1283 else {
1284 fprintf(stderr,
1285 ": %d unfreed float%s in %d out of %d block%s\n",
1286 fsum, fsum == 1 ? "" : "s",
1287 bc - bf, bc, bc == 1 ? "" : "s");
1288 }
1289 if (Py_VerboseFlag > 1) {
1290 list = block_list;
1291 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001292 for (i = 0, p = &list->objects[0];
1293 i < N_FLOATOBJECTS;
1294 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001295 if (PyFloat_CheckExact(p) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001296 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001297 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001298 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001299 /* XXX(twouters) cast refcount to
1300 long until %zd is universally
1301 available
1302 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001303 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001304 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001305 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001306 }
1307 }
1308 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001309 }
1310 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001311}
Tim Peters9905b942003-03-20 20:53:32 +00001312
1313/*----------------------------------------------------------------------------
1314 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1315 *
1316 * TODO: On platforms that use the standard IEEE-754 single and double
1317 * formats natively, these routines could simply copy the bytes.
1318 */
1319int
1320_PyFloat_Pack4(double x, unsigned char *p, int le)
1321{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001322 if (float_format == unknown_format) {
1323 unsigned char sign;
1324 int e;
1325 double f;
1326 unsigned int fbits;
1327 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001328
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001329 if (le) {
1330 p += 3;
1331 incr = -1;
1332 }
Tim Peters9905b942003-03-20 20:53:32 +00001333
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001334 if (x < 0) {
1335 sign = 1;
1336 x = -x;
1337 }
1338 else
1339 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001340
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001341 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001342
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001343 /* Normalize f to be in the range [1.0, 2.0) */
1344 if (0.5 <= f && f < 1.0) {
1345 f *= 2.0;
1346 e--;
1347 }
1348 else if (f == 0.0)
1349 e = 0;
1350 else {
1351 PyErr_SetString(PyExc_SystemError,
1352 "frexp() result out of range");
1353 return -1;
1354 }
1355
1356 if (e >= 128)
1357 goto Overflow;
1358 else if (e < -126) {
1359 /* Gradual underflow */
1360 f = ldexp(f, 126 + e);
1361 e = 0;
1362 }
1363 else if (!(e == 0 && f == 0.0)) {
1364 e += 127;
1365 f -= 1.0; /* Get rid of leading 1 */
1366 }
1367
1368 f *= 8388608.0; /* 2**23 */
1369 fbits = (unsigned int)(f + 0.5); /* Round */
1370 assert(fbits <= 8388608);
1371 if (fbits >> 23) {
1372 /* The carry propagated out of a string of 23 1 bits. */
1373 fbits = 0;
1374 ++e;
1375 if (e >= 255)
1376 goto Overflow;
1377 }
1378
1379 /* First byte */
1380 *p = (sign << 7) | (e >> 1);
1381 p += incr;
1382
1383 /* Second byte */
1384 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1385 p += incr;
1386
1387 /* Third byte */
1388 *p = (fbits >> 8) & 0xFF;
1389 p += incr;
1390
1391 /* Fourth byte */
1392 *p = fbits & 0xFF;
1393
1394 /* Done */
1395 return 0;
1396
1397 Overflow:
1398 PyErr_SetString(PyExc_OverflowError,
1399 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001400 return -1;
1401 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001402 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001403 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001404 const char *s = (char*)&y;
1405 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001406
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001407 if ((float_format == ieee_little_endian_format && !le)
1408 || (float_format == ieee_big_endian_format && le)) {
1409 p += 3;
1410 incr = -1;
1411 }
1412
1413 for (i = 0; i < 4; i++) {
1414 *p = *s++;
1415 p += incr;
1416 }
1417 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001418 }
Tim Peters9905b942003-03-20 20:53:32 +00001419}
1420
1421int
1422_PyFloat_Pack8(double x, unsigned char *p, int le)
1423{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001424 if (double_format == unknown_format) {
1425 unsigned char sign;
1426 int e;
1427 double f;
1428 unsigned int fhi, flo;
1429 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001430
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001431 if (le) {
1432 p += 7;
1433 incr = -1;
1434 }
Tim Peters9905b942003-03-20 20:53:32 +00001435
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001436 if (x < 0) {
1437 sign = 1;
1438 x = -x;
1439 }
1440 else
1441 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001442
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001443 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001444
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001445 /* Normalize f to be in the range [1.0, 2.0) */
1446 if (0.5 <= f && f < 1.0) {
1447 f *= 2.0;
1448 e--;
1449 }
1450 else if (f == 0.0)
1451 e = 0;
1452 else {
1453 PyErr_SetString(PyExc_SystemError,
1454 "frexp() result out of range");
1455 return -1;
1456 }
1457
1458 if (e >= 1024)
1459 goto Overflow;
1460 else if (e < -1022) {
1461 /* Gradual underflow */
1462 f = ldexp(f, 1022 + e);
1463 e = 0;
1464 }
1465 else if (!(e == 0 && f == 0.0)) {
1466 e += 1023;
1467 f -= 1.0; /* Get rid of leading 1 */
1468 }
1469
1470 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1471 f *= 268435456.0; /* 2**28 */
1472 fhi = (unsigned int)f; /* Truncate */
1473 assert(fhi < 268435456);
1474
1475 f -= (double)fhi;
1476 f *= 16777216.0; /* 2**24 */
1477 flo = (unsigned int)(f + 0.5); /* Round */
1478 assert(flo <= 16777216);
1479 if (flo >> 24) {
1480 /* The carry propagated out of a string of 24 1 bits. */
1481 flo = 0;
1482 ++fhi;
1483 if (fhi >> 28) {
1484 /* And it also progagated out of the next 28 bits. */
1485 fhi = 0;
1486 ++e;
1487 if (e >= 2047)
1488 goto Overflow;
1489 }
1490 }
1491
1492 /* First byte */
1493 *p = (sign << 7) | (e >> 4);
1494 p += incr;
1495
1496 /* Second byte */
1497 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1498 p += incr;
1499
1500 /* Third byte */
1501 *p = (fhi >> 16) & 0xFF;
1502 p += incr;
1503
1504 /* Fourth byte */
1505 *p = (fhi >> 8) & 0xFF;
1506 p += incr;
1507
1508 /* Fifth byte */
1509 *p = fhi & 0xFF;
1510 p += incr;
1511
1512 /* Sixth byte */
1513 *p = (flo >> 16) & 0xFF;
1514 p += incr;
1515
1516 /* Seventh byte */
1517 *p = (flo >> 8) & 0xFF;
1518 p += incr;
1519
1520 /* Eighth byte */
1521 *p = flo & 0xFF;
1522 p += incr;
1523
1524 /* Done */
1525 return 0;
1526
1527 Overflow:
1528 PyErr_SetString(PyExc_OverflowError,
1529 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001530 return -1;
1531 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001532 else {
1533 const char *s = (char*)&x;
1534 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001535
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001536 if ((double_format == ieee_little_endian_format && !le)
1537 || (double_format == ieee_big_endian_format && le)) {
1538 p += 7;
1539 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001540 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001541
1542 for (i = 0; i < 8; i++) {
1543 *p = *s++;
1544 p += incr;
1545 }
1546 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001547 }
Tim Peters9905b942003-03-20 20:53:32 +00001548}
1549
Neal Norwitz545686b2006-12-28 04:45:06 +00001550/* Should only be used by marshal. */
1551int
1552_PyFloat_Repr(double x, char *p, size_t len)
1553{
1554 format_double(p, len, x, PREC_REPR);
1555 return (int)strlen(p);
1556}
1557
Tim Peters9905b942003-03-20 20:53:32 +00001558double
1559_PyFloat_Unpack4(const unsigned char *p, int le)
1560{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001561 if (float_format == unknown_format) {
1562 unsigned char sign;
1563 int e;
1564 unsigned int f;
1565 double x;
1566 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001567
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001568 if (le) {
1569 p += 3;
1570 incr = -1;
1571 }
1572
1573 /* First byte */
1574 sign = (*p >> 7) & 1;
1575 e = (*p & 0x7F) << 1;
1576 p += incr;
1577
1578 /* Second byte */
1579 e |= (*p >> 7) & 1;
1580 f = (*p & 0x7F) << 16;
1581 p += incr;
1582
1583 if (e == 255) {
1584 PyErr_SetString(
1585 PyExc_ValueError,
1586 "can't unpack IEEE 754 special value "
1587 "on non-IEEE platform");
1588 return -1;
1589 }
1590
1591 /* Third byte */
1592 f |= *p << 8;
1593 p += incr;
1594
1595 /* Fourth byte */
1596 f |= *p;
1597
1598 x = (double)f / 8388608.0;
1599
1600 /* XXX This sadly ignores Inf/NaN issues */
1601 if (e == 0)
1602 e = -126;
1603 else {
1604 x += 1.0;
1605 e -= 127;
1606 }
1607 x = ldexp(x, e);
1608
1609 if (sign)
1610 x = -x;
1611
1612 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001613 }
Tim Peters9905b942003-03-20 20:53:32 +00001614 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001615 float x;
1616
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617 if ((float_format == ieee_little_endian_format && !le)
1618 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001619 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620 char *d = &buf[3];
1621 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001622
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001623 for (i = 0; i < 4; i++) {
1624 *d-- = *p++;
1625 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001626 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001627 }
1628 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001629 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001630 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001631
1632 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001633 }
Tim Peters9905b942003-03-20 20:53:32 +00001634}
1635
1636double
1637_PyFloat_Unpack8(const unsigned char *p, int le)
1638{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001639 if (double_format == unknown_format) {
1640 unsigned char sign;
1641 int e;
1642 unsigned int fhi, flo;
1643 double x;
1644 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001645
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001646 if (le) {
1647 p += 7;
1648 incr = -1;
1649 }
1650
1651 /* First byte */
1652 sign = (*p >> 7) & 1;
1653 e = (*p & 0x7F) << 4;
1654
1655 p += incr;
1656
1657 /* Second byte */
1658 e |= (*p >> 4) & 0xF;
1659 fhi = (*p & 0xF) << 24;
1660 p += incr;
1661
1662 if (e == 2047) {
1663 PyErr_SetString(
1664 PyExc_ValueError,
1665 "can't unpack IEEE 754 special value "
1666 "on non-IEEE platform");
1667 return -1.0;
1668 }
1669
1670 /* Third byte */
1671 fhi |= *p << 16;
1672 p += incr;
1673
1674 /* Fourth byte */
1675 fhi |= *p << 8;
1676 p += incr;
1677
1678 /* Fifth byte */
1679 fhi |= *p;
1680 p += incr;
1681
1682 /* Sixth byte */
1683 flo = *p << 16;
1684 p += incr;
1685
1686 /* Seventh byte */
1687 flo |= *p << 8;
1688 p += incr;
1689
1690 /* Eighth byte */
1691 flo |= *p;
1692
1693 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1694 x /= 268435456.0; /* 2**28 */
1695
1696 if (e == 0)
1697 e = -1022;
1698 else {
1699 x += 1.0;
1700 e -= 1023;
1701 }
1702 x = ldexp(x, e);
1703
1704 if (sign)
1705 x = -x;
1706
1707 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001708 }
Tim Peters9905b942003-03-20 20:53:32 +00001709 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001710 double x;
1711
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712 if ((double_format == ieee_little_endian_format && !le)
1713 || (double_format == ieee_big_endian_format && le)) {
1714 char buf[8];
1715 char *d = &buf[7];
1716 int i;
1717
1718 for (i = 0; i < 8; i++) {
1719 *d-- = *p++;
1720 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001721 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001722 }
1723 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001724 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001725 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001726
1727 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001728 }
Tim Peters9905b942003-03-20 20:53:32 +00001729}