blob: 8708690f077bf2d9030ed70028cc053178d3ab56 [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)
Guido van Rossumf61bbc81999-03-12 00:12:21 +000044 q->ob_type = (struct _typeobject *)(q-1);
45 q->ob_type = 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;
Guido van Rossumf61bbc81999-03-12 00:12:21 +000059 free_list = (PyFloatObject *)op->ob_type;
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)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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)) {
178 op->ob_type = (struct _typeobject *)free_list;
179 free_list = op;
180 }
181 else
182 op->ob_type->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
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000200 if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) {
201 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);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000338 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000342float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
344 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000345 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000346 return PyString_FromString(buf);
347}
348
349static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000350float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000351{
352 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000353 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000354 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355}
356
Tim Peters307fa782004-09-23 08:06:40 +0000357/* Comparison is pretty much a nightmare. When comparing float to float,
358 * we do it as straightforwardly (and long-windedly) as conceivable, so
359 * that, e.g., Python x == y delivers the same result as the platform
360 * C x == y when x and/or y is a NaN.
361 * When mixing float with an integer type, there's no good *uniform* approach.
362 * Converting the double to an integer obviously doesn't work, since we
363 * may lose info from fractional bits. Converting the integer to a double
364 * also has two failure modes: (1) a long int may trigger overflow (too
365 * large to fit in the dynamic range of a C double); (2) even a C long may have
366 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
367 * 63 bits of precision, but a C double probably has only 53), and then
368 * we can falsely claim equality when low-order integer bits are lost by
369 * coercion to double. So this part is painful too.
370 */
371
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000372static PyObject*
373float_richcompare(PyObject *v, PyObject *w, int op)
374{
375 double i, j;
376 int r = 0;
377
Tim Peters307fa782004-09-23 08:06:40 +0000378 assert(PyFloat_Check(v));
379 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000380
Tim Peters307fa782004-09-23 08:06:40 +0000381 /* Switch on the type of w. Set i and j to doubles to be compared,
382 * and op to the richcomp to use.
383 */
384 if (PyFloat_Check(w))
385 j = PyFloat_AS_DOUBLE(w);
386
Tim Peterse1c69b32004-09-23 19:22:41 +0000387 else if (Py_IS_INFINITY(i) || Py_IS_NAN(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000388 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000389 /* If i is an infinity, its magnitude exceeds any
390 * finite integer, so it doesn't matter which int we
391 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000392 */
393 j = 0.0;
394 else
395 goto Unimplemented;
396 }
397
398 else if (PyInt_Check(w)) {
399 long jj = PyInt_AS_LONG(w);
400 /* In the worst realistic case I can imagine, C double is a
401 * Cray single with 48 bits of precision, and long has 64
402 * bits.
403 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000404#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000405 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
406 if (abs >> 48) {
407 /* Needs more than 48 bits. Make it take the
408 * PyLong path.
409 */
410 PyObject *result;
411 PyObject *ww = PyLong_FromLong(jj);
412
413 if (ww == NULL)
414 return NULL;
415 result = float_richcompare(v, ww, op);
416 Py_DECREF(ww);
417 return result;
418 }
419#endif
420 j = (double)jj;
421 assert((long)j == jj);
422 }
423
424 else if (PyLong_Check(w)) {
425 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
426 int wsign = _PyLong_Sign(w);
427 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000428 int exponent;
429
430 if (vsign != wsign) {
431 /* Magnitudes are irrelevant -- the signs alone
432 * determine the outcome.
433 */
434 i = (double)vsign;
435 j = (double)wsign;
436 goto Compare;
437 }
438 /* The signs are the same. */
439 /* Convert w to a double if it fits. In particular, 0 fits. */
440 nbits = _PyLong_NumBits(w);
441 if (nbits == (size_t)-1 && PyErr_Occurred()) {
442 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000443 * to hold the # of bits. Replace with little doubles
444 * that give the same outcome -- w is so large that
445 * its magnitude must exceed the magnitude of any
446 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000447 */
448 PyErr_Clear();
449 i = (double)vsign;
450 assert(wsign != 0);
451 j = wsign * 2.0;
452 goto Compare;
453 }
454 if (nbits <= 48) {
455 j = PyLong_AsDouble(w);
456 /* It's impossible that <= 48 bits overflowed. */
457 assert(j != -1.0 || ! PyErr_Occurred());
458 goto Compare;
459 }
460 assert(wsign != 0); /* else nbits was 0 */
461 assert(vsign != 0); /* if vsign were 0, then since wsign is
462 * not 0, we would have taken the
463 * vsign != wsign branch at the start */
464 /* We want to work with non-negative numbers. */
465 if (vsign < 0) {
466 /* "Multiply both sides" by -1; this also swaps the
467 * comparator.
468 */
469 i = -i;
470 op = _Py_SwappedOp[op];
471 }
472 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000473 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000474 /* exponent is the # of bits in v before the radix point;
475 * we know that nbits (the # of bits in w) > 48 at this point
476 */
477 if (exponent < 0 || (size_t)exponent < nbits) {
478 i = 1.0;
479 j = 2.0;
480 goto Compare;
481 }
482 if ((size_t)exponent > nbits) {
483 i = 2.0;
484 j = 1.0;
485 goto Compare;
486 }
487 /* v and w have the same number of bits before the radix
488 * point. Construct two longs that have the same comparison
489 * outcome.
490 */
491 {
492 double fracpart;
493 double intpart;
494 PyObject *result = NULL;
495 PyObject *one = NULL;
496 PyObject *vv = NULL;
497 PyObject *ww = w;
498
499 if (wsign < 0) {
500 ww = PyNumber_Negative(w);
501 if (ww == NULL)
502 goto Error;
503 }
504 else
505 Py_INCREF(ww);
506
507 fracpart = modf(i, &intpart);
508 vv = PyLong_FromDouble(intpart);
509 if (vv == NULL)
510 goto Error;
511
512 if (fracpart != 0.0) {
513 /* Shift left, and or a 1 bit into vv
514 * to represent the lost fraction.
515 */
516 PyObject *temp;
517
518 one = PyInt_FromLong(1);
519 if (one == NULL)
520 goto Error;
521
522 temp = PyNumber_Lshift(ww, one);
523 if (temp == NULL)
524 goto Error;
525 Py_DECREF(ww);
526 ww = temp;
527
528 temp = PyNumber_Lshift(vv, one);
529 if (temp == NULL)
530 goto Error;
531 Py_DECREF(vv);
532 vv = temp;
533
534 temp = PyNumber_Or(vv, one);
535 if (temp == NULL)
536 goto Error;
537 Py_DECREF(vv);
538 vv = temp;
539 }
540
541 r = PyObject_RichCompareBool(vv, ww, op);
542 if (r < 0)
543 goto Error;
544 result = PyBool_FromLong(r);
545 Error:
546 Py_XDECREF(vv);
547 Py_XDECREF(ww);
548 Py_XDECREF(one);
549 return result;
550 }
551 } /* else if (PyLong_Check(w)) */
552
553 else /* w isn't float, int, or long */
554 goto Unimplemented;
555
556 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000557 PyFPE_START_PROTECT("richcompare", return NULL)
558 switch (op) {
559 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000560 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000561 break;
562 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000563 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000564 break;
565 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000566 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000567 break;
568 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000569 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000570 break;
571 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000572 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000573 break;
574 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000575 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000576 break;
577 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000578 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000579 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000580
581 Unimplemented:
582 Py_INCREF(Py_NotImplemented);
583 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000584}
585
Guido van Rossum9bfef441993-03-29 10:43:31 +0000586static long
Fred Drakefd99de62000-07-09 05:02:18 +0000587float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000588{
Tim Peters39dce292000-08-15 03:34:48 +0000589 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000590}
591
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000593float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000595 double a,b;
596 CONVERT_TO_DOUBLE(v, a);
597 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000598 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000599 a = a + b;
600 PyFPE_END_PROTECT(a)
601 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602}
603
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000605float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000607 double a,b;
608 CONVERT_TO_DOUBLE(v, a);
609 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000610 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000611 a = a - b;
612 PyFPE_END_PROTECT(a)
613 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000614}
615
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000617float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000618{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000619 double a,b;
620 CONVERT_TO_DOUBLE(v, a);
621 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000622 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000623 a = a * b;
624 PyFPE_END_PROTECT(a)
625 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000626}
627
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000628static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000629float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000630{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000631 double a,b;
632 CONVERT_TO_DOUBLE(v, a);
633 CONVERT_TO_DOUBLE(w, b);
634 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636 return NULL;
637 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000638 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000639 a = a / b;
640 PyFPE_END_PROTECT(a)
641 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642}
643
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000645float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000647 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000648 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000649 CONVERT_TO_DOUBLE(v, vx);
650 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653 return NULL;
654 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000655 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000656 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000657 /* note: checking mod*wx < 0 is incorrect -- underflows to
658 0 if wx < sqrt(smallest nonzero double) */
659 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000660 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000661 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000662 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000667float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000668{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000669 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000670 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000671 CONVERT_TO_DOUBLE(v, vx);
672 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000673 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000675 return NULL;
676 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000677 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000678 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000679 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000680 exact multiple of wx. But this is fp arithmetic, and fp
681 vx - mod is an approximation; the result is that div may
682 not be an exact integral value after the division, although
683 it will always be very close to one.
684 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000685 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000686 if (mod) {
687 /* ensure the remainder has the same sign as the denominator */
688 if ((wx < 0) != (mod < 0)) {
689 mod += wx;
690 div -= 1.0;
691 }
692 }
693 else {
694 /* the remainder is zero, and in the presence of signed zeroes
695 fmod returns different results across platforms; ensure
696 it has the same sign as the denominator; we'd like to do
697 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000698 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000699 if (wx < 0.0)
700 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000701 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000702 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000703 if (div) {
704 floordiv = floor(div);
705 if (div - floordiv > 0.5)
706 floordiv += 1.0;
707 }
708 else {
709 /* div is zero - get the same sign as the true quotient */
710 div *= div; /* hide "div = +0" from optimizers */
711 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
712 }
713 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000714 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000715}
716
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000717static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000718float_floor_div(PyObject *v, PyObject *w)
719{
720 PyObject *t, *r;
721
722 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000723 if (t == NULL || t == Py_NotImplemented)
724 return t;
725 assert(PyTuple_CheckExact(t));
726 r = PyTuple_GET_ITEM(t, 0);
727 Py_INCREF(r);
728 Py_DECREF(t);
729 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000730}
731
732static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000733float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000734{
735 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000736
737 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000738 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000739 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000740 return NULL;
741 }
742
Neil Schemenauer32117e52001-01-04 01:44:34 +0000743 CONVERT_TO_DOUBLE(v, iv);
744 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000745
746 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000747 if (iw == 0) { /* v**0 is 1, even 0**0 */
Tim Petersc54d1902000-10-06 00:36:09 +0000748 PyFPE_START_PROTECT("pow", return NULL)
749 if ((PyObject *)z != Py_None) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000750 double iz;
Neil Schemenauer010b0cc2001-01-08 06:29:50 +0000751 CONVERT_TO_DOUBLE(z, iz);
Tim Peters96685bf2001-08-23 22:31:37 +0000752 ix = fmod(1.0, iz);
753 if (ix != 0 && iz < 0)
754 ix += iz;
Guido van Rossum70d93461991-05-28 21:57:39 +0000755 }
Tim Petersc54d1902000-10-06 00:36:09 +0000756 else
757 ix = 1.0;
758 PyFPE_END_PROTECT(ix)
Tim Petersd2364e82001-11-01 20:09:42 +0000759 return PyFloat_FromDouble(ix);
Tim Petersc54d1902000-10-06 00:36:09 +0000760 }
Tim Peters96685bf2001-08-23 22:31:37 +0000761 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000762 if (iw < 0.0) {
763 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000764 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000765 return NULL;
766 }
767 return PyFloat_FromDouble(0.0);
768 }
Tim Peterse87568d2003-05-24 20:18:24 +0000769 if (iv < 0.0) {
770 /* Whether this is an error is a mess, and bumps into libm
771 * bugs so we have to figure it out ourselves.
772 */
773 if (iw != floor(iw)) {
774 PyErr_SetString(PyExc_ValueError, "negative number "
775 "cannot be raised to a fractional power");
776 return NULL;
777 }
778 /* iw is an exact integer, albeit perhaps a very large one.
779 * -1 raised to an exact integer should never be exceptional.
780 * Alas, some libms (chiefly glibc as of early 2003) return
781 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
782 * happen to be representable in a *C* integer. That's a
783 * bug; we let that slide in math.pow() (which currently
784 * reflects all platform accidents), but not for Python's **.
785 */
786 if (iv == -1.0 && !Py_IS_INFINITY(iw) && iw == iw) {
787 /* XXX the "iw == iw" was to weed out NaNs. This
788 * XXX doesn't actually work on all platforms.
789 */
790 /* Return 1 if iw is even, -1 if iw is odd; there's
791 * no guarantee that any C integral type is big
792 * enough to hold iw, so we have to check this
793 * indirectly.
794 */
795 ix = floor(iw * 0.5) * 2.0;
796 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
797 }
798 /* Else iv != -1.0, and overflow or underflow are possible.
799 * Unless we're to write pow() ourselves, we have to trust
800 * the platform to do this correctly.
801 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000802 }
Tim Peters96685bf2001-08-23 22:31:37 +0000803 errno = 0;
804 PyFPE_START_PROTECT("pow", return NULL)
805 ix = pow(iv, iw);
806 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000807 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000808 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000809 /* We don't expect any errno value other than ERANGE, but
810 * the range of libm bugs appears unbounded.
811 */
812 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
813 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000814 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000815 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000816 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000817}
818
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000819static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000820float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000822 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823}
824
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000825static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000826float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000827{
Tim Peters0280cf72001-09-11 21:53:35 +0000828 if (PyFloat_CheckExact(v)) {
829 Py_INCREF(v);
830 return (PyObject *)v;
831 }
832 else
833 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000834}
835
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000837float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000838{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000839 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000840}
841
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000842static int
Fred Drakefd99de62000-07-09 05:02:18 +0000843float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000844{
845 return v->ob_fval != 0.0;
846}
847
Guido van Rossum234f9421993-06-17 12:35:49 +0000848static int
Fred Drakefd99de62000-07-09 05:02:18 +0000849float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000850{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000851 if (PyInt_Check(*pw)) {
852 long x = PyInt_AsLong(*pw);
853 *pw = PyFloat_FromDouble((double)x);
854 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000855 return 0;
856 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000857 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000858 double x = PyLong_AsDouble(*pw);
859 if (x == -1.0 && PyErr_Occurred())
860 return -1;
861 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000862 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000863 return 0;
864 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000865 else if (PyFloat_Check(*pw)) {
866 Py_INCREF(*pv);
867 Py_INCREF(*pw);
868 return 0;
869 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000870 return 1; /* Can't do it */
871}
872
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000873static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000874float_long(PyObject *v)
875{
876 double x = PyFloat_AsDouble(v);
877 return PyLong_FromDouble(x);
878}
879
880static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000881float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000882{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000883 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000884 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000885
886 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000887 /* Try to get out cheap if this fits in a Python int. The attempt
888 * to cast to long must be protected, as C doesn't define what
889 * happens if the double is too big to fit in a long. Some rare
890 * systems raise an exception then (RISCOS was mentioned as one,
891 * and someone using a non-default option on Sun also bumped into
892 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
893 * still be vulnerable: if a long has more bits of precision than
894 * a double, casting MIN/MAX to double may yield an approximation,
895 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
896 * yield true from the C expression wholepart<=LONG_MAX, despite
897 * that wholepart is actually greater than LONG_MAX.
898 */
899 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
900 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000901 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000902 }
903 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000904}
905
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000906static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000907float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000908{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000909 if (PyFloat_CheckExact(v))
910 Py_INCREF(v);
911 else
912 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000913 return v;
914}
915
916
Jeremy Hylton938ace62002-07-17 16:30:39 +0000917static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000918float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
919
Tim Peters6d6c1a32001-08-02 04:15:00 +0000920static PyObject *
921float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
922{
923 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000924 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000925
Guido van Rossumbef14172001-08-29 15:47:46 +0000926 if (type != &PyFloat_Type)
927 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000928 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
929 return NULL;
930 if (PyString_Check(x))
931 return PyFloat_FromString(x, NULL);
932 return PyNumber_Float(x);
933}
934
Guido van Rossumbef14172001-08-29 15:47:46 +0000935/* Wimpy, slow approach to tp_new calls for subtypes of float:
936 first create a regular float from whatever arguments we got,
937 then allocate a subtype instance and initialize its ob_fval
938 from the regular float. The regular float is then thrown away.
939*/
940static PyObject *
941float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
942{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000943 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000944
945 assert(PyType_IsSubtype(type, &PyFloat_Type));
946 tmp = float_new(&PyFloat_Type, args, kwds);
947 if (tmp == NULL)
948 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000949 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000950 newobj = type->tp_alloc(type, 0);
951 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000952 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000953 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000954 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000955 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000956 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000957 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000958}
959
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000960static PyObject *
961float_getnewargs(PyFloatObject *v)
962{
963 return Py_BuildValue("(d)", v->ob_fval);
964}
965
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000966/* this is for the benefit of the pack/unpack routines below */
967
968typedef enum {
969 unknown_format, ieee_big_endian_format, ieee_little_endian_format
970} float_format_type;
971
972static float_format_type double_format, float_format;
973static float_format_type detected_double_format, detected_float_format;
974
975static PyObject *
976float_getformat(PyTypeObject *v, PyObject* arg)
977{
978 char* s;
979 float_format_type r;
980
981 if (!PyString_Check(arg)) {
982 PyErr_Format(PyExc_TypeError,
983 "__getformat__() argument must be string, not %.500s",
984 arg->ob_type->tp_name);
985 return NULL;
986 }
987 s = PyString_AS_STRING(arg);
988 if (strcmp(s, "double") == 0) {
989 r = double_format;
990 }
991 else if (strcmp(s, "float") == 0) {
992 r = float_format;
993 }
994 else {
995 PyErr_SetString(PyExc_ValueError,
996 "__getformat__() argument 1 must be "
997 "'double' or 'float'");
998 return NULL;
999 }
1000
1001 switch (r) {
1002 case unknown_format:
1003 return PyString_FromString("unknown");
1004 case ieee_little_endian_format:
1005 return PyString_FromString("IEEE, little-endian");
1006 case ieee_big_endian_format:
1007 return PyString_FromString("IEEE, big-endian");
1008 default:
1009 Py_FatalError("insane float_format or double_format");
1010 return NULL;
1011 }
1012}
1013
1014PyDoc_STRVAR(float_getformat_doc,
1015"float.__getformat__(typestr) -> string\n"
1016"\n"
1017"You probably don't want to use this function. It exists mainly to be\n"
1018"used in Python's test suite.\n"
1019"\n"
1020"typestr must be 'double' or 'float'. This function returns whichever of\n"
1021"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1022"format of floating point numbers used by the C type named by typestr.");
1023
1024static PyObject *
1025float_setformat(PyTypeObject *v, PyObject* args)
1026{
1027 char* typestr;
1028 char* format;
1029 float_format_type f;
1030 float_format_type detected;
1031 float_format_type *p;
1032
1033 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1034 return NULL;
1035
1036 if (strcmp(typestr, "double") == 0) {
1037 p = &double_format;
1038 detected = detected_double_format;
1039 }
1040 else if (strcmp(typestr, "float") == 0) {
1041 p = &float_format;
1042 detected = detected_float_format;
1043 }
1044 else {
1045 PyErr_SetString(PyExc_ValueError,
1046 "__setformat__() argument 1 must "
1047 "be 'double' or 'float'");
1048 return NULL;
1049 }
1050
1051 if (strcmp(format, "unknown") == 0) {
1052 f = unknown_format;
1053 }
1054 else if (strcmp(format, "IEEE, little-endian") == 0) {
1055 f = ieee_little_endian_format;
1056 }
1057 else if (strcmp(format, "IEEE, big-endian") == 0) {
1058 f = ieee_big_endian_format;
1059 }
1060 else {
1061 PyErr_SetString(PyExc_ValueError,
1062 "__setformat__() argument 2 must be "
1063 "'unknown', 'IEEE, little-endian' or "
1064 "'IEEE, big-endian'");
1065 return NULL;
1066
1067 }
1068
1069 if (f != unknown_format && f != detected) {
1070 PyErr_Format(PyExc_ValueError,
1071 "can only set %s format to 'unknown' or the "
1072 "detected platform value", typestr);
1073 return NULL;
1074 }
1075
1076 *p = f;
1077 Py_RETURN_NONE;
1078}
1079
1080PyDoc_STRVAR(float_setformat_doc,
1081"float.__setformat__(typestr, fmt) -> None\n"
1082"\n"
1083"You probably don't want to use this function. It exists mainly to be\n"
1084"used in Python's test suite.\n"
1085"\n"
1086"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1087"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1088"one of the latter two if it appears to match the underlying C reality.\n"
1089"\n"
1090"Overrides the automatic determination of C-level floating point type.\n"
1091"This affects how floats are converted to and from binary strings.");
1092
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001093static PyMethodDef float_methods[] = {
1094 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001095 {"__getformat__", (PyCFunction)float_getformat,
1096 METH_O|METH_CLASS, float_getformat_doc},
1097 {"__setformat__", (PyCFunction)float_setformat,
1098 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001099 {NULL, NULL} /* sentinel */
1100};
1101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001102PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103"float(x) -> floating point number\n\
1104\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001105Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106
1107
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001108static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001109 float_add, /*nb_add*/
1110 float_sub, /*nb_subtract*/
1111 float_mul, /*nb_multiply*/
1112 float_rem, /*nb_remainder*/
1113 float_divmod, /*nb_divmod*/
1114 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001115 (unaryfunc)float_neg, /*nb_negative*/
1116 (unaryfunc)float_pos, /*nb_positive*/
1117 (unaryfunc)float_abs, /*nb_absolute*/
1118 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001119 0, /*nb_invert*/
1120 0, /*nb_lshift*/
1121 0, /*nb_rshift*/
1122 0, /*nb_and*/
1123 0, /*nb_xor*/
1124 0, /*nb_or*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125 float_coerce, /*nb_coerce*/
1126 float_int, /*nb_int*/
1127 float_long, /*nb_long*/
1128 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001129 0, /* nb_oct */
1130 0, /* nb_hex */
1131 0, /* nb_inplace_add */
1132 0, /* nb_inplace_subtract */
1133 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001134 0, /* nb_inplace_remainder */
1135 0, /* nb_inplace_power */
1136 0, /* nb_inplace_lshift */
1137 0, /* nb_inplace_rshift */
1138 0, /* nb_inplace_and */
1139 0, /* nb_inplace_xor */
1140 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001141 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001142 float_div, /* nb_true_divide */
1143 0, /* nb_inplace_floor_divide */
1144 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001145};
1146
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001147PyTypeObject PyFloat_Type = {
1148 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001149 0,
1150 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001151 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001152 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 (destructor)float_dealloc, /* tp_dealloc */
1154 (printfunc)float_print, /* tp_print */
1155 0, /* tp_getattr */
1156 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001157 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001158 (reprfunc)float_repr, /* tp_repr */
1159 &float_as_number, /* tp_as_number */
1160 0, /* tp_as_sequence */
1161 0, /* tp_as_mapping */
1162 (hashfunc)float_hash, /* tp_hash */
1163 0, /* tp_call */
1164 (reprfunc)float_str, /* tp_str */
1165 PyObject_GenericGetAttr, /* tp_getattro */
1166 0, /* tp_setattro */
1167 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001168 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1169 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170 float_doc, /* tp_doc */
1171 0, /* tp_traverse */
1172 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001173 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174 0, /* tp_weaklistoffset */
1175 0, /* tp_iter */
1176 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001177 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 0, /* tp_members */
1179 0, /* tp_getset */
1180 0, /* tp_base */
1181 0, /* tp_dict */
1182 0, /* tp_descr_get */
1183 0, /* tp_descr_set */
1184 0, /* tp_dictoffset */
1185 0, /* tp_init */
1186 0, /* tp_alloc */
1187 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001188};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001189
1190void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001191_PyFloat_Init(void)
1192{
1193 /* We attempt to determine if this machine is using IEEE
1194 floating point formats by peering at the bits of some
1195 carefully chosen values. If it looks like we are on an
1196 IEEE platform, the float packing/unpacking routines can
1197 just copy bits, if not they resort to arithmetic & shifts
1198 and masks. The shifts & masks approach works on all finite
1199 values, but what happens to infinities, NaNs and signed
1200 zeroes on packing is an accident, and attempting to unpack
1201 a NaN or an infinity will raise an exception.
1202
1203 Note that if we're on some whacked-out platform which uses
1204 IEEE formats but isn't strictly little-endian or big-
1205 endian, we will fall back to the portable shifts & masks
1206 method. */
1207
1208#if SIZEOF_DOUBLE == 8
1209 {
1210 double x = 9006104071832581.0;
1211 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1212 detected_double_format = ieee_big_endian_format;
1213 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1214 detected_double_format = ieee_little_endian_format;
1215 else
1216 detected_double_format = unknown_format;
1217 }
1218#else
1219 detected_double_format = unknown_format;
1220#endif
1221
1222#if SIZEOF_FLOAT == 4
1223 {
1224 float y = 16711938.0;
1225 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1226 detected_float_format = ieee_big_endian_format;
1227 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1228 detected_float_format = ieee_little_endian_format;
1229 else
1230 detected_float_format = unknown_format;
1231 }
1232#else
1233 detected_float_format = unknown_format;
1234#endif
1235
1236 double_format = detected_double_format;
1237 float_format = detected_float_format;
1238}
1239
1240void
Fred Drakefd99de62000-07-09 05:02:18 +00001241PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001242{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001243 PyFloatObject *p;
1244 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001245 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001246 int bc, bf; /* block count, number of freed blocks */
1247 int frem, fsum; /* remaining unfreed floats per block, total */
1248
1249 bc = 0;
1250 bf = 0;
1251 fsum = 0;
1252 list = block_list;
1253 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001254 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001255 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001256 bc++;
1257 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001258 for (i = 0, p = &list->objects[0];
1259 i < N_FLOATOBJECTS;
1260 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001261 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001262 frem++;
1263 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001264 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001265 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001266 list->next = block_list;
1267 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001268 for (i = 0, p = &list->objects[0];
1269 i < N_FLOATOBJECTS;
1270 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001271 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +00001272 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001273 p->ob_type = (struct _typeobject *)
1274 free_list;
1275 free_list = p;
1276 }
1277 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001278 }
1279 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001280 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001281 bf++;
1282 }
1283 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001284 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001285 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001286 if (!Py_VerboseFlag)
1287 return;
1288 fprintf(stderr, "# cleanup floats");
1289 if (!fsum) {
1290 fprintf(stderr, "\n");
1291 }
1292 else {
1293 fprintf(stderr,
1294 ": %d unfreed float%s in %d out of %d block%s\n",
1295 fsum, fsum == 1 ? "" : "s",
1296 bc - bf, bc, bc == 1 ? "" : "s");
1297 }
1298 if (Py_VerboseFlag > 1) {
1299 list = block_list;
1300 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001301 for (i = 0, p = &list->objects[0];
1302 i < N_FLOATOBJECTS;
1303 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001304 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +00001305 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001306 char buf[100];
1307 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001308 /* XXX(twouters) cast refcount to
1309 long until %zd is universally
1310 available
1311 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001312 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001313 "# <float at %p, refcnt=%ld, val=%s>\n",
1314 p, (long)p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001315 }
1316 }
1317 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001318 }
1319 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001320}
Tim Peters9905b942003-03-20 20:53:32 +00001321
1322/*----------------------------------------------------------------------------
1323 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1324 *
1325 * TODO: On platforms that use the standard IEEE-754 single and double
1326 * formats natively, these routines could simply copy the bytes.
1327 */
1328int
1329_PyFloat_Pack4(double x, unsigned char *p, int le)
1330{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001331 if (float_format == unknown_format) {
1332 unsigned char sign;
1333 int e;
1334 double f;
1335 unsigned int fbits;
1336 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001337
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001338 if (le) {
1339 p += 3;
1340 incr = -1;
1341 }
Tim Peters9905b942003-03-20 20:53:32 +00001342
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001343 if (x < 0) {
1344 sign = 1;
1345 x = -x;
1346 }
1347 else
1348 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001349
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001350 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001351
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001352 /* Normalize f to be in the range [1.0, 2.0) */
1353 if (0.5 <= f && f < 1.0) {
1354 f *= 2.0;
1355 e--;
1356 }
1357 else if (f == 0.0)
1358 e = 0;
1359 else {
1360 PyErr_SetString(PyExc_SystemError,
1361 "frexp() result out of range");
1362 return -1;
1363 }
1364
1365 if (e >= 128)
1366 goto Overflow;
1367 else if (e < -126) {
1368 /* Gradual underflow */
1369 f = ldexp(f, 126 + e);
1370 e = 0;
1371 }
1372 else if (!(e == 0 && f == 0.0)) {
1373 e += 127;
1374 f -= 1.0; /* Get rid of leading 1 */
1375 }
1376
1377 f *= 8388608.0; /* 2**23 */
1378 fbits = (unsigned int)(f + 0.5); /* Round */
1379 assert(fbits <= 8388608);
1380 if (fbits >> 23) {
1381 /* The carry propagated out of a string of 23 1 bits. */
1382 fbits = 0;
1383 ++e;
1384 if (e >= 255)
1385 goto Overflow;
1386 }
1387
1388 /* First byte */
1389 *p = (sign << 7) | (e >> 1);
1390 p += incr;
1391
1392 /* Second byte */
1393 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1394 p += incr;
1395
1396 /* Third byte */
1397 *p = (fbits >> 8) & 0xFF;
1398 p += incr;
1399
1400 /* Fourth byte */
1401 *p = fbits & 0xFF;
1402
1403 /* Done */
1404 return 0;
1405
1406 Overflow:
1407 PyErr_SetString(PyExc_OverflowError,
1408 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001409 return -1;
1410 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001411 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001412 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001413 const char *s = (char*)&y;
1414 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001415
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001416 if ((float_format == ieee_little_endian_format && !le)
1417 || (float_format == ieee_big_endian_format && le)) {
1418 p += 3;
1419 incr = -1;
1420 }
1421
1422 for (i = 0; i < 4; i++) {
1423 *p = *s++;
1424 p += incr;
1425 }
1426 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001427 }
Tim Peters9905b942003-03-20 20:53:32 +00001428}
1429
1430int
1431_PyFloat_Pack8(double x, unsigned char *p, int le)
1432{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001433 if (double_format == unknown_format) {
1434 unsigned char sign;
1435 int e;
1436 double f;
1437 unsigned int fhi, flo;
1438 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001439
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001440 if (le) {
1441 p += 7;
1442 incr = -1;
1443 }
Tim Peters9905b942003-03-20 20:53:32 +00001444
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001445 if (x < 0) {
1446 sign = 1;
1447 x = -x;
1448 }
1449 else
1450 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001451
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001452 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001453
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001454 /* Normalize f to be in the range [1.0, 2.0) */
1455 if (0.5 <= f && f < 1.0) {
1456 f *= 2.0;
1457 e--;
1458 }
1459 else if (f == 0.0)
1460 e = 0;
1461 else {
1462 PyErr_SetString(PyExc_SystemError,
1463 "frexp() result out of range");
1464 return -1;
1465 }
1466
1467 if (e >= 1024)
1468 goto Overflow;
1469 else if (e < -1022) {
1470 /* Gradual underflow */
1471 f = ldexp(f, 1022 + e);
1472 e = 0;
1473 }
1474 else if (!(e == 0 && f == 0.0)) {
1475 e += 1023;
1476 f -= 1.0; /* Get rid of leading 1 */
1477 }
1478
1479 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1480 f *= 268435456.0; /* 2**28 */
1481 fhi = (unsigned int)f; /* Truncate */
1482 assert(fhi < 268435456);
1483
1484 f -= (double)fhi;
1485 f *= 16777216.0; /* 2**24 */
1486 flo = (unsigned int)(f + 0.5); /* Round */
1487 assert(flo <= 16777216);
1488 if (flo >> 24) {
1489 /* The carry propagated out of a string of 24 1 bits. */
1490 flo = 0;
1491 ++fhi;
1492 if (fhi >> 28) {
1493 /* And it also progagated out of the next 28 bits. */
1494 fhi = 0;
1495 ++e;
1496 if (e >= 2047)
1497 goto Overflow;
1498 }
1499 }
1500
1501 /* First byte */
1502 *p = (sign << 7) | (e >> 4);
1503 p += incr;
1504
1505 /* Second byte */
1506 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1507 p += incr;
1508
1509 /* Third byte */
1510 *p = (fhi >> 16) & 0xFF;
1511 p += incr;
1512
1513 /* Fourth byte */
1514 *p = (fhi >> 8) & 0xFF;
1515 p += incr;
1516
1517 /* Fifth byte */
1518 *p = fhi & 0xFF;
1519 p += incr;
1520
1521 /* Sixth byte */
1522 *p = (flo >> 16) & 0xFF;
1523 p += incr;
1524
1525 /* Seventh byte */
1526 *p = (flo >> 8) & 0xFF;
1527 p += incr;
1528
1529 /* Eighth byte */
1530 *p = flo & 0xFF;
1531 p += incr;
1532
1533 /* Done */
1534 return 0;
1535
1536 Overflow:
1537 PyErr_SetString(PyExc_OverflowError,
1538 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001539 return -1;
1540 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001541 else {
1542 const char *s = (char*)&x;
1543 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001544
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001545 if ((double_format == ieee_little_endian_format && !le)
1546 || (double_format == ieee_big_endian_format && le)) {
1547 p += 7;
1548 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001549 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001550
1551 for (i = 0; i < 8; i++) {
1552 *p = *s++;
1553 p += incr;
1554 }
1555 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001556 }
Tim Peters9905b942003-03-20 20:53:32 +00001557}
1558
1559double
1560_PyFloat_Unpack4(const unsigned char *p, int le)
1561{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001562 if (float_format == unknown_format) {
1563 unsigned char sign;
1564 int e;
1565 unsigned int f;
1566 double x;
1567 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001568
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001569 if (le) {
1570 p += 3;
1571 incr = -1;
1572 }
1573
1574 /* First byte */
1575 sign = (*p >> 7) & 1;
1576 e = (*p & 0x7F) << 1;
1577 p += incr;
1578
1579 /* Second byte */
1580 e |= (*p >> 7) & 1;
1581 f = (*p & 0x7F) << 16;
1582 p += incr;
1583
1584 if (e == 255) {
1585 PyErr_SetString(
1586 PyExc_ValueError,
1587 "can't unpack IEEE 754 special value "
1588 "on non-IEEE platform");
1589 return -1;
1590 }
1591
1592 /* Third byte */
1593 f |= *p << 8;
1594 p += incr;
1595
1596 /* Fourth byte */
1597 f |= *p;
1598
1599 x = (double)f / 8388608.0;
1600
1601 /* XXX This sadly ignores Inf/NaN issues */
1602 if (e == 0)
1603 e = -126;
1604 else {
1605 x += 1.0;
1606 e -= 127;
1607 }
1608 x = ldexp(x, e);
1609
1610 if (sign)
1611 x = -x;
1612
1613 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001614 }
Tim Peters9905b942003-03-20 20:53:32 +00001615 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001616 float x;
1617
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618 if ((float_format == ieee_little_endian_format && !le)
1619 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001620 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621 char *d = &buf[3];
1622 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001623
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 for (i = 0; i < 4; i++) {
1625 *d-- = *p++;
1626 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001627 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001628 }
1629 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001630 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001631 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001632
1633 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001634 }
Tim Peters9905b942003-03-20 20:53:32 +00001635}
1636
1637double
1638_PyFloat_Unpack8(const unsigned char *p, int le)
1639{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001640 if (double_format == unknown_format) {
1641 unsigned char sign;
1642 int e;
1643 unsigned int fhi, flo;
1644 double x;
1645 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001646
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001647 if (le) {
1648 p += 7;
1649 incr = -1;
1650 }
1651
1652 /* First byte */
1653 sign = (*p >> 7) & 1;
1654 e = (*p & 0x7F) << 4;
1655
1656 p += incr;
1657
1658 /* Second byte */
1659 e |= (*p >> 4) & 0xF;
1660 fhi = (*p & 0xF) << 24;
1661 p += incr;
1662
1663 if (e == 2047) {
1664 PyErr_SetString(
1665 PyExc_ValueError,
1666 "can't unpack IEEE 754 special value "
1667 "on non-IEEE platform");
1668 return -1.0;
1669 }
1670
1671 /* Third byte */
1672 fhi |= *p << 16;
1673 p += incr;
1674
1675 /* Fourth byte */
1676 fhi |= *p << 8;
1677 p += incr;
1678
1679 /* Fifth byte */
1680 fhi |= *p;
1681 p += incr;
1682
1683 /* Sixth byte */
1684 flo = *p << 16;
1685 p += incr;
1686
1687 /* Seventh byte */
1688 flo |= *p << 8;
1689 p += incr;
1690
1691 /* Eighth byte */
1692 flo |= *p;
1693
1694 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1695 x /= 268435456.0; /* 2**28 */
1696
1697 if (e == 0)
1698 e = -1022;
1699 else {
1700 x += 1.0;
1701 e -= 1023;
1702 }
1703 x = ldexp(x, e);
1704
1705 if (sign)
1706 x = -x;
1707
1708 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001709 }
Tim Peters9905b942003-03-20 20:53:32 +00001710 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001711 double x;
1712
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001713 if ((double_format == ieee_little_endian_format && !le)
1714 || (double_format == ieee_big_endian_format && le)) {
1715 char buf[8];
1716 char *d = &buf[7];
1717 int i;
1718
1719 for (i = 0; i < 8; i++) {
1720 *d-- = *p++;
1721 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001722 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001723 }
1724 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001725 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001726 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001727
1728 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001729 }
Tim Peters9905b942003-03-20 20:53:32 +00001730}