blob: 5d0b920f5c9405c4afc1122ca04591d4f2f9b914 [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)
Christian Heimese93237d2007-12-19 02:37:44 +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;
Christian Heimese93237d2007-12-19 02:37:44 +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{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000131 const char *s, *last, *end, *sp;
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 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000174 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000175 /* We don't care about overflow or underflow. If the platform supports
176 * them, infinities and signed zeroes (on underflow) are fine.
177 * However, strtod can return 0 for denormalized numbers, where atof
178 * does not. So (alas!) we special-case a zero result. Note that
179 * whether strtod sets errno on underflow is not defined, so we can't
180 * key off errno.
181 */
Tim Peters858346e2000-09-25 21:01:28 +0000182 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000183 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000184 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000185 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000186 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000187 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 if (end > last)
189 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000190 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000191 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000192 char *p = (char*)sp;
193 int sign = 1;
194
195 if (*p == '-') {
196 sign = -1;
197 p++;
198 }
199 if (*p == '+') {
200 p++;
201 }
202 if (PyOS_strnicmp(p, "inf", 4) == 0) {
203 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
204 }
205#ifdef Py_NAN
206 if(PyOS_strnicmp(p, "nan", 4) == 0) {
207 return PyFloat_FromDouble(Py_NAN);
208 }
209#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000210 PyOS_snprintf(buffer, sizeof(buffer),
211 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000212 PyErr_SetString(PyExc_ValueError, buffer);
213 return NULL;
214 }
215 /* Since end != s, the platform made *some* kind of sense out
216 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 while (*end && isspace(Py_CHARMASK(*end)))
218 end++;
219 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000220 PyOS_snprintf(buffer, sizeof(buffer),
221 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000222 PyErr_SetString(PyExc_ValueError, buffer);
223 return NULL;
224 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000225 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000226 PyErr_SetString(PyExc_ValueError,
227 "null byte in argument for float()");
228 return NULL;
229 }
Tim Petersef14d732000-09-23 03:39:17 +0000230 if (x == 0.0) {
231 /* See above -- may have been strtod being anal
232 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000233 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000234 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000235 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000236 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000238 return PyFloat_FromDouble(x);
239}
240
Guido van Rossum234f9421993-06-17 12:35:49 +0000241static void
Fred Drakefd99de62000-07-09 05:02:18 +0000242float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000243{
Guido van Rossum9475a232001-10-05 20:51:39 +0000244 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000245 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000246 free_list = op;
247 }
248 else
Christian Heimese93237d2007-12-19 02:37:44 +0000249 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000250}
251
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252double
Fred Drakefd99de62000-07-09 05:02:18 +0000253PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000255 PyNumberMethods *nb;
256 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000259 if (op && PyFloat_Check(op))
260 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000261
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000262 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264 return -1;
265 }
Tim Petersd2364e82001-11-01 20:09:42 +0000266
Christian Heimese93237d2007-12-19 02:37:44 +0000267 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000268 PyErr_SetString(PyExc_TypeError, "a float is required");
269 return -1;
270 }
271
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273 if (fo == NULL)
274 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275 if (!PyFloat_Check(fo)) {
276 PyErr_SetString(PyExc_TypeError,
277 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000278 return -1;
279 }
Tim Petersd2364e82001-11-01 20:09:42 +0000280
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 val = PyFloat_AS_DOUBLE(fo);
282 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000283
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285}
286
287/* Methods */
288
Tim Peters97019e42001-11-28 22:43:45 +0000289static void
290format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291{
292 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000293 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000294 int i;
295
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 /* Subroutine for float_repr and float_print.
297 We want float numbers to be recognizable as such,
298 i.e., they should contain a decimal point or an exponent.
299 However, %g may print the number as an integer;
300 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000301
302 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000303 PyOS_snprintf(format, 32, "%%.%ig", precision);
304 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305 cp = buf;
306 if (*cp == '-')
307 cp++;
308 for (; *cp != '\0'; cp++) {
309 /* Any non-digit means it's not an integer;
310 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000311 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312 break;
313 }
314 if (*cp == '\0') {
315 *cp++ = '.';
316 *cp++ = '0';
317 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000318 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000320 /* Checking the next three chars should be more than enough to
321 * detect inf or nan, even on Windows. We check for inf or nan
322 * at last because they are rare cases.
323 */
324 for (i=0; *cp != '\0' && i<3; cp++, i++) {
325 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
326 continue;
327 /* found something that is neither a digit nor point
328 * it might be a NaN or INF
329 */
330#ifdef Py_NAN
331 if (Py_IS_NAN(v->ob_fval)) {
332 strcpy(buf, "nan");
333 }
334 else
335#endif
336 if (Py_IS_INFINITY(v->ob_fval)) {
337 cp = buf;
338 if (*cp == '-')
339 cp++;
340 strcpy(cp, "inf");
341 }
342 break;
343 }
344
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345}
346
Tim Peters97019e42001-11-28 22:43:45 +0000347/* XXX PyFloat_AsStringEx should not be a public API function (for one
348 XXX thing, its signature passes a buffer without a length; for another,
349 XXX it isn't useful outside this file).
350*/
351void
352PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
353{
354 format_float(buf, 100, v, precision);
355}
356
Christian Heimesf15c66e2007-12-11 00:54:34 +0000357#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000358/* The following function is based on Tcl_PrintDouble,
359 * from tclUtil.c.
360 */
361
362#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
363#define is_nan(d) ((d) != (d))
364
365static void
366format_double_repr(char *dst, double value)
367{
368 char *p, c;
369 int exp;
370 int signum;
371 char buffer[30];
372
373 /*
374 * Handle NaN.
375 */
376
377 if (is_nan(value)) {
378 strcpy(dst, "nan");
379 return;
380 }
381
382 /*
383 * Handle infinities.
384 */
385
386 if (is_infinite(value)) {
387 if (value < 0) {
388 strcpy(dst, "-inf");
389 } else {
390 strcpy(dst, "inf");
391 }
392 return;
393 }
394
395 /*
396 * Ordinary (normal and denormal) values.
397 */
398
399 exp = _PyFloat_Digits(buffer, value, &signum)+1;
400 if (signum) {
401 *dst++ = '-';
402 }
403 p = buffer;
404 if (exp < -3 || exp > 17) {
405 /*
406 * E format for numbers < 1e-3 or >= 1e17.
407 */
408
409 *dst++ = *p++;
410 c = *p;
411 if (c != '\0') {
412 *dst++ = '.';
413 while (c != '\0') {
414 *dst++ = c;
415 c = *++p;
416 }
417 }
418 sprintf(dst, "e%+d", exp-1);
419 } else {
420 /*
421 * F format for others.
422 */
423
424 if (exp <= 0) {
425 *dst++ = '0';
426 }
427 c = *p;
428 while (exp-- > 0) {
429 if (c != '\0') {
430 *dst++ = c;
431 c = *++p;
432 } else {
433 *dst++ = '0';
434 }
435 }
436 *dst++ = '.';
437 if (c == '\0') {
438 *dst++ = '0';
439 } else {
440 while (++exp < 0) {
441 *dst++ = '0';
442 }
443 while (c != '\0') {
444 *dst++ = c;
445 c = *++p;
446 }
447 }
448 *dst++ = '\0';
449 }
450}
451
452static void
453format_float_repr(char *buf, PyFloatObject *v)
454{
455 assert(PyFloat_Check(v));
456 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
457}
458
Christian Heimesf15c66e2007-12-11 00:54:34 +0000459#endif /* Py_BROKEN_REPR */
460
Neil Schemenauer32117e52001-01-04 01:44:34 +0000461/* Macro and helper that convert PyObject obj to a C double and store
462 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000463 slot function. If conversion to double raises an exception, obj is
464 set to NULL, and the function invoking this macro returns NULL. If
465 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
466 stored in obj, and returned from the function invoking this macro.
467*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000468#define CONVERT_TO_DOUBLE(obj, dbl) \
469 if (PyFloat_Check(obj)) \
470 dbl = PyFloat_AS_DOUBLE(obj); \
471 else if (convert_to_double(&(obj), &(dbl)) < 0) \
472 return obj;
473
474static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000475convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000476{
477 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000478
Neil Schemenauer32117e52001-01-04 01:44:34 +0000479 if (PyInt_Check(obj)) {
480 *dbl = (double)PyInt_AS_LONG(obj);
481 }
482 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000483 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000484 if (*dbl == -1.0 && PyErr_Occurred()) {
485 *v = NULL;
486 return -1;
487 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000488 }
489 else {
490 Py_INCREF(Py_NotImplemented);
491 *v = Py_NotImplemented;
492 return -1;
493 }
494 return 0;
495}
496
Guido van Rossum57072eb1999-12-23 19:00:28 +0000497/* Precisions used by repr() and str(), respectively.
498
499 The repr() precision (17 significant decimal digits) is the minimal number
500 that is guaranteed to have enough precision so that if the number is read
501 back in the exact same binary value is recreated. This is true for IEEE
502 floating point by design, and also happens to work for all other modern
503 hardware.
504
505 The str() precision is chosen so that in most cases, the rounding noise
506 created by various operations is suppressed, while giving plenty of
507 precision for practical use.
508
509*/
510
511#define PREC_REPR 17
512#define PREC_STR 12
513
Tim Peters97019e42001-11-28 22:43:45 +0000514/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
515 XXX they pass a char buffer without passing a length.
516*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000517void
Fred Drakefd99de62000-07-09 05:02:18 +0000518PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000519{
Tim Peters97019e42001-11-28 22:43:45 +0000520 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000521}
522
Tim Peters72f98e92001-05-08 15:19:57 +0000523void
524PyFloat_AsReprString(char *buf, PyFloatObject *v)
525{
Tim Peters97019e42001-11-28 22:43:45 +0000526 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000527}
528
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000529/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000530static int
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532{
533 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000534 format_float(buf, sizeof(buf), v,
535 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000536 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000538 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000539 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000543float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000545#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000546 char buf[30];
547 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000548#else
549 char buf[100];
550 format_float(buf, sizeof(buf), v, PREC_REPR);
551#endif
552
Guido van Rossum57072eb1999-12-23 19:00:28 +0000553 return PyString_FromString(buf);
554}
555
556static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000557float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000558{
559 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000560 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Tim Peters307fa782004-09-23 08:06:40 +0000564/* Comparison is pretty much a nightmare. When comparing float to float,
565 * we do it as straightforwardly (and long-windedly) as conceivable, so
566 * that, e.g., Python x == y delivers the same result as the platform
567 * C x == y when x and/or y is a NaN.
568 * When mixing float with an integer type, there's no good *uniform* approach.
569 * Converting the double to an integer obviously doesn't work, since we
570 * may lose info from fractional bits. Converting the integer to a double
571 * also has two failure modes: (1) a long int may trigger overflow (too
572 * large to fit in the dynamic range of a C double); (2) even a C long may have
573 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
574 * 63 bits of precision, but a C double probably has only 53), and then
575 * we can falsely claim equality when low-order integer bits are lost by
576 * coercion to double. So this part is painful too.
577 */
578
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000579static PyObject*
580float_richcompare(PyObject *v, PyObject *w, int op)
581{
582 double i, j;
583 int r = 0;
584
Tim Peters307fa782004-09-23 08:06:40 +0000585 assert(PyFloat_Check(v));
586 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000587
Tim Peters307fa782004-09-23 08:06:40 +0000588 /* Switch on the type of w. Set i and j to doubles to be compared,
589 * and op to the richcomp to use.
590 */
591 if (PyFloat_Check(w))
592 j = PyFloat_AS_DOUBLE(w);
593
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000594 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000595 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000596 /* If i is an infinity, its magnitude exceeds any
597 * finite integer, so it doesn't matter which int we
598 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000599 */
600 j = 0.0;
601 else
602 goto Unimplemented;
603 }
604
605 else if (PyInt_Check(w)) {
606 long jj = PyInt_AS_LONG(w);
607 /* In the worst realistic case I can imagine, C double is a
608 * Cray single with 48 bits of precision, and long has 64
609 * bits.
610 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000611#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000612 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
613 if (abs >> 48) {
614 /* Needs more than 48 bits. Make it take the
615 * PyLong path.
616 */
617 PyObject *result;
618 PyObject *ww = PyLong_FromLong(jj);
619
620 if (ww == NULL)
621 return NULL;
622 result = float_richcompare(v, ww, op);
623 Py_DECREF(ww);
624 return result;
625 }
626#endif
627 j = (double)jj;
628 assert((long)j == jj);
629 }
630
631 else if (PyLong_Check(w)) {
632 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
633 int wsign = _PyLong_Sign(w);
634 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000635 int exponent;
636
637 if (vsign != wsign) {
638 /* Magnitudes are irrelevant -- the signs alone
639 * determine the outcome.
640 */
641 i = (double)vsign;
642 j = (double)wsign;
643 goto Compare;
644 }
645 /* The signs are the same. */
646 /* Convert w to a double if it fits. In particular, 0 fits. */
647 nbits = _PyLong_NumBits(w);
648 if (nbits == (size_t)-1 && PyErr_Occurred()) {
649 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000650 * to hold the # of bits. Replace with little doubles
651 * that give the same outcome -- w is so large that
652 * its magnitude must exceed the magnitude of any
653 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000654 */
655 PyErr_Clear();
656 i = (double)vsign;
657 assert(wsign != 0);
658 j = wsign * 2.0;
659 goto Compare;
660 }
661 if (nbits <= 48) {
662 j = PyLong_AsDouble(w);
663 /* It's impossible that <= 48 bits overflowed. */
664 assert(j != -1.0 || ! PyErr_Occurred());
665 goto Compare;
666 }
667 assert(wsign != 0); /* else nbits was 0 */
668 assert(vsign != 0); /* if vsign were 0, then since wsign is
669 * not 0, we would have taken the
670 * vsign != wsign branch at the start */
671 /* We want to work with non-negative numbers. */
672 if (vsign < 0) {
673 /* "Multiply both sides" by -1; this also swaps the
674 * comparator.
675 */
676 i = -i;
677 op = _Py_SwappedOp[op];
678 }
679 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000680 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000681 /* exponent is the # of bits in v before the radix point;
682 * we know that nbits (the # of bits in w) > 48 at this point
683 */
684 if (exponent < 0 || (size_t)exponent < nbits) {
685 i = 1.0;
686 j = 2.0;
687 goto Compare;
688 }
689 if ((size_t)exponent > nbits) {
690 i = 2.0;
691 j = 1.0;
692 goto Compare;
693 }
694 /* v and w have the same number of bits before the radix
695 * point. Construct two longs that have the same comparison
696 * outcome.
697 */
698 {
699 double fracpart;
700 double intpart;
701 PyObject *result = NULL;
702 PyObject *one = NULL;
703 PyObject *vv = NULL;
704 PyObject *ww = w;
705
706 if (wsign < 0) {
707 ww = PyNumber_Negative(w);
708 if (ww == NULL)
709 goto Error;
710 }
711 else
712 Py_INCREF(ww);
713
714 fracpart = modf(i, &intpart);
715 vv = PyLong_FromDouble(intpart);
716 if (vv == NULL)
717 goto Error;
718
719 if (fracpart != 0.0) {
720 /* Shift left, and or a 1 bit into vv
721 * to represent the lost fraction.
722 */
723 PyObject *temp;
724
725 one = PyInt_FromLong(1);
726 if (one == NULL)
727 goto Error;
728
729 temp = PyNumber_Lshift(ww, one);
730 if (temp == NULL)
731 goto Error;
732 Py_DECREF(ww);
733 ww = temp;
734
735 temp = PyNumber_Lshift(vv, one);
736 if (temp == NULL)
737 goto Error;
738 Py_DECREF(vv);
739 vv = temp;
740
741 temp = PyNumber_Or(vv, one);
742 if (temp == NULL)
743 goto Error;
744 Py_DECREF(vv);
745 vv = temp;
746 }
747
748 r = PyObject_RichCompareBool(vv, ww, op);
749 if (r < 0)
750 goto Error;
751 result = PyBool_FromLong(r);
752 Error:
753 Py_XDECREF(vv);
754 Py_XDECREF(ww);
755 Py_XDECREF(one);
756 return result;
757 }
758 } /* else if (PyLong_Check(w)) */
759
760 else /* w isn't float, int, or long */
761 goto Unimplemented;
762
763 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000764 PyFPE_START_PROTECT("richcompare", return NULL)
765 switch (op) {
766 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000767 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000768 break;
769 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000770 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000771 break;
772 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000773 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000774 break;
775 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000776 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000777 break;
778 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000779 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000780 break;
781 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000782 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000783 break;
784 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000785 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000786 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000787
788 Unimplemented:
789 Py_INCREF(Py_NotImplemented);
790 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000791}
792
Guido van Rossum9bfef441993-03-29 10:43:31 +0000793static long
Fred Drakefd99de62000-07-09 05:02:18 +0000794float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000795{
Tim Peters39dce292000-08-15 03:34:48 +0000796 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000797}
798
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000799static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000800float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000802 double a,b;
803 CONVERT_TO_DOUBLE(v, a);
804 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000805 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000806 a = a + b;
807 PyFPE_END_PROTECT(a)
808 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809}
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000812float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000814 double a,b;
815 CONVERT_TO_DOUBLE(v, a);
816 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000817 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000818 a = a - b;
819 PyFPE_END_PROTECT(a)
820 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821}
822
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000823static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000824float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000826 double a,b;
827 CONVERT_TO_DOUBLE(v, a);
828 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000829 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000830 a = a * b;
831 PyFPE_END_PROTECT(a)
832 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000836float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000838 double a,b;
839 CONVERT_TO_DOUBLE(v, a);
840 CONVERT_TO_DOUBLE(w, b);
841 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000842 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000843 return NULL;
844 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000845 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000846 a = a / b;
847 PyFPE_END_PROTECT(a)
848 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000849}
850
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000851static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000852float_classic_div(PyObject *v, PyObject *w)
853{
854 double a,b;
855 CONVERT_TO_DOUBLE(v, a);
856 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000857 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000858 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
859 return NULL;
860 if (b == 0.0) {
861 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
862 return NULL;
863 }
864 PyFPE_START_PROTECT("divide", return 0)
865 a = a / b;
866 PyFPE_END_PROTECT(a)
867 return PyFloat_FromDouble(a);
868}
869
870static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000871float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000873 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000874 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000875 CONVERT_TO_DOUBLE(v, vx);
876 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000878 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879 return NULL;
880 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000881 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000882 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000883 /* note: checking mod*wx < 0 is incorrect -- underflows to
884 0 if wx < sqrt(smallest nonzero double) */
885 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000886 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000887 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000888 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000890}
891
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000892static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000893float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000894{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000895 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000896 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000897 CONVERT_TO_DOUBLE(v, vx);
898 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000899 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000900 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000901 return NULL;
902 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000903 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000904 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000905 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000906 exact multiple of wx. But this is fp arithmetic, and fp
907 vx - mod is an approximation; the result is that div may
908 not be an exact integral value after the division, although
909 it will always be very close to one.
910 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000911 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000912 if (mod) {
913 /* ensure the remainder has the same sign as the denominator */
914 if ((wx < 0) != (mod < 0)) {
915 mod += wx;
916 div -= 1.0;
917 }
918 }
919 else {
920 /* the remainder is zero, and in the presence of signed zeroes
921 fmod returns different results across platforms; ensure
922 it has the same sign as the denominator; we'd like to do
923 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000924 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000925 if (wx < 0.0)
926 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000927 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000928 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000929 if (div) {
930 floordiv = floor(div);
931 if (div - floordiv > 0.5)
932 floordiv += 1.0;
933 }
934 else {
935 /* div is zero - get the same sign as the true quotient */
936 div *= div; /* hide "div = +0" from optimizers */
937 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
938 }
939 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000940 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000941}
942
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000944float_floor_div(PyObject *v, PyObject *w)
945{
946 PyObject *t, *r;
947
948 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000949 if (t == NULL || t == Py_NotImplemented)
950 return t;
951 assert(PyTuple_CheckExact(t));
952 r = PyTuple_GET_ITEM(t, 0);
953 Py_INCREF(r);
954 Py_DECREF(t);
955 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000956}
957
958static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000959float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000960{
961 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000962
963 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000964 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000965 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000966 return NULL;
967 }
968
Neil Schemenauer32117e52001-01-04 01:44:34 +0000969 CONVERT_TO_DOUBLE(v, iv);
970 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000971
972 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000973 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000974 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000975 }
Tim Peters96685bf2001-08-23 22:31:37 +0000976 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000977 if (iw < 0.0) {
978 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000979 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000980 return NULL;
981 }
982 return PyFloat_FromDouble(0.0);
983 }
Tim Peterse87568d2003-05-24 20:18:24 +0000984 if (iv < 0.0) {
985 /* Whether this is an error is a mess, and bumps into libm
986 * bugs so we have to figure it out ourselves.
987 */
988 if (iw != floor(iw)) {
989 PyErr_SetString(PyExc_ValueError, "negative number "
990 "cannot be raised to a fractional power");
991 return NULL;
992 }
993 /* iw is an exact integer, albeit perhaps a very large one.
994 * -1 raised to an exact integer should never be exceptional.
995 * Alas, some libms (chiefly glibc as of early 2003) return
996 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
997 * happen to be representable in a *C* integer. That's a
998 * bug; we let that slide in math.pow() (which currently
999 * reflects all platform accidents), but not for Python's **.
1000 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001001 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001002 /* Return 1 if iw is even, -1 if iw is odd; there's
1003 * no guarantee that any C integral type is big
1004 * enough to hold iw, so we have to check this
1005 * indirectly.
1006 */
1007 ix = floor(iw * 0.5) * 2.0;
1008 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1009 }
1010 /* Else iv != -1.0, and overflow or underflow are possible.
1011 * Unless we're to write pow() ourselves, we have to trust
1012 * the platform to do this correctly.
1013 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001014 }
Tim Peters96685bf2001-08-23 22:31:37 +00001015 errno = 0;
1016 PyFPE_START_PROTECT("pow", return NULL)
1017 ix = pow(iv, iw);
1018 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001019 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001020 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001021 /* We don't expect any errno value other than ERANGE, but
1022 * the range of libm bugs appears unbounded.
1023 */
Alex Martelli348dc882006-08-23 22:17:59 +00001024 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1025 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001026 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001027 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001029}
1030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001031static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001032float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001033{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001034 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001035}
1036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001037static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001038float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001039{
Tim Peters0280cf72001-09-11 21:53:35 +00001040 if (PyFloat_CheckExact(v)) {
1041 Py_INCREF(v);
1042 return (PyObject *)v;
1043 }
1044 else
1045 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001046}
1047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001048static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001049float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001050{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001051 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001052}
1053
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001054static int
Fred Drakefd99de62000-07-09 05:02:18 +00001055float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001056{
1057 return v->ob_fval != 0.0;
1058}
1059
Guido van Rossum234f9421993-06-17 12:35:49 +00001060static int
Fred Drakefd99de62000-07-09 05:02:18 +00001061float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001062{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001063 if (PyInt_Check(*pw)) {
1064 long x = PyInt_AsLong(*pw);
1065 *pw = PyFloat_FromDouble((double)x);
1066 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001067 return 0;
1068 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001069 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001070 double x = PyLong_AsDouble(*pw);
1071 if (x == -1.0 && PyErr_Occurred())
1072 return -1;
1073 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001074 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001075 return 0;
1076 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001077 else if (PyFloat_Check(*pw)) {
1078 Py_INCREF(*pv);
1079 Py_INCREF(*pw);
1080 return 0;
1081 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001082 return 1; /* Can't do it */
1083}
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00001086float_long(PyObject *v)
1087{
1088 double x = PyFloat_AsDouble(v);
1089 return PyLong_FromDouble(x);
1090}
1091
1092static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001093float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001094{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001095 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001096 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001097
1098 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001099 /* Try to get out cheap if this fits in a Python int. The attempt
1100 * to cast to long must be protected, as C doesn't define what
1101 * happens if the double is too big to fit in a long. Some rare
1102 * systems raise an exception then (RISCOS was mentioned as one,
1103 * and someone using a non-default option on Sun also bumped into
1104 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1105 * still be vulnerable: if a long has more bits of precision than
1106 * a double, casting MIN/MAX to double may yield an approximation,
1107 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1108 * yield true from the C expression wholepart<=LONG_MAX, despite
1109 * that wholepart is actually greater than LONG_MAX.
1110 */
1111 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1112 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001113 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001114 }
1115 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001116}
1117
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001118static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001119float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001120{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001121 if (PyFloat_CheckExact(v))
1122 Py_INCREF(v);
1123 else
1124 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001125 return v;
1126}
1127
1128
Jeremy Hylton938ace62002-07-17 16:30:39 +00001129static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001130float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1131
Tim Peters6d6c1a32001-08-02 04:15:00 +00001132static PyObject *
1133float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1134{
1135 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001136 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001137
Guido van Rossumbef14172001-08-29 15:47:46 +00001138 if (type != &PyFloat_Type)
1139 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1141 return NULL;
1142 if (PyString_Check(x))
1143 return PyFloat_FromString(x, NULL);
1144 return PyNumber_Float(x);
1145}
1146
Guido van Rossumbef14172001-08-29 15:47:46 +00001147/* Wimpy, slow approach to tp_new calls for subtypes of float:
1148 first create a regular float from whatever arguments we got,
1149 then allocate a subtype instance and initialize its ob_fval
1150 from the regular float. The regular float is then thrown away.
1151*/
1152static PyObject *
1153float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1154{
Anthony Baxter377be112006-04-11 06:54:30 +00001155 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001156
1157 assert(PyType_IsSubtype(type, &PyFloat_Type));
1158 tmp = float_new(&PyFloat_Type, args, kwds);
1159 if (tmp == NULL)
1160 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001161 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001162 newobj = type->tp_alloc(type, 0);
1163 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001164 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001165 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001166 }
Anthony Baxter377be112006-04-11 06:54:30 +00001167 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001168 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001169 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001170}
1171
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001172static PyObject *
1173float_getnewargs(PyFloatObject *v)
1174{
1175 return Py_BuildValue("(d)", v->ob_fval);
1176}
1177
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001178/* this is for the benefit of the pack/unpack routines below */
1179
1180typedef enum {
1181 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1182} float_format_type;
1183
1184static float_format_type double_format, float_format;
1185static float_format_type detected_double_format, detected_float_format;
1186
1187static PyObject *
1188float_getformat(PyTypeObject *v, PyObject* arg)
1189{
1190 char* s;
1191 float_format_type r;
1192
1193 if (!PyString_Check(arg)) {
1194 PyErr_Format(PyExc_TypeError,
1195 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001196 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001197 return NULL;
1198 }
1199 s = PyString_AS_STRING(arg);
1200 if (strcmp(s, "double") == 0) {
1201 r = double_format;
1202 }
1203 else if (strcmp(s, "float") == 0) {
1204 r = float_format;
1205 }
1206 else {
1207 PyErr_SetString(PyExc_ValueError,
1208 "__getformat__() argument 1 must be "
1209 "'double' or 'float'");
1210 return NULL;
1211 }
1212
1213 switch (r) {
1214 case unknown_format:
1215 return PyString_FromString("unknown");
1216 case ieee_little_endian_format:
1217 return PyString_FromString("IEEE, little-endian");
1218 case ieee_big_endian_format:
1219 return PyString_FromString("IEEE, big-endian");
1220 default:
1221 Py_FatalError("insane float_format or double_format");
1222 return NULL;
1223 }
1224}
1225
1226PyDoc_STRVAR(float_getformat_doc,
1227"float.__getformat__(typestr) -> string\n"
1228"\n"
1229"You probably don't want to use this function. It exists mainly to be\n"
1230"used in Python's test suite.\n"
1231"\n"
1232"typestr must be 'double' or 'float'. This function returns whichever of\n"
1233"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1234"format of floating point numbers used by the C type named by typestr.");
1235
1236static PyObject *
1237float_setformat(PyTypeObject *v, PyObject* args)
1238{
1239 char* typestr;
1240 char* format;
1241 float_format_type f;
1242 float_format_type detected;
1243 float_format_type *p;
1244
1245 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1246 return NULL;
1247
1248 if (strcmp(typestr, "double") == 0) {
1249 p = &double_format;
1250 detected = detected_double_format;
1251 }
1252 else if (strcmp(typestr, "float") == 0) {
1253 p = &float_format;
1254 detected = detected_float_format;
1255 }
1256 else {
1257 PyErr_SetString(PyExc_ValueError,
1258 "__setformat__() argument 1 must "
1259 "be 'double' or 'float'");
1260 return NULL;
1261 }
1262
1263 if (strcmp(format, "unknown") == 0) {
1264 f = unknown_format;
1265 }
1266 else if (strcmp(format, "IEEE, little-endian") == 0) {
1267 f = ieee_little_endian_format;
1268 }
1269 else if (strcmp(format, "IEEE, big-endian") == 0) {
1270 f = ieee_big_endian_format;
1271 }
1272 else {
1273 PyErr_SetString(PyExc_ValueError,
1274 "__setformat__() argument 2 must be "
1275 "'unknown', 'IEEE, little-endian' or "
1276 "'IEEE, big-endian'");
1277 return NULL;
1278
1279 }
1280
1281 if (f != unknown_format && f != detected) {
1282 PyErr_Format(PyExc_ValueError,
1283 "can only set %s format to 'unknown' or the "
1284 "detected platform value", typestr);
1285 return NULL;
1286 }
1287
1288 *p = f;
1289 Py_RETURN_NONE;
1290}
1291
1292PyDoc_STRVAR(float_setformat_doc,
1293"float.__setformat__(typestr, fmt) -> None\n"
1294"\n"
1295"You probably don't want to use this function. It exists mainly to be\n"
1296"used in Python's test suite.\n"
1297"\n"
1298"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1299"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1300"one of the latter two if it appears to match the underlying C reality.\n"
1301"\n"
1302"Overrides the automatic determination of C-level floating point type.\n"
1303"This affects how floats are converted to and from binary strings.");
1304
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001305static PyMethodDef float_methods[] = {
1306 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001307 {"__getformat__", (PyCFunction)float_getformat,
1308 METH_O|METH_CLASS, float_getformat_doc},
1309 {"__setformat__", (PyCFunction)float_setformat,
1310 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001311 {NULL, NULL} /* sentinel */
1312};
1313
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001314PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315"float(x) -> floating point number\n\
1316\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001317Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318
1319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001320static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001321 float_add, /*nb_add*/
1322 float_sub, /*nb_subtract*/
1323 float_mul, /*nb_multiply*/
1324 float_classic_div, /*nb_divide*/
1325 float_rem, /*nb_remainder*/
1326 float_divmod, /*nb_divmod*/
1327 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001328 (unaryfunc)float_neg, /*nb_negative*/
1329 (unaryfunc)float_pos, /*nb_positive*/
1330 (unaryfunc)float_abs, /*nb_absolute*/
1331 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001332 0, /*nb_invert*/
1333 0, /*nb_lshift*/
1334 0, /*nb_rshift*/
1335 0, /*nb_and*/
1336 0, /*nb_xor*/
1337 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001338 float_coerce, /*nb_coerce*/
1339 float_int, /*nb_int*/
1340 float_long, /*nb_long*/
1341 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001342 0, /* nb_oct */
1343 0, /* nb_hex */
1344 0, /* nb_inplace_add */
1345 0, /* nb_inplace_subtract */
1346 0, /* nb_inplace_multiply */
1347 0, /* nb_inplace_divide */
1348 0, /* nb_inplace_remainder */
1349 0, /* nb_inplace_power */
1350 0, /* nb_inplace_lshift */
1351 0, /* nb_inplace_rshift */
1352 0, /* nb_inplace_and */
1353 0, /* nb_inplace_xor */
1354 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001355 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001356 float_div, /* nb_true_divide */
1357 0, /* nb_inplace_floor_divide */
1358 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001359};
1360
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001361PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001362 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001363 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001364 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001365 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 (destructor)float_dealloc, /* tp_dealloc */
1367 (printfunc)float_print, /* tp_print */
1368 0, /* tp_getattr */
1369 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001370 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371 (reprfunc)float_repr, /* tp_repr */
1372 &float_as_number, /* tp_as_number */
1373 0, /* tp_as_sequence */
1374 0, /* tp_as_mapping */
1375 (hashfunc)float_hash, /* tp_hash */
1376 0, /* tp_call */
1377 (reprfunc)float_str, /* tp_str */
1378 PyObject_GenericGetAttr, /* tp_getattro */
1379 0, /* tp_setattro */
1380 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1382 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 float_doc, /* tp_doc */
1384 0, /* tp_traverse */
1385 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001386 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001387 0, /* tp_weaklistoffset */
1388 0, /* tp_iter */
1389 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001390 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 0, /* tp_members */
1392 0, /* tp_getset */
1393 0, /* tp_base */
1394 0, /* tp_dict */
1395 0, /* tp_descr_get */
1396 0, /* tp_descr_set */
1397 0, /* tp_dictoffset */
1398 0, /* tp_init */
1399 0, /* tp_alloc */
1400 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001401};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001402
1403void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001404_PyFloat_Init(void)
1405{
1406 /* We attempt to determine if this machine is using IEEE
1407 floating point formats by peering at the bits of some
1408 carefully chosen values. If it looks like we are on an
1409 IEEE platform, the float packing/unpacking routines can
1410 just copy bits, if not they resort to arithmetic & shifts
1411 and masks. The shifts & masks approach works on all finite
1412 values, but what happens to infinities, NaNs and signed
1413 zeroes on packing is an accident, and attempting to unpack
1414 a NaN or an infinity will raise an exception.
1415
1416 Note that if we're on some whacked-out platform which uses
1417 IEEE formats but isn't strictly little-endian or big-
1418 endian, we will fall back to the portable shifts & masks
1419 method. */
1420
1421#if SIZEOF_DOUBLE == 8
1422 {
1423 double x = 9006104071832581.0;
1424 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1425 detected_double_format = ieee_big_endian_format;
1426 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1427 detected_double_format = ieee_little_endian_format;
1428 else
1429 detected_double_format = unknown_format;
1430 }
1431#else
1432 detected_double_format = unknown_format;
1433#endif
1434
1435#if SIZEOF_FLOAT == 4
1436 {
1437 float y = 16711938.0;
1438 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1439 detected_float_format = ieee_big_endian_format;
1440 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1441 detected_float_format = ieee_little_endian_format;
1442 else
1443 detected_float_format = unknown_format;
1444 }
1445#else
1446 detected_float_format = unknown_format;
1447#endif
1448
1449 double_format = detected_double_format;
1450 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001451
1452#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001453 /* Initialize floating point repr */
1454 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001455#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001456}
1457
1458void
Fred Drakefd99de62000-07-09 05:02:18 +00001459PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001460{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001461 PyFloatObject *p;
1462 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001463 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001464 int bc, bf; /* block count, number of freed blocks */
1465 int frem, fsum; /* remaining unfreed floats per block, total */
1466
1467 bc = 0;
1468 bf = 0;
1469 fsum = 0;
1470 list = block_list;
1471 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001472 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001473 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001474 bc++;
1475 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001476 for (i = 0, p = &list->objects[0];
1477 i < N_FLOATOBJECTS;
1478 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001479 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001480 frem++;
1481 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001482 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001483 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001484 list->next = block_list;
1485 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001486 for (i = 0, p = &list->objects[0];
1487 i < N_FLOATOBJECTS;
1488 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001489 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001490 Py_REFCNT(p) == 0) {
1491 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001492 free_list;
1493 free_list = p;
1494 }
1495 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001496 }
1497 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001498 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001499 bf++;
1500 }
1501 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001502 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001503 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001504 if (!Py_VerboseFlag)
1505 return;
1506 fprintf(stderr, "# cleanup floats");
1507 if (!fsum) {
1508 fprintf(stderr, "\n");
1509 }
1510 else {
1511 fprintf(stderr,
1512 ": %d unfreed float%s in %d out of %d block%s\n",
1513 fsum, fsum == 1 ? "" : "s",
1514 bc - bf, bc, bc == 1 ? "" : "s");
1515 }
1516 if (Py_VerboseFlag > 1) {
1517 list = block_list;
1518 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001519 for (i = 0, p = &list->objects[0];
1520 i < N_FLOATOBJECTS;
1521 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001522 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001523 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001524 char buf[100];
1525 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001526 /* XXX(twouters) cast refcount to
1527 long until %zd is universally
1528 available
1529 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001530 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001531 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001532 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001533 }
1534 }
1535 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001536 }
1537 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001538}
Tim Peters9905b942003-03-20 20:53:32 +00001539
1540/*----------------------------------------------------------------------------
1541 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1542 *
1543 * TODO: On platforms that use the standard IEEE-754 single and double
1544 * formats natively, these routines could simply copy the bytes.
1545 */
1546int
1547_PyFloat_Pack4(double x, unsigned char *p, int le)
1548{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001549 if (float_format == unknown_format) {
1550 unsigned char sign;
1551 int e;
1552 double f;
1553 unsigned int fbits;
1554 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001555
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001556 if (le) {
1557 p += 3;
1558 incr = -1;
1559 }
Tim Peters9905b942003-03-20 20:53:32 +00001560
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001561 if (x < 0) {
1562 sign = 1;
1563 x = -x;
1564 }
1565 else
1566 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001567
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001568 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001569
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001570 /* Normalize f to be in the range [1.0, 2.0) */
1571 if (0.5 <= f && f < 1.0) {
1572 f *= 2.0;
1573 e--;
1574 }
1575 else if (f == 0.0)
1576 e = 0;
1577 else {
1578 PyErr_SetString(PyExc_SystemError,
1579 "frexp() result out of range");
1580 return -1;
1581 }
1582
1583 if (e >= 128)
1584 goto Overflow;
1585 else if (e < -126) {
1586 /* Gradual underflow */
1587 f = ldexp(f, 126 + e);
1588 e = 0;
1589 }
1590 else if (!(e == 0 && f == 0.0)) {
1591 e += 127;
1592 f -= 1.0; /* Get rid of leading 1 */
1593 }
1594
1595 f *= 8388608.0; /* 2**23 */
1596 fbits = (unsigned int)(f + 0.5); /* Round */
1597 assert(fbits <= 8388608);
1598 if (fbits >> 23) {
1599 /* The carry propagated out of a string of 23 1 bits. */
1600 fbits = 0;
1601 ++e;
1602 if (e >= 255)
1603 goto Overflow;
1604 }
1605
1606 /* First byte */
1607 *p = (sign << 7) | (e >> 1);
1608 p += incr;
1609
1610 /* Second byte */
1611 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1612 p += incr;
1613
1614 /* Third byte */
1615 *p = (fbits >> 8) & 0xFF;
1616 p += incr;
1617
1618 /* Fourth byte */
1619 *p = fbits & 0xFF;
1620
1621 /* Done */
1622 return 0;
1623
1624 Overflow:
1625 PyErr_SetString(PyExc_OverflowError,
1626 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001627 return -1;
1628 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001629 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001630 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001631 const char *s = (char*)&y;
1632 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001633
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001634 if ((float_format == ieee_little_endian_format && !le)
1635 || (float_format == ieee_big_endian_format && le)) {
1636 p += 3;
1637 incr = -1;
1638 }
1639
1640 for (i = 0; i < 4; i++) {
1641 *p = *s++;
1642 p += incr;
1643 }
1644 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001645 }
Tim Peters9905b942003-03-20 20:53:32 +00001646}
1647
1648int
1649_PyFloat_Pack8(double x, unsigned char *p, int le)
1650{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651 if (double_format == unknown_format) {
1652 unsigned char sign;
1653 int e;
1654 double f;
1655 unsigned int fhi, flo;
1656 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001657
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001658 if (le) {
1659 p += 7;
1660 incr = -1;
1661 }
Tim Peters9905b942003-03-20 20:53:32 +00001662
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001663 if (x < 0) {
1664 sign = 1;
1665 x = -x;
1666 }
1667 else
1668 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001669
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001670 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001671
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001672 /* Normalize f to be in the range [1.0, 2.0) */
1673 if (0.5 <= f && f < 1.0) {
1674 f *= 2.0;
1675 e--;
1676 }
1677 else if (f == 0.0)
1678 e = 0;
1679 else {
1680 PyErr_SetString(PyExc_SystemError,
1681 "frexp() result out of range");
1682 return -1;
1683 }
1684
1685 if (e >= 1024)
1686 goto Overflow;
1687 else if (e < -1022) {
1688 /* Gradual underflow */
1689 f = ldexp(f, 1022 + e);
1690 e = 0;
1691 }
1692 else if (!(e == 0 && f == 0.0)) {
1693 e += 1023;
1694 f -= 1.0; /* Get rid of leading 1 */
1695 }
1696
1697 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1698 f *= 268435456.0; /* 2**28 */
1699 fhi = (unsigned int)f; /* Truncate */
1700 assert(fhi < 268435456);
1701
1702 f -= (double)fhi;
1703 f *= 16777216.0; /* 2**24 */
1704 flo = (unsigned int)(f + 0.5); /* Round */
1705 assert(flo <= 16777216);
1706 if (flo >> 24) {
1707 /* The carry propagated out of a string of 24 1 bits. */
1708 flo = 0;
1709 ++fhi;
1710 if (fhi >> 28) {
1711 /* And it also progagated out of the next 28 bits. */
1712 fhi = 0;
1713 ++e;
1714 if (e >= 2047)
1715 goto Overflow;
1716 }
1717 }
1718
1719 /* First byte */
1720 *p = (sign << 7) | (e >> 4);
1721 p += incr;
1722
1723 /* Second byte */
1724 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1725 p += incr;
1726
1727 /* Third byte */
1728 *p = (fhi >> 16) & 0xFF;
1729 p += incr;
1730
1731 /* Fourth byte */
1732 *p = (fhi >> 8) & 0xFF;
1733 p += incr;
1734
1735 /* Fifth byte */
1736 *p = fhi & 0xFF;
1737 p += incr;
1738
1739 /* Sixth byte */
1740 *p = (flo >> 16) & 0xFF;
1741 p += incr;
1742
1743 /* Seventh byte */
1744 *p = (flo >> 8) & 0xFF;
1745 p += incr;
1746
1747 /* Eighth byte */
1748 *p = flo & 0xFF;
1749 p += incr;
1750
1751 /* Done */
1752 return 0;
1753
1754 Overflow:
1755 PyErr_SetString(PyExc_OverflowError,
1756 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001757 return -1;
1758 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001759 else {
1760 const char *s = (char*)&x;
1761 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001762
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001763 if ((double_format == ieee_little_endian_format && !le)
1764 || (double_format == ieee_big_endian_format && le)) {
1765 p += 7;
1766 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001767 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001768
1769 for (i = 0; i < 8; i++) {
1770 *p = *s++;
1771 p += incr;
1772 }
1773 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001774 }
Tim Peters9905b942003-03-20 20:53:32 +00001775}
1776
1777double
1778_PyFloat_Unpack4(const unsigned char *p, int le)
1779{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001780 if (float_format == unknown_format) {
1781 unsigned char sign;
1782 int e;
1783 unsigned int f;
1784 double x;
1785 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001786
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001787 if (le) {
1788 p += 3;
1789 incr = -1;
1790 }
1791
1792 /* First byte */
1793 sign = (*p >> 7) & 1;
1794 e = (*p & 0x7F) << 1;
1795 p += incr;
1796
1797 /* Second byte */
1798 e |= (*p >> 7) & 1;
1799 f = (*p & 0x7F) << 16;
1800 p += incr;
1801
1802 if (e == 255) {
1803 PyErr_SetString(
1804 PyExc_ValueError,
1805 "can't unpack IEEE 754 special value "
1806 "on non-IEEE platform");
1807 return -1;
1808 }
1809
1810 /* Third byte */
1811 f |= *p << 8;
1812 p += incr;
1813
1814 /* Fourth byte */
1815 f |= *p;
1816
1817 x = (double)f / 8388608.0;
1818
1819 /* XXX This sadly ignores Inf/NaN issues */
1820 if (e == 0)
1821 e = -126;
1822 else {
1823 x += 1.0;
1824 e -= 127;
1825 }
1826 x = ldexp(x, e);
1827
1828 if (sign)
1829 x = -x;
1830
1831 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001832 }
Tim Peters9905b942003-03-20 20:53:32 +00001833 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001834 float x;
1835
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001836 if ((float_format == ieee_little_endian_format && !le)
1837 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001838 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001839 char *d = &buf[3];
1840 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001841
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001842 for (i = 0; i < 4; i++) {
1843 *d-- = *p++;
1844 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001845 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001846 }
1847 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001848 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001849 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001850
1851 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001852 }
Tim Peters9905b942003-03-20 20:53:32 +00001853}
1854
1855double
1856_PyFloat_Unpack8(const unsigned char *p, int le)
1857{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001858 if (double_format == unknown_format) {
1859 unsigned char sign;
1860 int e;
1861 unsigned int fhi, flo;
1862 double x;
1863 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001864
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001865 if (le) {
1866 p += 7;
1867 incr = -1;
1868 }
1869
1870 /* First byte */
1871 sign = (*p >> 7) & 1;
1872 e = (*p & 0x7F) << 4;
1873
1874 p += incr;
1875
1876 /* Second byte */
1877 e |= (*p >> 4) & 0xF;
1878 fhi = (*p & 0xF) << 24;
1879 p += incr;
1880
1881 if (e == 2047) {
1882 PyErr_SetString(
1883 PyExc_ValueError,
1884 "can't unpack IEEE 754 special value "
1885 "on non-IEEE platform");
1886 return -1.0;
1887 }
1888
1889 /* Third byte */
1890 fhi |= *p << 16;
1891 p += incr;
1892
1893 /* Fourth byte */
1894 fhi |= *p << 8;
1895 p += incr;
1896
1897 /* Fifth byte */
1898 fhi |= *p;
1899 p += incr;
1900
1901 /* Sixth byte */
1902 flo = *p << 16;
1903 p += incr;
1904
1905 /* Seventh byte */
1906 flo |= *p << 8;
1907 p += incr;
1908
1909 /* Eighth byte */
1910 flo |= *p;
1911
1912 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1913 x /= 268435456.0; /* 2**28 */
1914
1915 if (e == 0)
1916 e = -1022;
1917 else {
1918 x += 1.0;
1919 e -= 1023;
1920 }
1921 x = ldexp(x, e);
1922
1923 if (sign)
1924 x = -x;
1925
1926 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001927 }
Tim Peters9905b942003-03-20 20:53:32 +00001928 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001929 double x;
1930
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931 if ((double_format == ieee_little_endian_format && !le)
1932 || (double_format == ieee_big_endian_format && le)) {
1933 char buf[8];
1934 char *d = &buf[7];
1935 int i;
1936
1937 for (i = 0; i < 8; i++) {
1938 *d-- = *p++;
1939 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001940 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001941 }
1942 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001943 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001944 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001945
1946 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001947 }
Tim Peters9905b942003-03-20 20:53:32 +00001948}