blob: 9e6db549edafd310f7917ad31447d59f4362bc00 [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
Barry Warsaw226ae6c1999-10-12 19:54:53 +000065PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +000066PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +000067{
Guido van Rossum4c08d552000-03-10 22:55:18 +000068 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000069 double x;
Tim Petersef14d732000-09-23 03:39:17 +000070 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000071#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +000072 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000073#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +000074 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000075
Guido van Rossum4c08d552000-03-10 22:55:18 +000076 if (PyString_Check(v)) {
77 s = PyString_AS_STRING(v);
78 len = PyString_GET_SIZE(v);
79 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +000080#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +000081 else if (PyUnicode_Check(v)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000082 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +000083 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +000084 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +000085 return NULL;
86 }
Tim Petersef14d732000-09-23 03:39:17 +000087 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +000088 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +000089 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +000090 NULL))
91 return NULL;
92 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +000093 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +000094 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +000095#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +000096 else if (PyObject_AsCharBuffer(v, &s, &len)) {
97 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +000098 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +000099 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000100 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000101
Guido van Rossum4c08d552000-03-10 22:55:18 +0000102 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000103 while (*s && isspace(Py_CHARMASK(*s)))
104 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000105 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000106 PyErr_SetString(PyExc_ValueError, "empty string for float()");
107 return NULL;
108 }
Tim Petersef14d732000-09-23 03:39:17 +0000109 /* We don't care about overflow or underflow. If the platform supports
110 * them, infinities and signed zeroes (on underflow) are fine.
111 * However, strtod can return 0 for denormalized numbers, where atof
112 * does not. So (alas!) we special-case a zero result. Note that
113 * whether strtod sets errno on underflow is not defined, so we can't
114 * key off errno.
115 */
Tim Peters858346e2000-09-25 21:01:28 +0000116 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000117 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000118 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000119 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000120 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000121 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000122 if (end > last)
123 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000124 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000125 PyOS_snprintf(buffer, sizeof(buffer),
126 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000127 PyErr_SetString(PyExc_ValueError, buffer);
128 return NULL;
129 }
130 /* Since end != s, the platform made *some* kind of sense out
131 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000132 while (*end && isspace(Py_CHARMASK(*end)))
133 end++;
134 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000135 PyOS_snprintf(buffer, sizeof(buffer),
136 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000137 PyErr_SetString(PyExc_ValueError, buffer);
138 return NULL;
139 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000140 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000141 PyErr_SetString(PyExc_ValueError,
142 "null byte in argument for float()");
143 return NULL;
144 }
Tim Petersef14d732000-09-23 03:39:17 +0000145 if (x == 0.0) {
146 /* See above -- may have been strtod being anal
147 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000148 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000149 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000150 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000151 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000152 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000153 return PyFloat_FromDouble(x);
154}
155
Guido van Rossum234f9421993-06-17 12:35:49 +0000156static void
Fred Drakefd99de62000-07-09 05:02:18 +0000157float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000158{
Guido van Rossum9475a232001-10-05 20:51:39 +0000159 if (PyFloat_CheckExact(op)) {
160 op->ob_type = (struct _typeobject *)free_list;
161 free_list = op;
162 }
163 else
164 op->ob_type->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000165}
166
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167double
Fred Drakefd99de62000-07-09 05:02:18 +0000168PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 PyNumberMethods *nb;
171 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000172 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000173
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174 if (op && PyFloat_Check(op))
175 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000176
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000177 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179 return -1;
180 }
Tim Petersd2364e82001-11-01 20:09:42 +0000181
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000182 if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) {
183 PyErr_SetString(PyExc_TypeError, "a float is required");
184 return -1;
185 }
186
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000188 if (fo == NULL)
189 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 if (!PyFloat_Check(fo)) {
191 PyErr_SetString(PyExc_TypeError,
192 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000193 return -1;
194 }
Tim Petersd2364e82001-11-01 20:09:42 +0000195
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196 val = PyFloat_AS_DOUBLE(fo);
197 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000198
Guido van Rossumb6775db1994-08-01 11:34:53 +0000199 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
202/* Methods */
203
Tim Peters97019e42001-11-28 22:43:45 +0000204static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000205format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206{
207 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000208 char format[32];
Neal Norwitz545686b2006-12-28 04:45:06 +0000209 /* Subroutine for float_repr, float_str, float_print and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000210 We want float numbers to be recognizable as such,
211 i.e., they should contain a decimal point or an exponent.
212 However, %g may print the number as an integer;
213 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000214
Martin v. Löwis737ea822004-06-08 18:52:54 +0000215 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000216 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217 cp = buf;
218 if (*cp == '-')
219 cp++;
220 for (; *cp != '\0'; cp++) {
221 /* Any non-digit means it's not an integer;
222 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000223 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224 break;
225 }
226 if (*cp == '\0') {
227 *cp++ = '.';
228 *cp++ = '0';
229 *cp++ = '\0';
230 }
231}
232
Neal Norwitz545686b2006-12-28 04:45:06 +0000233static void
234format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000235{
Neal Norwitz545686b2006-12-28 04:45:06 +0000236 assert(PyFloat_Check(v));
237 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000238}
239
Neil Schemenauer32117e52001-01-04 01:44:34 +0000240/* Macro and helper that convert PyObject obj to a C double and store
241 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000242 slot function. If conversion to double raises an exception, obj is
243 set to NULL, and the function invoking this macro returns NULL. If
244 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
245 stored in obj, and returned from the function invoking this macro.
246*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000247#define CONVERT_TO_DOUBLE(obj, dbl) \
248 if (PyFloat_Check(obj)) \
249 dbl = PyFloat_AS_DOUBLE(obj); \
250 else if (convert_to_double(&(obj), &(dbl)) < 0) \
251 return obj;
252
253static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000254convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000255{
256 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000257
Guido van Rossumddefaf32007-01-14 03:31:43 +0000258 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000259 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000260 if (*dbl == -1.0 && PyErr_Occurred()) {
261 *v = NULL;
262 return -1;
263 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264 }
265 else {
266 Py_INCREF(Py_NotImplemented);
267 *v = Py_NotImplemented;
268 return -1;
269 }
270 return 0;
271}
272
Guido van Rossum57072eb1999-12-23 19:00:28 +0000273/* Precisions used by repr() and str(), respectively.
274
275 The repr() precision (17 significant decimal digits) is the minimal number
276 that is guaranteed to have enough precision so that if the number is read
277 back in the exact same binary value is recreated. This is true for IEEE
278 floating point by design, and also happens to work for all other modern
279 hardware.
280
281 The str() precision is chosen so that in most cases, the rounding noise
282 created by various operations is suppressed, while giving plenty of
283 precision for practical use.
284
285*/
286
287#define PREC_REPR 17
288#define PREC_STR 12
289
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000290/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000291static int
Fred Drakefd99de62000-07-09 05:02:18 +0000292float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293{
294 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000295 format_float(buf, sizeof(buf), v,
296 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000297 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000298 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299}
300
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000301static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000302float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303{
304 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000305 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000306 return PyString_FromString(buf);
307}
308
309static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000310float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000311{
312 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000313 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000314 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315}
316
Tim Peters307fa782004-09-23 08:06:40 +0000317/* Comparison is pretty much a nightmare. When comparing float to float,
318 * we do it as straightforwardly (and long-windedly) as conceivable, so
319 * that, e.g., Python x == y delivers the same result as the platform
320 * C x == y when x and/or y is a NaN.
321 * When mixing float with an integer type, there's no good *uniform* approach.
322 * Converting the double to an integer obviously doesn't work, since we
323 * may lose info from fractional bits. Converting the integer to a double
324 * also has two failure modes: (1) a long int may trigger overflow (too
325 * large to fit in the dynamic range of a C double); (2) even a C long may have
326 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
327 * 63 bits of precision, but a C double probably has only 53), and then
328 * we can falsely claim equality when low-order integer bits are lost by
329 * coercion to double. So this part is painful too.
330 */
331
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000332static PyObject*
333float_richcompare(PyObject *v, PyObject *w, int op)
334{
335 double i, j;
336 int r = 0;
337
Tim Peters307fa782004-09-23 08:06:40 +0000338 assert(PyFloat_Check(v));
339 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000340
Tim Peters307fa782004-09-23 08:06:40 +0000341 /* Switch on the type of w. Set i and j to doubles to be compared,
342 * and op to the richcomp to use.
343 */
344 if (PyFloat_Check(w))
345 j = PyFloat_AS_DOUBLE(w);
346
Thomas Wouters477c8d52006-05-27 19:21:47 +0000347 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000348 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000349 /* If i is an infinity, its magnitude exceeds any
350 * finite integer, so it doesn't matter which int we
351 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000352 */
353 j = 0.0;
354 else
355 goto Unimplemented;
356 }
357
Tim Peters307fa782004-09-23 08:06:40 +0000358 else if (PyLong_Check(w)) {
359 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
360 int wsign = _PyLong_Sign(w);
361 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000362 int exponent;
363
364 if (vsign != wsign) {
365 /* Magnitudes are irrelevant -- the signs alone
366 * determine the outcome.
367 */
368 i = (double)vsign;
369 j = (double)wsign;
370 goto Compare;
371 }
372 /* The signs are the same. */
373 /* Convert w to a double if it fits. In particular, 0 fits. */
374 nbits = _PyLong_NumBits(w);
375 if (nbits == (size_t)-1 && PyErr_Occurred()) {
376 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000377 * to hold the # of bits. Replace with little doubles
378 * that give the same outcome -- w is so large that
379 * its magnitude must exceed the magnitude of any
380 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000381 */
382 PyErr_Clear();
383 i = (double)vsign;
384 assert(wsign != 0);
385 j = wsign * 2.0;
386 goto Compare;
387 }
388 if (nbits <= 48) {
389 j = PyLong_AsDouble(w);
390 /* It's impossible that <= 48 bits overflowed. */
391 assert(j != -1.0 || ! PyErr_Occurred());
392 goto Compare;
393 }
394 assert(wsign != 0); /* else nbits was 0 */
395 assert(vsign != 0); /* if vsign were 0, then since wsign is
396 * not 0, we would have taken the
397 * vsign != wsign branch at the start */
398 /* We want to work with non-negative numbers. */
399 if (vsign < 0) {
400 /* "Multiply both sides" by -1; this also swaps the
401 * comparator.
402 */
403 i = -i;
404 op = _Py_SwappedOp[op];
405 }
406 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000407 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000408 /* exponent is the # of bits in v before the radix point;
409 * we know that nbits (the # of bits in w) > 48 at this point
410 */
411 if (exponent < 0 || (size_t)exponent < nbits) {
412 i = 1.0;
413 j = 2.0;
414 goto Compare;
415 }
416 if ((size_t)exponent > nbits) {
417 i = 2.0;
418 j = 1.0;
419 goto Compare;
420 }
421 /* v and w have the same number of bits before the radix
422 * point. Construct two longs that have the same comparison
423 * outcome.
424 */
425 {
426 double fracpart;
427 double intpart;
428 PyObject *result = NULL;
429 PyObject *one = NULL;
430 PyObject *vv = NULL;
431 PyObject *ww = w;
432
433 if (wsign < 0) {
434 ww = PyNumber_Negative(w);
435 if (ww == NULL)
436 goto Error;
437 }
438 else
439 Py_INCREF(ww);
440
441 fracpart = modf(i, &intpart);
442 vv = PyLong_FromDouble(intpart);
443 if (vv == NULL)
444 goto Error;
445
446 if (fracpart != 0.0) {
447 /* Shift left, and or a 1 bit into vv
448 * to represent the lost fraction.
449 */
450 PyObject *temp;
451
452 one = PyInt_FromLong(1);
453 if (one == NULL)
454 goto Error;
455
456 temp = PyNumber_Lshift(ww, one);
457 if (temp == NULL)
458 goto Error;
459 Py_DECREF(ww);
460 ww = temp;
461
462 temp = PyNumber_Lshift(vv, one);
463 if (temp == NULL)
464 goto Error;
465 Py_DECREF(vv);
466 vv = temp;
467
468 temp = PyNumber_Or(vv, one);
469 if (temp == NULL)
470 goto Error;
471 Py_DECREF(vv);
472 vv = temp;
473 }
474
475 r = PyObject_RichCompareBool(vv, ww, op);
476 if (r < 0)
477 goto Error;
478 result = PyBool_FromLong(r);
479 Error:
480 Py_XDECREF(vv);
481 Py_XDECREF(ww);
482 Py_XDECREF(one);
483 return result;
484 }
485 } /* else if (PyLong_Check(w)) */
486
487 else /* w isn't float, int, or long */
488 goto Unimplemented;
489
490 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000491 PyFPE_START_PROTECT("richcompare", return NULL)
492 switch (op) {
493 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000494 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000495 break;
496 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000497 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000498 break;
499 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000500 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000501 break;
502 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000503 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000504 break;
505 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000506 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000507 break;
508 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000509 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000510 break;
511 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000512 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000513 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000514
515 Unimplemented:
516 Py_INCREF(Py_NotImplemented);
517 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000518}
519
Guido van Rossum9bfef441993-03-29 10:43:31 +0000520static long
Fred Drakefd99de62000-07-09 05:02:18 +0000521float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000522{
Tim Peters39dce292000-08-15 03:34:48 +0000523 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000524}
525
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000527float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529 double a,b;
530 CONVERT_TO_DOUBLE(v, a);
531 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000532 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000533 a = a + b;
534 PyFPE_END_PROTECT(a)
535 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000536}
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000539float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541 double a,b;
542 CONVERT_TO_DOUBLE(v, a);
543 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000544 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000545 a = a - b;
546 PyFPE_END_PROTECT(a)
547 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548}
549
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000551float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553 double a,b;
554 CONVERT_TO_DOUBLE(v, a);
555 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000556 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000557 a = a * b;
558 PyFPE_END_PROTECT(a)
559 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565 double a,b;
566 CONVERT_TO_DOUBLE(v, a);
567 CONVERT_TO_DOUBLE(w, b);
568 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570 return NULL;
571 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000572 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573 a = a / b;
574 PyFPE_END_PROTECT(a)
575 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000576}
577
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000578static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000579float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000581 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000582 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000583 CONVERT_TO_DOUBLE(v, vx);
584 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587 return NULL;
588 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000589 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000590 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000591 /* note: checking mod*wx < 0 is incorrect -- underflows to
592 0 if wx < sqrt(smallest nonzero double) */
593 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000594 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000595 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000596 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000597 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598}
599
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000601float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000602{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000603 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000604 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000605 CONVERT_TO_DOUBLE(v, vx);
606 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000607 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000609 return NULL;
610 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000611 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000612 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000613 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000614 exact multiple of wx. But this is fp arithmetic, and fp
615 vx - mod is an approximation; the result is that div may
616 not be an exact integral value after the division, although
617 it will always be very close to one.
618 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000619 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000620 if (mod) {
621 /* ensure the remainder has the same sign as the denominator */
622 if ((wx < 0) != (mod < 0)) {
623 mod += wx;
624 div -= 1.0;
625 }
626 }
627 else {
628 /* the remainder is zero, and in the presence of signed zeroes
629 fmod returns different results across platforms; ensure
630 it has the same sign as the denominator; we'd like to do
631 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000632 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000633 if (wx < 0.0)
634 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000635 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000636 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000637 if (div) {
638 floordiv = floor(div);
639 if (div - floordiv > 0.5)
640 floordiv += 1.0;
641 }
642 else {
643 /* div is zero - get the same sign as the true quotient */
644 div *= div; /* hide "div = +0" from optimizers */
645 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
646 }
647 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000648 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000649}
650
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000651static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000652float_floor_div(PyObject *v, PyObject *w)
653{
654 PyObject *t, *r;
655
656 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000657 if (t == NULL || t == Py_NotImplemented)
658 return t;
659 assert(PyTuple_CheckExact(t));
660 r = PyTuple_GET_ITEM(t, 0);
661 Py_INCREF(r);
662 Py_DECREF(t);
663 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000664}
665
666static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000667float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000668{
669 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000670
671 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000672 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000673 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000674 return NULL;
675 }
676
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677 CONVERT_TO_DOUBLE(v, iv);
678 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000679
680 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000681 if (iw == 0) { /* v**0 is 1, even 0**0 */
Tim Petersc54d1902000-10-06 00:36:09 +0000682 PyFPE_START_PROTECT("pow", return NULL)
683 if ((PyObject *)z != Py_None) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000684 double iz;
Neil Schemenauer010b0cc2001-01-08 06:29:50 +0000685 CONVERT_TO_DOUBLE(z, iz);
Tim Peters96685bf2001-08-23 22:31:37 +0000686 ix = fmod(1.0, iz);
687 if (ix != 0 && iz < 0)
688 ix += iz;
Guido van Rossum70d93461991-05-28 21:57:39 +0000689 }
Tim Petersc54d1902000-10-06 00:36:09 +0000690 else
691 ix = 1.0;
692 PyFPE_END_PROTECT(ix)
Tim Petersd2364e82001-11-01 20:09:42 +0000693 return PyFloat_FromDouble(ix);
Tim Petersc54d1902000-10-06 00:36:09 +0000694 }
Tim Peters96685bf2001-08-23 22:31:37 +0000695 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000696 if (iw < 0.0) {
697 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000698 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000699 return NULL;
700 }
701 return PyFloat_FromDouble(0.0);
702 }
Tim Peterse87568d2003-05-24 20:18:24 +0000703 if (iv < 0.0) {
704 /* Whether this is an error is a mess, and bumps into libm
705 * bugs so we have to figure it out ourselves.
706 */
707 if (iw != floor(iw)) {
708 PyErr_SetString(PyExc_ValueError, "negative number "
709 "cannot be raised to a fractional power");
710 return NULL;
711 }
712 /* iw is an exact integer, albeit perhaps a very large one.
713 * -1 raised to an exact integer should never be exceptional.
714 * Alas, some libms (chiefly glibc as of early 2003) return
715 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
716 * happen to be representable in a *C* integer. That's a
717 * bug; we let that slide in math.pow() (which currently
718 * reflects all platform accidents), but not for Python's **.
719 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000721 /* Return 1 if iw is even, -1 if iw is odd; there's
722 * no guarantee that any C integral type is big
723 * enough to hold iw, so we have to check this
724 * indirectly.
725 */
726 ix = floor(iw * 0.5) * 2.0;
727 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
728 }
729 /* Else iv != -1.0, and overflow or underflow are possible.
730 * Unless we're to write pow() ourselves, we have to trust
731 * the platform to do this correctly.
732 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000733 }
Tim Peters96685bf2001-08-23 22:31:37 +0000734 errno = 0;
735 PyFPE_START_PROTECT("pow", return NULL)
736 ix = pow(iv, iw);
737 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000738 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000739 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000740 /* We don't expect any errno value other than ERANGE, but
741 * the range of libm bugs appears unbounded.
742 */
743 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
744 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000745 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000746 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000748}
749
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000750static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000751float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000753 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000754}
755
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000757float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000758{
Tim Peters0280cf72001-09-11 21:53:35 +0000759 if (PyFloat_CheckExact(v)) {
760 Py_INCREF(v);
761 return (PyObject *)v;
762 }
763 else
764 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000765}
766
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000768float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000769{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000770 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771}
772
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000773static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000774float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000775{
776 return v->ob_fval != 0.0;
777}
778
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000779static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000780float_long(PyObject *v)
781{
782 double x = PyFloat_AsDouble(v);
783 return PyLong_FromDouble(x);
784}
785
786static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000787float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000788{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000790 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000791
792 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000793 /* Try to get out cheap if this fits in a Python int. The attempt
794 * to cast to long must be protected, as C doesn't define what
795 * happens if the double is too big to fit in a long. Some rare
796 * systems raise an exception then (RISCOS was mentioned as one,
797 * and someone using a non-default option on Sun also bumped into
798 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
799 * still be vulnerable: if a long has more bits of precision than
800 * a double, casting MIN/MAX to double may yield an approximation,
801 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
802 * yield true from the C expression wholepart<=LONG_MAX, despite
803 * that wholepart is actually greater than LONG_MAX.
804 */
805 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
806 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000807 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000808 }
809 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000810}
811
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000813float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000814{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000815 if (PyFloat_CheckExact(v))
816 Py_INCREF(v);
817 else
818 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000819 return v;
820}
821
822
Jeremy Hylton938ace62002-07-17 16:30:39 +0000823static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000824float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
825
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826static PyObject *
827float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
828{
829 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000830 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831
Guido van Rossumbef14172001-08-29 15:47:46 +0000832 if (type != &PyFloat_Type)
833 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
835 return NULL;
836 if (PyString_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000837 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000838 return PyNumber_Float(x);
839}
840
Guido van Rossumbef14172001-08-29 15:47:46 +0000841/* Wimpy, slow approach to tp_new calls for subtypes of float:
842 first create a regular float from whatever arguments we got,
843 then allocate a subtype instance and initialize its ob_fval
844 from the regular float. The regular float is then thrown away.
845*/
846static PyObject *
847float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
848{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000849 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000850
851 assert(PyType_IsSubtype(type, &PyFloat_Type));
852 tmp = float_new(&PyFloat_Type, args, kwds);
853 if (tmp == NULL)
854 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000855 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000856 newobj = type->tp_alloc(type, 0);
857 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000858 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000859 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000860 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000862 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000863 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000864}
865
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000866static PyObject *
867float_getnewargs(PyFloatObject *v)
868{
869 return Py_BuildValue("(d)", v->ob_fval);
870}
871
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000872/* this is for the benefit of the pack/unpack routines below */
873
874typedef enum {
875 unknown_format, ieee_big_endian_format, ieee_little_endian_format
876} float_format_type;
877
878static float_format_type double_format, float_format;
879static float_format_type detected_double_format, detected_float_format;
880
881static PyObject *
882float_getformat(PyTypeObject *v, PyObject* arg)
883{
884 char* s;
885 float_format_type r;
886
887 if (!PyString_Check(arg)) {
888 PyErr_Format(PyExc_TypeError,
889 "__getformat__() argument must be string, not %.500s",
890 arg->ob_type->tp_name);
891 return NULL;
892 }
893 s = PyString_AS_STRING(arg);
894 if (strcmp(s, "double") == 0) {
895 r = double_format;
896 }
897 else if (strcmp(s, "float") == 0) {
898 r = float_format;
899 }
900 else {
901 PyErr_SetString(PyExc_ValueError,
902 "__getformat__() argument 1 must be "
903 "'double' or 'float'");
904 return NULL;
905 }
906
907 switch (r) {
908 case unknown_format:
909 return PyString_FromString("unknown");
910 case ieee_little_endian_format:
911 return PyString_FromString("IEEE, little-endian");
912 case ieee_big_endian_format:
913 return PyString_FromString("IEEE, big-endian");
914 default:
915 Py_FatalError("insane float_format or double_format");
916 return NULL;
917 }
918}
919
920PyDoc_STRVAR(float_getformat_doc,
921"float.__getformat__(typestr) -> string\n"
922"\n"
923"You probably don't want to use this function. It exists mainly to be\n"
924"used in Python's test suite.\n"
925"\n"
926"typestr must be 'double' or 'float'. This function returns whichever of\n"
927"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
928"format of floating point numbers used by the C type named by typestr.");
929
930static PyObject *
931float_setformat(PyTypeObject *v, PyObject* args)
932{
933 char* typestr;
934 char* format;
935 float_format_type f;
936 float_format_type detected;
937 float_format_type *p;
938
939 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
940 return NULL;
941
942 if (strcmp(typestr, "double") == 0) {
943 p = &double_format;
944 detected = detected_double_format;
945 }
946 else if (strcmp(typestr, "float") == 0) {
947 p = &float_format;
948 detected = detected_float_format;
949 }
950 else {
951 PyErr_SetString(PyExc_ValueError,
952 "__setformat__() argument 1 must "
953 "be 'double' or 'float'");
954 return NULL;
955 }
956
957 if (strcmp(format, "unknown") == 0) {
958 f = unknown_format;
959 }
960 else if (strcmp(format, "IEEE, little-endian") == 0) {
961 f = ieee_little_endian_format;
962 }
963 else if (strcmp(format, "IEEE, big-endian") == 0) {
964 f = ieee_big_endian_format;
965 }
966 else {
967 PyErr_SetString(PyExc_ValueError,
968 "__setformat__() argument 2 must be "
969 "'unknown', 'IEEE, little-endian' or "
970 "'IEEE, big-endian'");
971 return NULL;
972
973 }
974
975 if (f != unknown_format && f != detected) {
976 PyErr_Format(PyExc_ValueError,
977 "can only set %s format to 'unknown' or the "
978 "detected platform value", typestr);
979 return NULL;
980 }
981
982 *p = f;
983 Py_RETURN_NONE;
984}
985
986PyDoc_STRVAR(float_setformat_doc,
987"float.__setformat__(typestr, fmt) -> None\n"
988"\n"
989"You probably don't want to use this function. It exists mainly to be\n"
990"used in Python's test suite.\n"
991"\n"
992"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
993"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
994"one of the latter two if it appears to match the underlying C reality.\n"
995"\n"
996"Overrides the automatic determination of C-level floating point type.\n"
997"This affects how floats are converted to and from binary strings.");
998
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000999static PyMethodDef float_methods[] = {
1000 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001001 {"__getformat__", (PyCFunction)float_getformat,
1002 METH_O|METH_CLASS, float_getformat_doc},
1003 {"__setformat__", (PyCFunction)float_setformat,
1004 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001005 {NULL, NULL} /* sentinel */
1006};
1007
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001008PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009"float(x) -> floating point number\n\
1010\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001011Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012
1013
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001014static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001015 float_add, /*nb_add*/
1016 float_sub, /*nb_subtract*/
1017 float_mul, /*nb_multiply*/
1018 float_rem, /*nb_remainder*/
1019 float_divmod, /*nb_divmod*/
1020 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001021 (unaryfunc)float_neg, /*nb_negative*/
1022 (unaryfunc)float_pos, /*nb_positive*/
1023 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001024 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001025 0, /*nb_invert*/
1026 0, /*nb_lshift*/
1027 0, /*nb_rshift*/
1028 0, /*nb_and*/
1029 0, /*nb_xor*/
1030 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001031 (coercion)0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001032 float_int, /*nb_int*/
1033 float_long, /*nb_long*/
1034 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001035 0, /* nb_oct */
1036 0, /* nb_hex */
1037 0, /* nb_inplace_add */
1038 0, /* nb_inplace_subtract */
1039 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001040 0, /* nb_inplace_remainder */
1041 0, /* nb_inplace_power */
1042 0, /* nb_inplace_lshift */
1043 0, /* nb_inplace_rshift */
1044 0, /* nb_inplace_and */
1045 0, /* nb_inplace_xor */
1046 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001047 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001048 float_div, /* nb_true_divide */
1049 0, /* nb_inplace_floor_divide */
1050 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001051};
1052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053PyTypeObject PyFloat_Type = {
1054 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001055 0,
1056 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001057 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001058 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059 (destructor)float_dealloc, /* tp_dealloc */
1060 (printfunc)float_print, /* tp_print */
1061 0, /* tp_getattr */
1062 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001063 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 (reprfunc)float_repr, /* tp_repr */
1065 &float_as_number, /* tp_as_number */
1066 0, /* tp_as_sequence */
1067 0, /* tp_as_mapping */
1068 (hashfunc)float_hash, /* tp_hash */
1069 0, /* tp_call */
1070 (reprfunc)float_str, /* tp_str */
1071 PyObject_GenericGetAttr, /* tp_getattro */
1072 0, /* tp_setattro */
1073 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001074 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 float_doc, /* tp_doc */
1076 0, /* tp_traverse */
1077 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 0, /* tp_weaklistoffset */
1080 0, /* tp_iter */
1081 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001082 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 0, /* tp_members */
1084 0, /* tp_getset */
1085 0, /* tp_base */
1086 0, /* tp_dict */
1087 0, /* tp_descr_get */
1088 0, /* tp_descr_set */
1089 0, /* tp_dictoffset */
1090 0, /* tp_init */
1091 0, /* tp_alloc */
1092 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001093};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001094
1095void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001096_PyFloat_Init(void)
1097{
1098 /* We attempt to determine if this machine is using IEEE
1099 floating point formats by peering at the bits of some
1100 carefully chosen values. If it looks like we are on an
1101 IEEE platform, the float packing/unpacking routines can
1102 just copy bits, if not they resort to arithmetic & shifts
1103 and masks. The shifts & masks approach works on all finite
1104 values, but what happens to infinities, NaNs and signed
1105 zeroes on packing is an accident, and attempting to unpack
1106 a NaN or an infinity will raise an exception.
1107
1108 Note that if we're on some whacked-out platform which uses
1109 IEEE formats but isn't strictly little-endian or big-
1110 endian, we will fall back to the portable shifts & masks
1111 method. */
1112
1113#if SIZEOF_DOUBLE == 8
1114 {
1115 double x = 9006104071832581.0;
1116 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1117 detected_double_format = ieee_big_endian_format;
1118 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1119 detected_double_format = ieee_little_endian_format;
1120 else
1121 detected_double_format = unknown_format;
1122 }
1123#else
1124 detected_double_format = unknown_format;
1125#endif
1126
1127#if SIZEOF_FLOAT == 4
1128 {
1129 float y = 16711938.0;
1130 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1131 detected_float_format = ieee_big_endian_format;
1132 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1133 detected_float_format = ieee_little_endian_format;
1134 else
1135 detected_float_format = unknown_format;
1136 }
1137#else
1138 detected_float_format = unknown_format;
1139#endif
1140
1141 double_format = detected_double_format;
1142 float_format = detected_float_format;
1143}
1144
1145void
Fred Drakefd99de62000-07-09 05:02:18 +00001146PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001147{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001148 PyFloatObject *p;
1149 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001150 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001151 int bc, bf; /* block count, number of freed blocks */
1152 int frem, fsum; /* remaining unfreed floats per block, total */
1153
1154 bc = 0;
1155 bf = 0;
1156 fsum = 0;
1157 list = block_list;
1158 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001159 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001160 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001161 bc++;
1162 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001163 for (i = 0, p = &list->objects[0];
1164 i < N_FLOATOBJECTS;
1165 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001166 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001167 frem++;
1168 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001169 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001170 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001171 list->next = block_list;
1172 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001173 for (i = 0, p = &list->objects[0];
1174 i < N_FLOATOBJECTS;
1175 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001176 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +00001177 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001178 p->ob_type = (struct _typeobject *)
1179 free_list;
1180 free_list = p;
1181 }
1182 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001183 }
1184 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001185 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001186 bf++;
1187 }
1188 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001189 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001190 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001191 if (!Py_VerboseFlag)
1192 return;
1193 fprintf(stderr, "# cleanup floats");
1194 if (!fsum) {
1195 fprintf(stderr, "\n");
1196 }
1197 else {
1198 fprintf(stderr,
1199 ": %d unfreed float%s in %d out of %d block%s\n",
1200 fsum, fsum == 1 ? "" : "s",
1201 bc - bf, bc, bc == 1 ? "" : "s");
1202 }
1203 if (Py_VerboseFlag > 1) {
1204 list = block_list;
1205 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001206 for (i = 0, p = &list->objects[0];
1207 i < N_FLOATOBJECTS;
1208 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001209 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +00001210 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001211 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001212 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001213 /* XXX(twouters) cast refcount to
1214 long until %zd is universally
1215 available
1216 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001217 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001218 "# <float at %p, refcnt=%ld, val=%s>\n",
1219 p, (long)p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001220 }
1221 }
1222 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001223 }
1224 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001225}
Tim Peters9905b942003-03-20 20:53:32 +00001226
1227/*----------------------------------------------------------------------------
1228 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1229 *
1230 * TODO: On platforms that use the standard IEEE-754 single and double
1231 * formats natively, these routines could simply copy the bytes.
1232 */
1233int
1234_PyFloat_Pack4(double x, unsigned char *p, int le)
1235{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001236 if (float_format == unknown_format) {
1237 unsigned char sign;
1238 int e;
1239 double f;
1240 unsigned int fbits;
1241 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001242
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001243 if (le) {
1244 p += 3;
1245 incr = -1;
1246 }
Tim Peters9905b942003-03-20 20:53:32 +00001247
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001248 if (x < 0) {
1249 sign = 1;
1250 x = -x;
1251 }
1252 else
1253 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001254
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001255 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001256
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001257 /* Normalize f to be in the range [1.0, 2.0) */
1258 if (0.5 <= f && f < 1.0) {
1259 f *= 2.0;
1260 e--;
1261 }
1262 else if (f == 0.0)
1263 e = 0;
1264 else {
1265 PyErr_SetString(PyExc_SystemError,
1266 "frexp() result out of range");
1267 return -1;
1268 }
1269
1270 if (e >= 128)
1271 goto Overflow;
1272 else if (e < -126) {
1273 /* Gradual underflow */
1274 f = ldexp(f, 126 + e);
1275 e = 0;
1276 }
1277 else if (!(e == 0 && f == 0.0)) {
1278 e += 127;
1279 f -= 1.0; /* Get rid of leading 1 */
1280 }
1281
1282 f *= 8388608.0; /* 2**23 */
1283 fbits = (unsigned int)(f + 0.5); /* Round */
1284 assert(fbits <= 8388608);
1285 if (fbits >> 23) {
1286 /* The carry propagated out of a string of 23 1 bits. */
1287 fbits = 0;
1288 ++e;
1289 if (e >= 255)
1290 goto Overflow;
1291 }
1292
1293 /* First byte */
1294 *p = (sign << 7) | (e >> 1);
1295 p += incr;
1296
1297 /* Second byte */
1298 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1299 p += incr;
1300
1301 /* Third byte */
1302 *p = (fbits >> 8) & 0xFF;
1303 p += incr;
1304
1305 /* Fourth byte */
1306 *p = fbits & 0xFF;
1307
1308 /* Done */
1309 return 0;
1310
1311 Overflow:
1312 PyErr_SetString(PyExc_OverflowError,
1313 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001314 return -1;
1315 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001316 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001317 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001318 const char *s = (char*)&y;
1319 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001320
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001321 if ((float_format == ieee_little_endian_format && !le)
1322 || (float_format == ieee_big_endian_format && le)) {
1323 p += 3;
1324 incr = -1;
1325 }
1326
1327 for (i = 0; i < 4; i++) {
1328 *p = *s++;
1329 p += incr;
1330 }
1331 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001332 }
Tim Peters9905b942003-03-20 20:53:32 +00001333}
1334
1335int
1336_PyFloat_Pack8(double x, unsigned char *p, int le)
1337{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001338 if (double_format == unknown_format) {
1339 unsigned char sign;
1340 int e;
1341 double f;
1342 unsigned int fhi, flo;
1343 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001344
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001345 if (le) {
1346 p += 7;
1347 incr = -1;
1348 }
Tim Peters9905b942003-03-20 20:53:32 +00001349
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001350 if (x < 0) {
1351 sign = 1;
1352 x = -x;
1353 }
1354 else
1355 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001356
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001357 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001358
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001359 /* Normalize f to be in the range [1.0, 2.0) */
1360 if (0.5 <= f && f < 1.0) {
1361 f *= 2.0;
1362 e--;
1363 }
1364 else if (f == 0.0)
1365 e = 0;
1366 else {
1367 PyErr_SetString(PyExc_SystemError,
1368 "frexp() result out of range");
1369 return -1;
1370 }
1371
1372 if (e >= 1024)
1373 goto Overflow;
1374 else if (e < -1022) {
1375 /* Gradual underflow */
1376 f = ldexp(f, 1022 + e);
1377 e = 0;
1378 }
1379 else if (!(e == 0 && f == 0.0)) {
1380 e += 1023;
1381 f -= 1.0; /* Get rid of leading 1 */
1382 }
1383
1384 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1385 f *= 268435456.0; /* 2**28 */
1386 fhi = (unsigned int)f; /* Truncate */
1387 assert(fhi < 268435456);
1388
1389 f -= (double)fhi;
1390 f *= 16777216.0; /* 2**24 */
1391 flo = (unsigned int)(f + 0.5); /* Round */
1392 assert(flo <= 16777216);
1393 if (flo >> 24) {
1394 /* The carry propagated out of a string of 24 1 bits. */
1395 flo = 0;
1396 ++fhi;
1397 if (fhi >> 28) {
1398 /* And it also progagated out of the next 28 bits. */
1399 fhi = 0;
1400 ++e;
1401 if (e >= 2047)
1402 goto Overflow;
1403 }
1404 }
1405
1406 /* First byte */
1407 *p = (sign << 7) | (e >> 4);
1408 p += incr;
1409
1410 /* Second byte */
1411 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1412 p += incr;
1413
1414 /* Third byte */
1415 *p = (fhi >> 16) & 0xFF;
1416 p += incr;
1417
1418 /* Fourth byte */
1419 *p = (fhi >> 8) & 0xFF;
1420 p += incr;
1421
1422 /* Fifth byte */
1423 *p = fhi & 0xFF;
1424 p += incr;
1425
1426 /* Sixth byte */
1427 *p = (flo >> 16) & 0xFF;
1428 p += incr;
1429
1430 /* Seventh byte */
1431 *p = (flo >> 8) & 0xFF;
1432 p += incr;
1433
1434 /* Eighth byte */
1435 *p = flo & 0xFF;
1436 p += incr;
1437
1438 /* Done */
1439 return 0;
1440
1441 Overflow:
1442 PyErr_SetString(PyExc_OverflowError,
1443 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001444 return -1;
1445 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001446 else {
1447 const char *s = (char*)&x;
1448 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001449
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001450 if ((double_format == ieee_little_endian_format && !le)
1451 || (double_format == ieee_big_endian_format && le)) {
1452 p += 7;
1453 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001454 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001455
1456 for (i = 0; i < 8; i++) {
1457 *p = *s++;
1458 p += incr;
1459 }
1460 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001461 }
Tim Peters9905b942003-03-20 20:53:32 +00001462}
1463
Neal Norwitz545686b2006-12-28 04:45:06 +00001464/* Should only be used by marshal. */
1465int
1466_PyFloat_Repr(double x, char *p, size_t len)
1467{
1468 format_double(p, len, x, PREC_REPR);
1469 return (int)strlen(p);
1470}
1471
Tim Peters9905b942003-03-20 20:53:32 +00001472double
1473_PyFloat_Unpack4(const unsigned char *p, int le)
1474{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001475 if (float_format == unknown_format) {
1476 unsigned char sign;
1477 int e;
1478 unsigned int f;
1479 double x;
1480 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001481
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001482 if (le) {
1483 p += 3;
1484 incr = -1;
1485 }
1486
1487 /* First byte */
1488 sign = (*p >> 7) & 1;
1489 e = (*p & 0x7F) << 1;
1490 p += incr;
1491
1492 /* Second byte */
1493 e |= (*p >> 7) & 1;
1494 f = (*p & 0x7F) << 16;
1495 p += incr;
1496
1497 if (e == 255) {
1498 PyErr_SetString(
1499 PyExc_ValueError,
1500 "can't unpack IEEE 754 special value "
1501 "on non-IEEE platform");
1502 return -1;
1503 }
1504
1505 /* Third byte */
1506 f |= *p << 8;
1507 p += incr;
1508
1509 /* Fourth byte */
1510 f |= *p;
1511
1512 x = (double)f / 8388608.0;
1513
1514 /* XXX This sadly ignores Inf/NaN issues */
1515 if (e == 0)
1516 e = -126;
1517 else {
1518 x += 1.0;
1519 e -= 127;
1520 }
1521 x = ldexp(x, e);
1522
1523 if (sign)
1524 x = -x;
1525
1526 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001527 }
Tim Peters9905b942003-03-20 20:53:32 +00001528 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001529 float x;
1530
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001531 if ((float_format == ieee_little_endian_format && !le)
1532 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001533 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001534 char *d = &buf[3];
1535 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001536
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001537 for (i = 0; i < 4; i++) {
1538 *d-- = *p++;
1539 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001540 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001541 }
1542 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001543 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001544 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001545
1546 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001547 }
Tim Peters9905b942003-03-20 20:53:32 +00001548}
1549
1550double
1551_PyFloat_Unpack8(const unsigned char *p, int le)
1552{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001553 if (double_format == unknown_format) {
1554 unsigned char sign;
1555 int e;
1556 unsigned int fhi, flo;
1557 double x;
1558 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001559
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001560 if (le) {
1561 p += 7;
1562 incr = -1;
1563 }
1564
1565 /* First byte */
1566 sign = (*p >> 7) & 1;
1567 e = (*p & 0x7F) << 4;
1568
1569 p += incr;
1570
1571 /* Second byte */
1572 e |= (*p >> 4) & 0xF;
1573 fhi = (*p & 0xF) << 24;
1574 p += incr;
1575
1576 if (e == 2047) {
1577 PyErr_SetString(
1578 PyExc_ValueError,
1579 "can't unpack IEEE 754 special value "
1580 "on non-IEEE platform");
1581 return -1.0;
1582 }
1583
1584 /* Third byte */
1585 fhi |= *p << 16;
1586 p += incr;
1587
1588 /* Fourth byte */
1589 fhi |= *p << 8;
1590 p += incr;
1591
1592 /* Fifth byte */
1593 fhi |= *p;
1594 p += incr;
1595
1596 /* Sixth byte */
1597 flo = *p << 16;
1598 p += incr;
1599
1600 /* Seventh byte */
1601 flo |= *p << 8;
1602 p += incr;
1603
1604 /* Eighth byte */
1605 flo |= *p;
1606
1607 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1608 x /= 268435456.0; /* 2**28 */
1609
1610 if (e == 0)
1611 e = -1022;
1612 else {
1613 x += 1.0;
1614 e -= 1023;
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 double x;
1625
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001626 if ((double_format == ieee_little_endian_format && !le)
1627 || (double_format == ieee_big_endian_format && le)) {
1628 char buf[8];
1629 char *d = &buf[7];
1630 int i;
1631
1632 for (i = 0; i < 8; i++) {
1633 *d-- = *p++;
1634 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001635 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001636 }
1637 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001638 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001639 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001640
1641 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001642 }
Tim Peters9905b942003-03-20 20:53:32 +00001643}