blob: bf9b1728621ee5ce1677b0810707ca12e33ffdbc [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>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Jack Janseneddc1442003-11-20 01:44:59 +000011#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000012extern double fmod(double, double);
13extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000014#endif
15
Guido van Rossum93ad0df1997-05-13 21:00:42 +000016/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000017#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000018#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000019#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000020
Guido van Rossum3fce8831999-03-12 19:43:17 +000021struct _floatblock {
22 struct _floatblock *next;
23 PyFloatObject objects[N_FLOATOBJECTS];
24};
25
26typedef struct _floatblock PyFloatBlock;
27
28static PyFloatBlock *block_list = NULL;
29static PyFloatObject *free_list = NULL;
30
Guido van Rossum93ad0df1997-05-13 21:00:42 +000031static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000032fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000033{
34 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000035 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
36 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000037 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000038 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000039 ((PyFloatBlock *)p)->next = block_list;
40 block_list = (PyFloatBlock *)p;
41 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042 q = p + N_FLOATOBJECTS;
43 while (--q > p)
Martin v. Löwis68192102007-07-21 06:55:02 +000044 Py_Type(q) = (struct _typeobject *)(q-1);
45 Py_Type(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046 return p + N_FLOATOBJECTS - 1;
47}
48
Guido van Rossumc0b618a1997-05-02 03:12:38 +000049PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000050PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051{
Guido van Rossum93ad0df1997-05-13 21:00:42 +000052 register PyFloatObject *op;
53 if (free_list == NULL) {
54 if ((free_list = fill_free_list()) == NULL)
55 return NULL;
56 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +000057 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 op = free_list;
Martin v. Löwis68192102007-07-21 06:55:02 +000059 free_list = (PyFloatObject *)Py_Type(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +000060 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +000061 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063}
64
Tim Petersef14d732000-09-23 03:39:17 +000065/**************************************************************************
66RED_FLAG 22-Sep-2000 tim
67PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
68
691. If v was a regular string, *pend was set to point to its terminating
70 null byte. That's useless (the caller can find that without any
71 help from this function!).
72
732. If v was a Unicode string, or an object convertible to a character
74 buffer, *pend was set to point into stack trash (the auto temp
75 vector holding the character buffer). That was downright dangerous.
76
77Since we can't change the interface of a public API function, pend is
78still supported but now *officially* useless: if pend is not NULL,
79*pend is set to NULL.
80**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +000081PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000082PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +000083{
Guido van Rossum4c08d552000-03-10 22:55:18 +000084 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000085 double x;
Tim Petersef14d732000-09-23 03:39:17 +000086 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000087#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +000088 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000089#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +000090 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000091
Tim Petersef14d732000-09-23 03:39:17 +000092 if (pend)
93 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +000094 if (PyString_Check(v)) {
95 s = PyString_AS_STRING(v);
96 len = PyString_GET_SIZE(v);
97 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +000098#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +000099 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000100 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000101 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000102 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000103 return NULL;
104 }
Tim Petersef14d732000-09-23 03:39:17 +0000105 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000106 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000107 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000108 NULL))
109 return NULL;
110 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000111 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000112 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000113#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000114 else if (PyObject_AsCharBuffer(v, &s, &len)) {
115 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000116 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000117 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000118 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000119
Guido van Rossum4c08d552000-03-10 22:55:18 +0000120 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000121 while (*s && isspace(Py_CHARMASK(*s)))
122 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000123 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000124 PyErr_SetString(PyExc_ValueError, "empty string for float()");
125 return NULL;
126 }
Tim Petersef14d732000-09-23 03:39:17 +0000127 /* We don't care about overflow or underflow. If the platform supports
128 * them, infinities and signed zeroes (on underflow) are fine.
129 * However, strtod can return 0 for denormalized numbers, where atof
130 * does not. So (alas!) we special-case a zero result. Note that
131 * whether strtod sets errno on underflow is not defined, so we can't
132 * key off errno.
133 */
Tim Peters858346e2000-09-25 21:01:28 +0000134 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000135 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000136 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000137 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000138 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000139 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000140 if (end > last)
141 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000142 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000143 PyOS_snprintf(buffer, sizeof(buffer),
144 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000145 PyErr_SetString(PyExc_ValueError, buffer);
146 return NULL;
147 }
148 /* Since end != s, the platform made *some* kind of sense out
149 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000150 while (*end && isspace(Py_CHARMASK(*end)))
151 end++;
152 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000153 PyOS_snprintf(buffer, sizeof(buffer),
154 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000155 PyErr_SetString(PyExc_ValueError, buffer);
156 return NULL;
157 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000158 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159 PyErr_SetString(PyExc_ValueError,
160 "null byte in argument for float()");
161 return NULL;
162 }
Tim Petersef14d732000-09-23 03:39:17 +0000163 if (x == 0.0) {
164 /* See above -- may have been strtod being anal
165 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000166 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000167 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000168 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000169 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000170 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 return PyFloat_FromDouble(x);
172}
173
Guido van Rossum234f9421993-06-17 12:35:49 +0000174static void
Fred Drakefd99de62000-07-09 05:02:18 +0000175float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000176{
Guido van Rossum9475a232001-10-05 20:51:39 +0000177 if (PyFloat_CheckExact(op)) {
Martin v. Löwis68192102007-07-21 06:55:02 +0000178 Py_Type(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000179 free_list = op;
180 }
181 else
Martin v. Löwis68192102007-07-21 06:55:02 +0000182 Py_Type(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000183}
184
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185double
Fred Drakefd99de62000-07-09 05:02:18 +0000186PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 PyNumberMethods *nb;
189 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000190 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000191
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 if (op && PyFloat_Check(op))
193 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000194
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000195 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197 return -1;
198 }
Tim Petersd2364e82001-11-01 20:09:42 +0000199
Martin v. Löwis68192102007-07-21 06:55:02 +0000200 if ((nb = Py_Type(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000201 PyErr_SetString(PyExc_TypeError, "a float is required");
202 return -1;
203 }
204
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206 if (fo == NULL)
207 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 if (!PyFloat_Check(fo)) {
209 PyErr_SetString(PyExc_TypeError,
210 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000211 return -1;
212 }
Tim Petersd2364e82001-11-01 20:09:42 +0000213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 val = PyFloat_AS_DOUBLE(fo);
215 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000216
Guido van Rossumb6775db1994-08-01 11:34:53 +0000217 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
220/* Methods */
221
Tim Peters97019e42001-11-28 22:43:45 +0000222static void
223format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
225 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000226 char format[32];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227 /* Subroutine for float_repr and float_print.
228 We want float numbers to be recognizable as such,
229 i.e., they should contain a decimal point or an exponent.
230 However, %g may print the number as an integer;
231 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000232
233 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000234 PyOS_snprintf(format, 32, "%%.%ig", precision);
235 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236 cp = buf;
237 if (*cp == '-')
238 cp++;
239 for (; *cp != '\0'; cp++) {
240 /* Any non-digit means it's not an integer;
241 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000242 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243 break;
244 }
245 if (*cp == '\0') {
246 *cp++ = '.';
247 *cp++ = '0';
248 *cp++ = '\0';
249 }
250}
251
Tim Peters97019e42001-11-28 22:43:45 +0000252/* XXX PyFloat_AsStringEx should not be a public API function (for one
253 XXX thing, its signature passes a buffer without a length; for another,
254 XXX it isn't useful outside this file).
255*/
256void
257PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
258{
259 format_float(buf, 100, v, precision);
260}
261
Neil Schemenauer32117e52001-01-04 01:44:34 +0000262/* Macro and helper that convert PyObject obj to a C double and store
263 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000264 slot function. If conversion to double raises an exception, obj is
265 set to NULL, and the function invoking this macro returns NULL. If
266 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
267 stored in obj, and returned from the function invoking this macro.
268*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000269#define CONVERT_TO_DOUBLE(obj, dbl) \
270 if (PyFloat_Check(obj)) \
271 dbl = PyFloat_AS_DOUBLE(obj); \
272 else if (convert_to_double(&(obj), &(dbl)) < 0) \
273 return obj;
274
275static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000276convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000277{
278 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000279
Neil Schemenauer32117e52001-01-04 01:44:34 +0000280 if (PyInt_Check(obj)) {
281 *dbl = (double)PyInt_AS_LONG(obj);
282 }
283 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000284 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000285 if (*dbl == -1.0 && PyErr_Occurred()) {
286 *v = NULL;
287 return -1;
288 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000289 }
290 else {
291 Py_INCREF(Py_NotImplemented);
292 *v = Py_NotImplemented;
293 return -1;
294 }
295 return 0;
296}
297
Guido van Rossum57072eb1999-12-23 19:00:28 +0000298/* Precisions used by repr() and str(), respectively.
299
300 The repr() precision (17 significant decimal digits) is the minimal number
301 that is guaranteed to have enough precision so that if the number is read
302 back in the exact same binary value is recreated. This is true for IEEE
303 floating point by design, and also happens to work for all other modern
304 hardware.
305
306 The str() precision is chosen so that in most cases, the rounding noise
307 created by various operations is suppressed, while giving plenty of
308 precision for practical use.
309
310*/
311
312#define PREC_REPR 17
313#define PREC_STR 12
314
Tim Peters97019e42001-11-28 22:43:45 +0000315/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
316 XXX they pass a char buffer without passing a length.
317*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000318void
Fred Drakefd99de62000-07-09 05:02:18 +0000319PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000320{
Tim Peters97019e42001-11-28 22:43:45 +0000321 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000322}
323
Tim Peters72f98e92001-05-08 15:19:57 +0000324void
325PyFloat_AsReprString(char *buf, PyFloatObject *v)
326{
Tim Peters97019e42001-11-28 22:43:45 +0000327 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000328}
329
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000330/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000331static int
Fred Drakefd99de62000-07-09 05:02:18 +0000332float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333{
334 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000335 format_float(buf, sizeof(buf), v,
336 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000337 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000339 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000340 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341}
342
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000344float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
346 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000347 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000348 return PyString_FromString(buf);
349}
350
351static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000352float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000353{
354 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000355 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000356 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357}
358
Tim Peters307fa782004-09-23 08:06:40 +0000359/* Comparison is pretty much a nightmare. When comparing float to float,
360 * we do it as straightforwardly (and long-windedly) as conceivable, so
361 * that, e.g., Python x == y delivers the same result as the platform
362 * C x == y when x and/or y is a NaN.
363 * When mixing float with an integer type, there's no good *uniform* approach.
364 * Converting the double to an integer obviously doesn't work, since we
365 * may lose info from fractional bits. Converting the integer to a double
366 * also has two failure modes: (1) a long int may trigger overflow (too
367 * large to fit in the dynamic range of a C double); (2) even a C long may have
368 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
369 * 63 bits of precision, but a C double probably has only 53), and then
370 * we can falsely claim equality when low-order integer bits are lost by
371 * coercion to double. So this part is painful too.
372 */
373
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000374static PyObject*
375float_richcompare(PyObject *v, PyObject *w, int op)
376{
377 double i, j;
378 int r = 0;
379
Tim Peters307fa782004-09-23 08:06:40 +0000380 assert(PyFloat_Check(v));
381 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000382
Tim Peters307fa782004-09-23 08:06:40 +0000383 /* Switch on the type of w. Set i and j to doubles to be compared,
384 * and op to the richcomp to use.
385 */
386 if (PyFloat_Check(w))
387 j = PyFloat_AS_DOUBLE(w);
388
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000389 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000390 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000391 /* If i is an infinity, its magnitude exceeds any
392 * finite integer, so it doesn't matter which int we
393 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000394 */
395 j = 0.0;
396 else
397 goto Unimplemented;
398 }
399
400 else if (PyInt_Check(w)) {
401 long jj = PyInt_AS_LONG(w);
402 /* In the worst realistic case I can imagine, C double is a
403 * Cray single with 48 bits of precision, and long has 64
404 * bits.
405 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000406#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000407 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
408 if (abs >> 48) {
409 /* Needs more than 48 bits. Make it take the
410 * PyLong path.
411 */
412 PyObject *result;
413 PyObject *ww = PyLong_FromLong(jj);
414
415 if (ww == NULL)
416 return NULL;
417 result = float_richcompare(v, ww, op);
418 Py_DECREF(ww);
419 return result;
420 }
421#endif
422 j = (double)jj;
423 assert((long)j == jj);
424 }
425
426 else if (PyLong_Check(w)) {
427 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
428 int wsign = _PyLong_Sign(w);
429 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000430 int exponent;
431
432 if (vsign != wsign) {
433 /* Magnitudes are irrelevant -- the signs alone
434 * determine the outcome.
435 */
436 i = (double)vsign;
437 j = (double)wsign;
438 goto Compare;
439 }
440 /* The signs are the same. */
441 /* Convert w to a double if it fits. In particular, 0 fits. */
442 nbits = _PyLong_NumBits(w);
443 if (nbits == (size_t)-1 && PyErr_Occurred()) {
444 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000445 * to hold the # of bits. Replace with little doubles
446 * that give the same outcome -- w is so large that
447 * its magnitude must exceed the magnitude of any
448 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000449 */
450 PyErr_Clear();
451 i = (double)vsign;
452 assert(wsign != 0);
453 j = wsign * 2.0;
454 goto Compare;
455 }
456 if (nbits <= 48) {
457 j = PyLong_AsDouble(w);
458 /* It's impossible that <= 48 bits overflowed. */
459 assert(j != -1.0 || ! PyErr_Occurred());
460 goto Compare;
461 }
462 assert(wsign != 0); /* else nbits was 0 */
463 assert(vsign != 0); /* if vsign were 0, then since wsign is
464 * not 0, we would have taken the
465 * vsign != wsign branch at the start */
466 /* We want to work with non-negative numbers. */
467 if (vsign < 0) {
468 /* "Multiply both sides" by -1; this also swaps the
469 * comparator.
470 */
471 i = -i;
472 op = _Py_SwappedOp[op];
473 }
474 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000475 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000476 /* exponent is the # of bits in v before the radix point;
477 * we know that nbits (the # of bits in w) > 48 at this point
478 */
479 if (exponent < 0 || (size_t)exponent < nbits) {
480 i = 1.0;
481 j = 2.0;
482 goto Compare;
483 }
484 if ((size_t)exponent > nbits) {
485 i = 2.0;
486 j = 1.0;
487 goto Compare;
488 }
489 /* v and w have the same number of bits before the radix
490 * point. Construct two longs that have the same comparison
491 * outcome.
492 */
493 {
494 double fracpart;
495 double intpart;
496 PyObject *result = NULL;
497 PyObject *one = NULL;
498 PyObject *vv = NULL;
499 PyObject *ww = w;
500
501 if (wsign < 0) {
502 ww = PyNumber_Negative(w);
503 if (ww == NULL)
504 goto Error;
505 }
506 else
507 Py_INCREF(ww);
508
509 fracpart = modf(i, &intpart);
510 vv = PyLong_FromDouble(intpart);
511 if (vv == NULL)
512 goto Error;
513
514 if (fracpart != 0.0) {
515 /* Shift left, and or a 1 bit into vv
516 * to represent the lost fraction.
517 */
518 PyObject *temp;
519
520 one = PyInt_FromLong(1);
521 if (one == NULL)
522 goto Error;
523
524 temp = PyNumber_Lshift(ww, one);
525 if (temp == NULL)
526 goto Error;
527 Py_DECREF(ww);
528 ww = temp;
529
530 temp = PyNumber_Lshift(vv, one);
531 if (temp == NULL)
532 goto Error;
533 Py_DECREF(vv);
534 vv = temp;
535
536 temp = PyNumber_Or(vv, one);
537 if (temp == NULL)
538 goto Error;
539 Py_DECREF(vv);
540 vv = temp;
541 }
542
543 r = PyObject_RichCompareBool(vv, ww, op);
544 if (r < 0)
545 goto Error;
546 result = PyBool_FromLong(r);
547 Error:
548 Py_XDECREF(vv);
549 Py_XDECREF(ww);
550 Py_XDECREF(one);
551 return result;
552 }
553 } /* else if (PyLong_Check(w)) */
554
555 else /* w isn't float, int, or long */
556 goto Unimplemented;
557
558 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000559 PyFPE_START_PROTECT("richcompare", return NULL)
560 switch (op) {
561 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000562 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000563 break;
564 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000565 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000566 break;
567 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000568 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000569 break;
570 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000571 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000572 break;
573 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000574 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000575 break;
576 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000577 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000578 break;
579 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000580 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000581 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000582
583 Unimplemented:
584 Py_INCREF(Py_NotImplemented);
585 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000586}
587
Guido van Rossum9bfef441993-03-29 10:43:31 +0000588static long
Fred Drakefd99de62000-07-09 05:02:18 +0000589float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000590{
Tim Peters39dce292000-08-15 03:34:48 +0000591 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000592}
593
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000594static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000595float_add(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);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000600 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000601 a = a + b;
602 PyFPE_END_PROTECT(a)
603 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604}
605
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000607float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000608{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000609 double a,b;
610 CONVERT_TO_DOUBLE(v, a);
611 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000612 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000613 a = a - b;
614 PyFPE_END_PROTECT(a)
615 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616}
617
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000619float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000620{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000621 double a,b;
622 CONVERT_TO_DOUBLE(v, a);
623 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000624 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000625 a = a * b;
626 PyFPE_END_PROTECT(a)
627 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000628}
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000631float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000633 double a,b;
634 CONVERT_TO_DOUBLE(v, a);
635 CONVERT_TO_DOUBLE(w, b);
636 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638 return NULL;
639 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000640 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000641 a = a / b;
642 PyFPE_END_PROTECT(a)
643 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000644}
645
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000647float_classic_div(PyObject *v, PyObject *w)
648{
649 double a,b;
650 CONVERT_TO_DOUBLE(v, a);
651 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000652 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000653 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
654 return NULL;
655 if (b == 0.0) {
656 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
657 return NULL;
658 }
659 PyFPE_START_PROTECT("divide", return 0)
660 a = a / b;
661 PyFPE_END_PROTECT(a)
662 return PyFloat_FromDouble(a);
663}
664
665static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000666float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000668 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000669 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000670 CONVERT_TO_DOUBLE(v, vx);
671 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674 return NULL;
675 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000676 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000677 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000678 /* note: checking mod*wx < 0 is incorrect -- underflows to
679 0 if wx < sqrt(smallest nonzero double) */
680 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000681 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000682 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000683 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000684 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685}
686
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000688float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000689{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000690 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000691 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000692 CONVERT_TO_DOUBLE(v, vx);
693 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000694 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000696 return NULL;
697 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000698 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000699 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000700 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000701 exact multiple of wx. But this is fp arithmetic, and fp
702 vx - mod is an approximation; the result is that div may
703 not be an exact integral value after the division, although
704 it will always be very close to one.
705 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000706 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000707 if (mod) {
708 /* ensure the remainder has the same sign as the denominator */
709 if ((wx < 0) != (mod < 0)) {
710 mod += wx;
711 div -= 1.0;
712 }
713 }
714 else {
715 /* the remainder is zero, and in the presence of signed zeroes
716 fmod returns different results across platforms; ensure
717 it has the same sign as the denominator; we'd like to do
718 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000719 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000720 if (wx < 0.0)
721 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000722 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000723 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000724 if (div) {
725 floordiv = floor(div);
726 if (div - floordiv > 0.5)
727 floordiv += 1.0;
728 }
729 else {
730 /* div is zero - get the same sign as the true quotient */
731 div *= div; /* hide "div = +0" from optimizers */
732 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
733 }
734 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000735 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000736}
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000739float_floor_div(PyObject *v, PyObject *w)
740{
741 PyObject *t, *r;
742
743 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000744 if (t == NULL || t == Py_NotImplemented)
745 return t;
746 assert(PyTuple_CheckExact(t));
747 r = PyTuple_GET_ITEM(t, 0);
748 Py_INCREF(r);
749 Py_DECREF(t);
750 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000751}
752
753static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000754float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755{
756 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000757
758 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000759 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000760 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000761 return NULL;
762 }
763
Neil Schemenauer32117e52001-01-04 01:44:34 +0000764 CONVERT_TO_DOUBLE(v, iv);
765 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000766
767 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000768 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000769 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000770 }
Tim Peters96685bf2001-08-23 22:31:37 +0000771 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000772 if (iw < 0.0) {
773 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000774 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000775 return NULL;
776 }
777 return PyFloat_FromDouble(0.0);
778 }
Tim Peterse87568d2003-05-24 20:18:24 +0000779 if (iv < 0.0) {
780 /* Whether this is an error is a mess, and bumps into libm
781 * bugs so we have to figure it out ourselves.
782 */
783 if (iw != floor(iw)) {
784 PyErr_SetString(PyExc_ValueError, "negative number "
785 "cannot be raised to a fractional power");
786 return NULL;
787 }
788 /* iw is an exact integer, albeit perhaps a very large one.
789 * -1 raised to an exact integer should never be exceptional.
790 * Alas, some libms (chiefly glibc as of early 2003) return
791 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
792 * happen to be representable in a *C* integer. That's a
793 * bug; we let that slide in math.pow() (which currently
794 * reflects all platform accidents), but not for Python's **.
795 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000796 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000797 /* Return 1 if iw is even, -1 if iw is odd; there's
798 * no guarantee that any C integral type is big
799 * enough to hold iw, so we have to check this
800 * indirectly.
801 */
802 ix = floor(iw * 0.5) * 2.0;
803 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
804 }
805 /* Else iv != -1.0, and overflow or underflow are possible.
806 * Unless we're to write pow() ourselves, we have to trust
807 * the platform to do this correctly.
808 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000809 }
Tim Peters96685bf2001-08-23 22:31:37 +0000810 errno = 0;
811 PyFPE_START_PROTECT("pow", return NULL)
812 ix = pow(iv, iw);
813 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000814 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000815 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000816 /* We don't expect any errno value other than ERANGE, but
817 * the range of libm bugs appears unbounded.
818 */
Alex Martelli348dc882006-08-23 22:17:59 +0000819 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
820 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000822 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000823 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824}
825
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000826static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000827float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000829 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830}
831
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000833float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000834{
Tim Peters0280cf72001-09-11 21:53:35 +0000835 if (PyFloat_CheckExact(v)) {
836 Py_INCREF(v);
837 return (PyObject *)v;
838 }
839 else
840 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000841}
842
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000844float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000845{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000846 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000847}
848
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000849static int
Fred Drakefd99de62000-07-09 05:02:18 +0000850float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000851{
852 return v->ob_fval != 0.0;
853}
854
Guido van Rossum234f9421993-06-17 12:35:49 +0000855static int
Fred Drakefd99de62000-07-09 05:02:18 +0000856float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000857{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000858 if (PyInt_Check(*pw)) {
859 long x = PyInt_AsLong(*pw);
860 *pw = PyFloat_FromDouble((double)x);
861 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000862 return 0;
863 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000864 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000865 double x = PyLong_AsDouble(*pw);
866 if (x == -1.0 && PyErr_Occurred())
867 return -1;
868 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000869 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000870 return 0;
871 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000872 else if (PyFloat_Check(*pw)) {
873 Py_INCREF(*pv);
874 Py_INCREF(*pw);
875 return 0;
876 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000877 return 1; /* Can't do it */
878}
879
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000880static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000881float_long(PyObject *v)
882{
883 double x = PyFloat_AsDouble(v);
884 return PyLong_FromDouble(x);
885}
886
887static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000888float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000889{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000890 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000891 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000892
893 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000894 /* Try to get out cheap if this fits in a Python int. The attempt
895 * to cast to long must be protected, as C doesn't define what
896 * happens if the double is too big to fit in a long. Some rare
897 * systems raise an exception then (RISCOS was mentioned as one,
898 * and someone using a non-default option on Sun also bumped into
899 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
900 * still be vulnerable: if a long has more bits of precision than
901 * a double, casting MIN/MAX to double may yield an approximation,
902 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
903 * yield true from the C expression wholepart<=LONG_MAX, despite
904 * that wholepart is actually greater than LONG_MAX.
905 */
906 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
907 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000908 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000909 }
910 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000911}
912
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000913static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000914float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000915{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000916 if (PyFloat_CheckExact(v))
917 Py_INCREF(v);
918 else
919 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000920 return v;
921}
922
923
Jeremy Hylton938ace62002-07-17 16:30:39 +0000924static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000925float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
926
Tim Peters6d6c1a32001-08-02 04:15:00 +0000927static PyObject *
928float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
929{
930 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000931 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932
Guido van Rossumbef14172001-08-29 15:47:46 +0000933 if (type != &PyFloat_Type)
934 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
936 return NULL;
937 if (PyString_Check(x))
938 return PyFloat_FromString(x, NULL);
939 return PyNumber_Float(x);
940}
941
Guido van Rossumbef14172001-08-29 15:47:46 +0000942/* Wimpy, slow approach to tp_new calls for subtypes of float:
943 first create a regular float from whatever arguments we got,
944 then allocate a subtype instance and initialize its ob_fval
945 from the regular float. The regular float is then thrown away.
946*/
947static PyObject *
948float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
949{
Anthony Baxter377be112006-04-11 06:54:30 +0000950 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000951
952 assert(PyType_IsSubtype(type, &PyFloat_Type));
953 tmp = float_new(&PyFloat_Type, args, kwds);
954 if (tmp == NULL)
955 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000956 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +0000957 newobj = type->tp_alloc(type, 0);
958 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000959 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000960 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000961 }
Anthony Baxter377be112006-04-11 06:54:30 +0000962 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000963 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +0000964 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000965}
966
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000967static PyObject *
968float_getnewargs(PyFloatObject *v)
969{
970 return Py_BuildValue("(d)", v->ob_fval);
971}
972
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000973/* this is for the benefit of the pack/unpack routines below */
974
975typedef enum {
976 unknown_format, ieee_big_endian_format, ieee_little_endian_format
977} float_format_type;
978
979static float_format_type double_format, float_format;
980static float_format_type detected_double_format, detected_float_format;
981
982static PyObject *
983float_getformat(PyTypeObject *v, PyObject* arg)
984{
985 char* s;
986 float_format_type r;
987
988 if (!PyString_Check(arg)) {
989 PyErr_Format(PyExc_TypeError,
990 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis68192102007-07-21 06:55:02 +0000991 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000992 return NULL;
993 }
994 s = PyString_AS_STRING(arg);
995 if (strcmp(s, "double") == 0) {
996 r = double_format;
997 }
998 else if (strcmp(s, "float") == 0) {
999 r = float_format;
1000 }
1001 else {
1002 PyErr_SetString(PyExc_ValueError,
1003 "__getformat__() argument 1 must be "
1004 "'double' or 'float'");
1005 return NULL;
1006 }
1007
1008 switch (r) {
1009 case unknown_format:
1010 return PyString_FromString("unknown");
1011 case ieee_little_endian_format:
1012 return PyString_FromString("IEEE, little-endian");
1013 case ieee_big_endian_format:
1014 return PyString_FromString("IEEE, big-endian");
1015 default:
1016 Py_FatalError("insane float_format or double_format");
1017 return NULL;
1018 }
1019}
1020
1021PyDoc_STRVAR(float_getformat_doc,
1022"float.__getformat__(typestr) -> string\n"
1023"\n"
1024"You probably don't want to use this function. It exists mainly to be\n"
1025"used in Python's test suite.\n"
1026"\n"
1027"typestr must be 'double' or 'float'. This function returns whichever of\n"
1028"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1029"format of floating point numbers used by the C type named by typestr.");
1030
1031static PyObject *
1032float_setformat(PyTypeObject *v, PyObject* args)
1033{
1034 char* typestr;
1035 char* format;
1036 float_format_type f;
1037 float_format_type detected;
1038 float_format_type *p;
1039
1040 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1041 return NULL;
1042
1043 if (strcmp(typestr, "double") == 0) {
1044 p = &double_format;
1045 detected = detected_double_format;
1046 }
1047 else if (strcmp(typestr, "float") == 0) {
1048 p = &float_format;
1049 detected = detected_float_format;
1050 }
1051 else {
1052 PyErr_SetString(PyExc_ValueError,
1053 "__setformat__() argument 1 must "
1054 "be 'double' or 'float'");
1055 return NULL;
1056 }
1057
1058 if (strcmp(format, "unknown") == 0) {
1059 f = unknown_format;
1060 }
1061 else if (strcmp(format, "IEEE, little-endian") == 0) {
1062 f = ieee_little_endian_format;
1063 }
1064 else if (strcmp(format, "IEEE, big-endian") == 0) {
1065 f = ieee_big_endian_format;
1066 }
1067 else {
1068 PyErr_SetString(PyExc_ValueError,
1069 "__setformat__() argument 2 must be "
1070 "'unknown', 'IEEE, little-endian' or "
1071 "'IEEE, big-endian'");
1072 return NULL;
1073
1074 }
1075
1076 if (f != unknown_format && f != detected) {
1077 PyErr_Format(PyExc_ValueError,
1078 "can only set %s format to 'unknown' or the "
1079 "detected platform value", typestr);
1080 return NULL;
1081 }
1082
1083 *p = f;
1084 Py_RETURN_NONE;
1085}
1086
1087PyDoc_STRVAR(float_setformat_doc,
1088"float.__setformat__(typestr, fmt) -> None\n"
1089"\n"
1090"You probably don't want to use this function. It exists mainly to be\n"
1091"used in Python's test suite.\n"
1092"\n"
1093"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1094"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1095"one of the latter two if it appears to match the underlying C reality.\n"
1096"\n"
1097"Overrides the automatic determination of C-level floating point type.\n"
1098"This affects how floats are converted to and from binary strings.");
1099
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001100static PyMethodDef float_methods[] = {
1101 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001102 {"__getformat__", (PyCFunction)float_getformat,
1103 METH_O|METH_CLASS, float_getformat_doc},
1104 {"__setformat__", (PyCFunction)float_setformat,
1105 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001106 {NULL, NULL} /* sentinel */
1107};
1108
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001109PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110"float(x) -> floating point number\n\
1111\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001112Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113
1114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001115static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001116 float_add, /*nb_add*/
1117 float_sub, /*nb_subtract*/
1118 float_mul, /*nb_multiply*/
1119 float_classic_div, /*nb_divide*/
1120 float_rem, /*nb_remainder*/
1121 float_divmod, /*nb_divmod*/
1122 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001123 (unaryfunc)float_neg, /*nb_negative*/
1124 (unaryfunc)float_pos, /*nb_positive*/
1125 (unaryfunc)float_abs, /*nb_absolute*/
1126 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001127 0, /*nb_invert*/
1128 0, /*nb_lshift*/
1129 0, /*nb_rshift*/
1130 0, /*nb_and*/
1131 0, /*nb_xor*/
1132 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001133 float_coerce, /*nb_coerce*/
1134 float_int, /*nb_int*/
1135 float_long, /*nb_long*/
1136 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001137 0, /* nb_oct */
1138 0, /* nb_hex */
1139 0, /* nb_inplace_add */
1140 0, /* nb_inplace_subtract */
1141 0, /* nb_inplace_multiply */
1142 0, /* nb_inplace_divide */
1143 0, /* nb_inplace_remainder */
1144 0, /* nb_inplace_power */
1145 0, /* nb_inplace_lshift */
1146 0, /* nb_inplace_rshift */
1147 0, /* nb_inplace_and */
1148 0, /* nb_inplace_xor */
1149 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001150 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001151 float_div, /* nb_true_divide */
1152 0, /* nb_inplace_floor_divide */
1153 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001154};
1155
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001156PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001157 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001158 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001159 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001160 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 (destructor)float_dealloc, /* tp_dealloc */
1162 (printfunc)float_print, /* tp_print */
1163 0, /* tp_getattr */
1164 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001165 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 (reprfunc)float_repr, /* tp_repr */
1167 &float_as_number, /* tp_as_number */
1168 0, /* tp_as_sequence */
1169 0, /* tp_as_mapping */
1170 (hashfunc)float_hash, /* tp_hash */
1171 0, /* tp_call */
1172 (reprfunc)float_str, /* tp_str */
1173 PyObject_GenericGetAttr, /* tp_getattro */
1174 0, /* tp_setattro */
1175 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001176 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1177 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 float_doc, /* tp_doc */
1179 0, /* tp_traverse */
1180 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001181 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 0, /* tp_weaklistoffset */
1183 0, /* tp_iter */
1184 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001185 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001186 0, /* tp_members */
1187 0, /* tp_getset */
1188 0, /* tp_base */
1189 0, /* tp_dict */
1190 0, /* tp_descr_get */
1191 0, /* tp_descr_set */
1192 0, /* tp_dictoffset */
1193 0, /* tp_init */
1194 0, /* tp_alloc */
1195 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001196};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001197
1198void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001199_PyFloat_Init(void)
1200{
1201 /* We attempt to determine if this machine is using IEEE
1202 floating point formats by peering at the bits of some
1203 carefully chosen values. If it looks like we are on an
1204 IEEE platform, the float packing/unpacking routines can
1205 just copy bits, if not they resort to arithmetic & shifts
1206 and masks. The shifts & masks approach works on all finite
1207 values, but what happens to infinities, NaNs and signed
1208 zeroes on packing is an accident, and attempting to unpack
1209 a NaN or an infinity will raise an exception.
1210
1211 Note that if we're on some whacked-out platform which uses
1212 IEEE formats but isn't strictly little-endian or big-
1213 endian, we will fall back to the portable shifts & masks
1214 method. */
1215
1216#if SIZEOF_DOUBLE == 8
1217 {
1218 double x = 9006104071832581.0;
1219 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1220 detected_double_format = ieee_big_endian_format;
1221 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1222 detected_double_format = ieee_little_endian_format;
1223 else
1224 detected_double_format = unknown_format;
1225 }
1226#else
1227 detected_double_format = unknown_format;
1228#endif
1229
1230#if SIZEOF_FLOAT == 4
1231 {
1232 float y = 16711938.0;
1233 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1234 detected_float_format = ieee_big_endian_format;
1235 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1236 detected_float_format = ieee_little_endian_format;
1237 else
1238 detected_float_format = unknown_format;
1239 }
1240#else
1241 detected_float_format = unknown_format;
1242#endif
1243
1244 double_format = detected_double_format;
1245 float_format = detected_float_format;
1246}
1247
1248void
Fred Drakefd99de62000-07-09 05:02:18 +00001249PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001250{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001251 PyFloatObject *p;
1252 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001253 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001254 int bc, bf; /* block count, number of freed blocks */
1255 int frem, fsum; /* remaining unfreed floats per block, total */
1256
1257 bc = 0;
1258 bf = 0;
1259 fsum = 0;
1260 list = block_list;
1261 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001262 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001263 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001264 bc++;
1265 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001266 for (i = 0, p = &list->objects[0];
1267 i < N_FLOATOBJECTS;
1268 i++, p++) {
Martin v. Löwis68192102007-07-21 06:55:02 +00001269 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001270 frem++;
1271 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001272 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001273 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001274 list->next = block_list;
1275 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001276 for (i = 0, p = &list->objects[0];
1277 i < N_FLOATOBJECTS;
1278 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001279 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis68192102007-07-21 06:55:02 +00001280 Py_Refcnt(p) == 0) {
1281 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001282 free_list;
1283 free_list = p;
1284 }
1285 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001286 }
1287 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001288 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001289 bf++;
1290 }
1291 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001292 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001293 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001294 if (!Py_VerboseFlag)
1295 return;
1296 fprintf(stderr, "# cleanup floats");
1297 if (!fsum) {
1298 fprintf(stderr, "\n");
1299 }
1300 else {
1301 fprintf(stderr,
1302 ": %d unfreed float%s in %d out of %d block%s\n",
1303 fsum, fsum == 1 ? "" : "s",
1304 bc - bf, bc, bc == 1 ? "" : "s");
1305 }
1306 if (Py_VerboseFlag > 1) {
1307 list = block_list;
1308 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001309 for (i = 0, p = &list->objects[0];
1310 i < N_FLOATOBJECTS;
1311 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001312 if (PyFloat_CheckExact(p) &&
Martin v. Löwis68192102007-07-21 06:55:02 +00001313 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001314 char buf[100];
1315 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001316 /* XXX(twouters) cast refcount to
1317 long until %zd is universally
1318 available
1319 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001320 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001321 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis68192102007-07-21 06:55:02 +00001322 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001323 }
1324 }
1325 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001326 }
1327 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001328}
Tim Peters9905b942003-03-20 20:53:32 +00001329
1330/*----------------------------------------------------------------------------
1331 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1332 *
1333 * TODO: On platforms that use the standard IEEE-754 single and double
1334 * formats natively, these routines could simply copy the bytes.
1335 */
1336int
1337_PyFloat_Pack4(double x, unsigned char *p, int le)
1338{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001339 if (float_format == unknown_format) {
1340 unsigned char sign;
1341 int e;
1342 double f;
1343 unsigned int fbits;
1344 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001345
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001346 if (le) {
1347 p += 3;
1348 incr = -1;
1349 }
Tim Peters9905b942003-03-20 20:53:32 +00001350
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001351 if (x < 0) {
1352 sign = 1;
1353 x = -x;
1354 }
1355 else
1356 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001357
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001358 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001359
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001360 /* Normalize f to be in the range [1.0, 2.0) */
1361 if (0.5 <= f && f < 1.0) {
1362 f *= 2.0;
1363 e--;
1364 }
1365 else if (f == 0.0)
1366 e = 0;
1367 else {
1368 PyErr_SetString(PyExc_SystemError,
1369 "frexp() result out of range");
1370 return -1;
1371 }
1372
1373 if (e >= 128)
1374 goto Overflow;
1375 else if (e < -126) {
1376 /* Gradual underflow */
1377 f = ldexp(f, 126 + e);
1378 e = 0;
1379 }
1380 else if (!(e == 0 && f == 0.0)) {
1381 e += 127;
1382 f -= 1.0; /* Get rid of leading 1 */
1383 }
1384
1385 f *= 8388608.0; /* 2**23 */
1386 fbits = (unsigned int)(f + 0.5); /* Round */
1387 assert(fbits <= 8388608);
1388 if (fbits >> 23) {
1389 /* The carry propagated out of a string of 23 1 bits. */
1390 fbits = 0;
1391 ++e;
1392 if (e >= 255)
1393 goto Overflow;
1394 }
1395
1396 /* First byte */
1397 *p = (sign << 7) | (e >> 1);
1398 p += incr;
1399
1400 /* Second byte */
1401 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1402 p += incr;
1403
1404 /* Third byte */
1405 *p = (fbits >> 8) & 0xFF;
1406 p += incr;
1407
1408 /* Fourth byte */
1409 *p = fbits & 0xFF;
1410
1411 /* Done */
1412 return 0;
1413
1414 Overflow:
1415 PyErr_SetString(PyExc_OverflowError,
1416 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001417 return -1;
1418 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001419 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001420 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001421 const char *s = (char*)&y;
1422 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001423
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001424 if ((float_format == ieee_little_endian_format && !le)
1425 || (float_format == ieee_big_endian_format && le)) {
1426 p += 3;
1427 incr = -1;
1428 }
1429
1430 for (i = 0; i < 4; i++) {
1431 *p = *s++;
1432 p += incr;
1433 }
1434 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001435 }
Tim Peters9905b942003-03-20 20:53:32 +00001436}
1437
1438int
1439_PyFloat_Pack8(double x, unsigned char *p, int le)
1440{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001441 if (double_format == unknown_format) {
1442 unsigned char sign;
1443 int e;
1444 double f;
1445 unsigned int fhi, flo;
1446 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001447
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001448 if (le) {
1449 p += 7;
1450 incr = -1;
1451 }
Tim Peters9905b942003-03-20 20:53:32 +00001452
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001453 if (x < 0) {
1454 sign = 1;
1455 x = -x;
1456 }
1457 else
1458 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001459
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001460 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001461
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001462 /* Normalize f to be in the range [1.0, 2.0) */
1463 if (0.5 <= f && f < 1.0) {
1464 f *= 2.0;
1465 e--;
1466 }
1467 else if (f == 0.0)
1468 e = 0;
1469 else {
1470 PyErr_SetString(PyExc_SystemError,
1471 "frexp() result out of range");
1472 return -1;
1473 }
1474
1475 if (e >= 1024)
1476 goto Overflow;
1477 else if (e < -1022) {
1478 /* Gradual underflow */
1479 f = ldexp(f, 1022 + e);
1480 e = 0;
1481 }
1482 else if (!(e == 0 && f == 0.0)) {
1483 e += 1023;
1484 f -= 1.0; /* Get rid of leading 1 */
1485 }
1486
1487 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1488 f *= 268435456.0; /* 2**28 */
1489 fhi = (unsigned int)f; /* Truncate */
1490 assert(fhi < 268435456);
1491
1492 f -= (double)fhi;
1493 f *= 16777216.0; /* 2**24 */
1494 flo = (unsigned int)(f + 0.5); /* Round */
1495 assert(flo <= 16777216);
1496 if (flo >> 24) {
1497 /* The carry propagated out of a string of 24 1 bits. */
1498 flo = 0;
1499 ++fhi;
1500 if (fhi >> 28) {
1501 /* And it also progagated out of the next 28 bits. */
1502 fhi = 0;
1503 ++e;
1504 if (e >= 2047)
1505 goto Overflow;
1506 }
1507 }
1508
1509 /* First byte */
1510 *p = (sign << 7) | (e >> 4);
1511 p += incr;
1512
1513 /* Second byte */
1514 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1515 p += incr;
1516
1517 /* Third byte */
1518 *p = (fhi >> 16) & 0xFF;
1519 p += incr;
1520
1521 /* Fourth byte */
1522 *p = (fhi >> 8) & 0xFF;
1523 p += incr;
1524
1525 /* Fifth byte */
1526 *p = fhi & 0xFF;
1527 p += incr;
1528
1529 /* Sixth byte */
1530 *p = (flo >> 16) & 0xFF;
1531 p += incr;
1532
1533 /* Seventh byte */
1534 *p = (flo >> 8) & 0xFF;
1535 p += incr;
1536
1537 /* Eighth byte */
1538 *p = flo & 0xFF;
1539 p += incr;
1540
1541 /* Done */
1542 return 0;
1543
1544 Overflow:
1545 PyErr_SetString(PyExc_OverflowError,
1546 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001547 return -1;
1548 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001549 else {
1550 const char *s = (char*)&x;
1551 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001552
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001553 if ((double_format == ieee_little_endian_format && !le)
1554 || (double_format == ieee_big_endian_format && le)) {
1555 p += 7;
1556 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001557 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001558
1559 for (i = 0; i < 8; i++) {
1560 *p = *s++;
1561 p += incr;
1562 }
1563 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001564 }
Tim Peters9905b942003-03-20 20:53:32 +00001565}
1566
1567double
1568_PyFloat_Unpack4(const unsigned char *p, int le)
1569{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001570 if (float_format == unknown_format) {
1571 unsigned char sign;
1572 int e;
1573 unsigned int f;
1574 double x;
1575 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001576
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001577 if (le) {
1578 p += 3;
1579 incr = -1;
1580 }
1581
1582 /* First byte */
1583 sign = (*p >> 7) & 1;
1584 e = (*p & 0x7F) << 1;
1585 p += incr;
1586
1587 /* Second byte */
1588 e |= (*p >> 7) & 1;
1589 f = (*p & 0x7F) << 16;
1590 p += incr;
1591
1592 if (e == 255) {
1593 PyErr_SetString(
1594 PyExc_ValueError,
1595 "can't unpack IEEE 754 special value "
1596 "on non-IEEE platform");
1597 return -1;
1598 }
1599
1600 /* Third byte */
1601 f |= *p << 8;
1602 p += incr;
1603
1604 /* Fourth byte */
1605 f |= *p;
1606
1607 x = (double)f / 8388608.0;
1608
1609 /* XXX This sadly ignores Inf/NaN issues */
1610 if (e == 0)
1611 e = -126;
1612 else {
1613 x += 1.0;
1614 e -= 127;
1615 }
1616 x = ldexp(x, e);
1617
1618 if (sign)
1619 x = -x;
1620
1621 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001622 }
Tim Peters9905b942003-03-20 20:53:32 +00001623 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001624 float x;
1625
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001626 if ((float_format == ieee_little_endian_format && !le)
1627 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001628 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001629 char *d = &buf[3];
1630 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001631
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001632 for (i = 0; i < 4; i++) {
1633 *d-- = *p++;
1634 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001635 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001636 }
1637 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001638 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001639 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001640
1641 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001642 }
Tim Peters9905b942003-03-20 20:53:32 +00001643}
1644
1645double
1646_PyFloat_Unpack8(const unsigned char *p, int le)
1647{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001648 if (double_format == unknown_format) {
1649 unsigned char sign;
1650 int e;
1651 unsigned int fhi, flo;
1652 double x;
1653 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001654
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655 if (le) {
1656 p += 7;
1657 incr = -1;
1658 }
1659
1660 /* First byte */
1661 sign = (*p >> 7) & 1;
1662 e = (*p & 0x7F) << 4;
1663
1664 p += incr;
1665
1666 /* Second byte */
1667 e |= (*p >> 4) & 0xF;
1668 fhi = (*p & 0xF) << 24;
1669 p += incr;
1670
1671 if (e == 2047) {
1672 PyErr_SetString(
1673 PyExc_ValueError,
1674 "can't unpack IEEE 754 special value "
1675 "on non-IEEE platform");
1676 return -1.0;
1677 }
1678
1679 /* Third byte */
1680 fhi |= *p << 16;
1681 p += incr;
1682
1683 /* Fourth byte */
1684 fhi |= *p << 8;
1685 p += incr;
1686
1687 /* Fifth byte */
1688 fhi |= *p;
1689 p += incr;
1690
1691 /* Sixth byte */
1692 flo = *p << 16;
1693 p += incr;
1694
1695 /* Seventh byte */
1696 flo |= *p << 8;
1697 p += incr;
1698
1699 /* Eighth byte */
1700 flo |= *p;
1701
1702 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1703 x /= 268435456.0; /* 2**28 */
1704
1705 if (e == 0)
1706 e = -1022;
1707 else {
1708 x += 1.0;
1709 e -= 1023;
1710 }
1711 x = ldexp(x, e);
1712
1713 if (sign)
1714 x = -x;
1715
1716 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001717 }
Tim Peters9905b942003-03-20 20:53:32 +00001718 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001719 double x;
1720
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721 if ((double_format == ieee_little_endian_format && !le)
1722 || (double_format == ieee_big_endian_format && le)) {
1723 char buf[8];
1724 char *d = &buf[7];
1725 int i;
1726
1727 for (i = 0; i < 8; i++) {
1728 *d-- = *p++;
1729 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001730 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731 }
1732 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001733 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001734 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001735
1736 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001737 }
Tim Peters9905b942003-03-20 20:53:32 +00001738}