blob: b5fb9cfc55b0d669ade7576239522e77202df22a [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 */
71 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +000072 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000073
Guido van Rossum4c08d552000-03-10 22:55:18 +000074 if (PyString_Check(v)) {
75 s = PyString_AS_STRING(v);
76 len = PyString_GET_SIZE(v);
77 }
Guido van Rossum9e896b32000-04-05 20:11:21 +000078 else if (PyUnicode_Check(v)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +000080 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +000081 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +000082 return NULL;
83 }
Tim Petersef14d732000-09-23 03:39:17 +000084 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +000085 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +000086 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +000087 NULL))
88 return NULL;
89 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +000090 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +000091 }
Guido van Rossum4c08d552000-03-10 22:55:18 +000092 else if (PyObject_AsCharBuffer(v, &s, &len)) {
93 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +000094 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +000095 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +000096 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +000097
Guido van Rossum4c08d552000-03-10 22:55:18 +000098 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000099 while (*s && isspace(Py_CHARMASK(*s)))
100 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000101 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000102 PyErr_SetString(PyExc_ValueError, "empty string for float()");
103 return NULL;
104 }
Tim Petersef14d732000-09-23 03:39:17 +0000105 /* We don't care about overflow or underflow. If the platform supports
106 * them, infinities and signed zeroes (on underflow) are fine.
107 * However, strtod can return 0 for denormalized numbers, where atof
108 * does not. So (alas!) we special-case a zero result. Note that
109 * whether strtod sets errno on underflow is not defined, so we can't
110 * key off errno.
111 */
Tim Peters858346e2000-09-25 21:01:28 +0000112 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000113 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000114 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000115 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000116 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000117 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000118 if (end > last)
119 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000120 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000121 PyOS_snprintf(buffer, sizeof(buffer),
122 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000123 PyErr_SetString(PyExc_ValueError, buffer);
124 return NULL;
125 }
126 /* Since end != s, the platform made *some* kind of sense out
127 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000128 while (*end && isspace(Py_CHARMASK(*end)))
129 end++;
130 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000131 PyOS_snprintf(buffer, sizeof(buffer),
132 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000133 PyErr_SetString(PyExc_ValueError, buffer);
134 return NULL;
135 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000136 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000137 PyErr_SetString(PyExc_ValueError,
138 "null byte in argument for float()");
139 return NULL;
140 }
Tim Petersef14d732000-09-23 03:39:17 +0000141 if (x == 0.0) {
142 /* See above -- may have been strtod being anal
143 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000144 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000145 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000146 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000147 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000148 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000149 return PyFloat_FromDouble(x);
150}
151
Guido van Rossum234f9421993-06-17 12:35:49 +0000152static void
Fred Drakefd99de62000-07-09 05:02:18 +0000153float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000154{
Guido van Rossum9475a232001-10-05 20:51:39 +0000155 if (PyFloat_CheckExact(op)) {
156 op->ob_type = (struct _typeobject *)free_list;
157 free_list = op;
158 }
159 else
160 op->ob_type->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000161}
162
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163double
Fred Drakefd99de62000-07-09 05:02:18 +0000164PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000166 PyNumberMethods *nb;
167 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000168 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000169
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 if (op && PyFloat_Check(op))
171 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000172
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000173 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175 return -1;
176 }
Tim Petersd2364e82001-11-01 20:09:42 +0000177
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000178 if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) {
179 PyErr_SetString(PyExc_TypeError, "a float is required");
180 return -1;
181 }
182
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000184 if (fo == NULL)
185 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 if (!PyFloat_Check(fo)) {
187 PyErr_SetString(PyExc_TypeError,
188 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000189 return -1;
190 }
Tim Petersd2364e82001-11-01 20:09:42 +0000191
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 val = PyFloat_AS_DOUBLE(fo);
193 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000194
Guido van Rossumb6775db1994-08-01 11:34:53 +0000195 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196}
197
198/* Methods */
199
Tim Peters97019e42001-11-28 22:43:45 +0000200static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000201format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202{
203 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000204 char format[32];
Neal Norwitz545686b2006-12-28 04:45:06 +0000205 /* Subroutine for float_repr, float_str, float_print and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206 We want float numbers to be recognizable as such,
207 i.e., they should contain a decimal point or an exponent.
208 However, %g may print the number as an integer;
209 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000210
Martin v. Löwis737ea822004-06-08 18:52:54 +0000211 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000212 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213 cp = buf;
214 if (*cp == '-')
215 cp++;
216 for (; *cp != '\0'; cp++) {
217 /* Any non-digit means it's not an integer;
218 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000219 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000220 break;
221 }
222 if (*cp == '\0') {
223 *cp++ = '.';
224 *cp++ = '0';
225 *cp++ = '\0';
226 }
227}
228
Neal Norwitz545686b2006-12-28 04:45:06 +0000229static void
230format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000231{
Neal Norwitz545686b2006-12-28 04:45:06 +0000232 assert(PyFloat_Check(v));
233 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000234}
235
Neil Schemenauer32117e52001-01-04 01:44:34 +0000236/* Macro and helper that convert PyObject obj to a C double and store
237 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000238 slot function. If conversion to double raises an exception, obj is
239 set to NULL, and the function invoking this macro returns NULL. If
240 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
241 stored in obj, and returned from the function invoking this macro.
242*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000243#define CONVERT_TO_DOUBLE(obj, dbl) \
244 if (PyFloat_Check(obj)) \
245 dbl = PyFloat_AS_DOUBLE(obj); \
246 else if (convert_to_double(&(obj), &(dbl)) < 0) \
247 return obj;
248
249static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000250convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000251{
252 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000253
Guido van Rossumddefaf32007-01-14 03:31:43 +0000254 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000255 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000256 if (*dbl == -1.0 && PyErr_Occurred()) {
257 *v = NULL;
258 return -1;
259 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000260 }
261 else {
262 Py_INCREF(Py_NotImplemented);
263 *v = Py_NotImplemented;
264 return -1;
265 }
266 return 0;
267}
268
Guido van Rossum57072eb1999-12-23 19:00:28 +0000269/* Precisions used by repr() and str(), respectively.
270
271 The repr() precision (17 significant decimal digits) is the minimal number
272 that is guaranteed to have enough precision so that if the number is read
273 back in the exact same binary value is recreated. This is true for IEEE
274 floating point by design, and also happens to work for all other modern
275 hardware.
276
277 The str() precision is chosen so that in most cases, the rounding noise
278 created by various operations is suppressed, while giving plenty of
279 precision for practical use.
280
281*/
282
283#define PREC_REPR 17
284#define PREC_STR 12
285
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000286/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000287static int
Fred Drakefd99de62000-07-09 05:02:18 +0000288float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289{
290 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000291 format_float(buf, sizeof(buf), v,
292 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000294 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000295}
296
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000297static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000298float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299{
300 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000301 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000302 return PyString_FromString(buf);
303}
304
305static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000306float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000307{
308 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000309 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000310 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311}
312
Tim Peters307fa782004-09-23 08:06:40 +0000313/* Comparison is pretty much a nightmare. When comparing float to float,
314 * we do it as straightforwardly (and long-windedly) as conceivable, so
315 * that, e.g., Python x == y delivers the same result as the platform
316 * C x == y when x and/or y is a NaN.
317 * When mixing float with an integer type, there's no good *uniform* approach.
318 * Converting the double to an integer obviously doesn't work, since we
319 * may lose info from fractional bits. Converting the integer to a double
320 * also has two failure modes: (1) a long int may trigger overflow (too
321 * large to fit in the dynamic range of a C double); (2) even a C long may have
322 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
323 * 63 bits of precision, but a C double probably has only 53), and then
324 * we can falsely claim equality when low-order integer bits are lost by
325 * coercion to double. So this part is painful too.
326 */
327
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000328static PyObject*
329float_richcompare(PyObject *v, PyObject *w, int op)
330{
331 double i, j;
332 int r = 0;
333
Tim Peters307fa782004-09-23 08:06:40 +0000334 assert(PyFloat_Check(v));
335 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000336
Tim Peters307fa782004-09-23 08:06:40 +0000337 /* Switch on the type of w. Set i and j to doubles to be compared,
338 * and op to the richcomp to use.
339 */
340 if (PyFloat_Check(w))
341 j = PyFloat_AS_DOUBLE(w);
342
Thomas Wouters477c8d52006-05-27 19:21:47 +0000343 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000344 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000345 /* If i is an infinity, its magnitude exceeds any
346 * finite integer, so it doesn't matter which int we
347 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000348 */
349 j = 0.0;
350 else
351 goto Unimplemented;
352 }
353
Tim Peters307fa782004-09-23 08:06:40 +0000354 else if (PyLong_Check(w)) {
355 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
356 int wsign = _PyLong_Sign(w);
357 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000358 int exponent;
359
360 if (vsign != wsign) {
361 /* Magnitudes are irrelevant -- the signs alone
362 * determine the outcome.
363 */
364 i = (double)vsign;
365 j = (double)wsign;
366 goto Compare;
367 }
368 /* The signs are the same. */
369 /* Convert w to a double if it fits. In particular, 0 fits. */
370 nbits = _PyLong_NumBits(w);
371 if (nbits == (size_t)-1 && PyErr_Occurred()) {
372 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000373 * to hold the # of bits. Replace with little doubles
374 * that give the same outcome -- w is so large that
375 * its magnitude must exceed the magnitude of any
376 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000377 */
378 PyErr_Clear();
379 i = (double)vsign;
380 assert(wsign != 0);
381 j = wsign * 2.0;
382 goto Compare;
383 }
384 if (nbits <= 48) {
385 j = PyLong_AsDouble(w);
386 /* It's impossible that <= 48 bits overflowed. */
387 assert(j != -1.0 || ! PyErr_Occurred());
388 goto Compare;
389 }
390 assert(wsign != 0); /* else nbits was 0 */
391 assert(vsign != 0); /* if vsign were 0, then since wsign is
392 * not 0, we would have taken the
393 * vsign != wsign branch at the start */
394 /* We want to work with non-negative numbers. */
395 if (vsign < 0) {
396 /* "Multiply both sides" by -1; this also swaps the
397 * comparator.
398 */
399 i = -i;
400 op = _Py_SwappedOp[op];
401 }
402 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000403 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000404 /* exponent is the # of bits in v before the radix point;
405 * we know that nbits (the # of bits in w) > 48 at this point
406 */
407 if (exponent < 0 || (size_t)exponent < nbits) {
408 i = 1.0;
409 j = 2.0;
410 goto Compare;
411 }
412 if ((size_t)exponent > nbits) {
413 i = 2.0;
414 j = 1.0;
415 goto Compare;
416 }
417 /* v and w have the same number of bits before the radix
418 * point. Construct two longs that have the same comparison
419 * outcome.
420 */
421 {
422 double fracpart;
423 double intpart;
424 PyObject *result = NULL;
425 PyObject *one = NULL;
426 PyObject *vv = NULL;
427 PyObject *ww = w;
428
429 if (wsign < 0) {
430 ww = PyNumber_Negative(w);
431 if (ww == NULL)
432 goto Error;
433 }
434 else
435 Py_INCREF(ww);
436
437 fracpart = modf(i, &intpart);
438 vv = PyLong_FromDouble(intpart);
439 if (vv == NULL)
440 goto Error;
441
442 if (fracpart != 0.0) {
443 /* Shift left, and or a 1 bit into vv
444 * to represent the lost fraction.
445 */
446 PyObject *temp;
447
448 one = PyInt_FromLong(1);
449 if (one == NULL)
450 goto Error;
451
452 temp = PyNumber_Lshift(ww, one);
453 if (temp == NULL)
454 goto Error;
455 Py_DECREF(ww);
456 ww = temp;
457
458 temp = PyNumber_Lshift(vv, one);
459 if (temp == NULL)
460 goto Error;
461 Py_DECREF(vv);
462 vv = temp;
463
464 temp = PyNumber_Or(vv, one);
465 if (temp == NULL)
466 goto Error;
467 Py_DECREF(vv);
468 vv = temp;
469 }
470
471 r = PyObject_RichCompareBool(vv, ww, op);
472 if (r < 0)
473 goto Error;
474 result = PyBool_FromLong(r);
475 Error:
476 Py_XDECREF(vv);
477 Py_XDECREF(ww);
478 Py_XDECREF(one);
479 return result;
480 }
481 } /* else if (PyLong_Check(w)) */
482
483 else /* w isn't float, int, or long */
484 goto Unimplemented;
485
486 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000487 PyFPE_START_PROTECT("richcompare", return NULL)
488 switch (op) {
489 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000490 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000491 break;
492 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000493 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000494 break;
495 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000496 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000497 break;
498 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000499 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000500 break;
501 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000502 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000503 break;
504 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000505 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000506 break;
507 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000508 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000509 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000510
511 Unimplemented:
512 Py_INCREF(Py_NotImplemented);
513 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000514}
515
Guido van Rossum9bfef441993-03-29 10:43:31 +0000516static long
Fred Drakefd99de62000-07-09 05:02:18 +0000517float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000518{
Tim Peters39dce292000-08-15 03:34:48 +0000519 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000520}
521
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000523float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000525 double a,b;
526 CONVERT_TO_DOUBLE(v, a);
527 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000528 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529 a = a + b;
530 PyFPE_END_PROTECT(a)
531 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532}
533
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000535float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000536{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537 double a,b;
538 CONVERT_TO_DOUBLE(v, a);
539 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000540 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541 a = a - b;
542 PyFPE_END_PROTECT(a)
543 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544}
545
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000547float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000549 double a,b;
550 CONVERT_TO_DOUBLE(v, a);
551 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000552 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553 a = a * b;
554 PyFPE_END_PROTECT(a)
555 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556}
557
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000559float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561 double a,b;
562 CONVERT_TO_DOUBLE(v, a);
563 CONVERT_TO_DOUBLE(w, b);
564 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566 return NULL;
567 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000568 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000569 a = a / b;
570 PyFPE_END_PROTECT(a)
571 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000572}
573
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000575float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000576{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000577 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000578 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000579 CONVERT_TO_DOUBLE(v, vx);
580 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583 return NULL;
584 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000585 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000586 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000587 /* note: checking mod*wx < 0 is incorrect -- underflows to
588 0 if wx < sqrt(smallest nonzero double) */
589 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000590 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000591 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000592 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594}
595
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000597float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000598{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000599 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000600 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000601 CONVERT_TO_DOUBLE(v, vx);
602 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000603 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000605 return NULL;
606 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000607 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000608 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000609 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000610 exact multiple of wx. But this is fp arithmetic, and fp
611 vx - mod is an approximation; the result is that div may
612 not be an exact integral value after the division, although
613 it will always be very close to one.
614 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000615 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000616 if (mod) {
617 /* ensure the remainder has the same sign as the denominator */
618 if ((wx < 0) != (mod < 0)) {
619 mod += wx;
620 div -= 1.0;
621 }
622 }
623 else {
624 /* the remainder is zero, and in the presence of signed zeroes
625 fmod returns different results across platforms; ensure
626 it has the same sign as the denominator; we'd like to do
627 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000628 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000629 if (wx < 0.0)
630 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000631 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000632 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000633 if (div) {
634 floordiv = floor(div);
635 if (div - floordiv > 0.5)
636 floordiv += 1.0;
637 }
638 else {
639 /* div is zero - get the same sign as the true quotient */
640 div *= div; /* hide "div = +0" from optimizers */
641 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
642 }
643 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000644 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000645}
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000648float_floor_div(PyObject *v, PyObject *w)
649{
650 PyObject *t, *r;
651
652 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000653 if (t == NULL || t == Py_NotImplemented)
654 return t;
655 assert(PyTuple_CheckExact(t));
656 r = PyTuple_GET_ITEM(t, 0);
657 Py_INCREF(r);
658 Py_DECREF(t);
659 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000660}
661
662static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000663float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664{
665 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000666
667 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000668 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000669 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000670 return NULL;
671 }
672
Neil Schemenauer32117e52001-01-04 01:44:34 +0000673 CONVERT_TO_DOUBLE(v, iv);
674 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000675
676 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000677 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000678 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000679 }
Tim Peters96685bf2001-08-23 22:31:37 +0000680 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000681 if (iw < 0.0) {
682 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000683 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000684 return NULL;
685 }
686 return PyFloat_FromDouble(0.0);
687 }
Tim Peterse87568d2003-05-24 20:18:24 +0000688 if (iv < 0.0) {
689 /* Whether this is an error is a mess, and bumps into libm
690 * bugs so we have to figure it out ourselves.
691 */
692 if (iw != floor(iw)) {
693 PyErr_SetString(PyExc_ValueError, "negative number "
694 "cannot be raised to a fractional power");
695 return NULL;
696 }
697 /* iw is an exact integer, albeit perhaps a very large one.
698 * -1 raised to an exact integer should never be exceptional.
699 * Alas, some libms (chiefly glibc as of early 2003) return
700 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
701 * happen to be representable in a *C* integer. That's a
702 * bug; we let that slide in math.pow() (which currently
703 * reflects all platform accidents), but not for Python's **.
704 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000705 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000706 /* Return 1 if iw is even, -1 if iw is odd; there's
707 * no guarantee that any C integral type is big
708 * enough to hold iw, so we have to check this
709 * indirectly.
710 */
711 ix = floor(iw * 0.5) * 2.0;
712 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
713 }
714 /* Else iv != -1.0, and overflow or underflow are possible.
715 * Unless we're to write pow() ourselves, we have to trust
716 * the platform to do this correctly.
717 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000718 }
Tim Peters96685bf2001-08-23 22:31:37 +0000719 errno = 0;
720 PyFPE_START_PROTECT("pow", return NULL)
721 ix = pow(iv, iw);
722 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000723 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000724 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000725 /* We don't expect any errno value other than ERANGE, but
726 * the range of libm bugs appears unbounded.
727 */
728 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
729 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000731 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733}
734
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000736float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000739}
740
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000742float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000743{
Tim Peters0280cf72001-09-11 21:53:35 +0000744 if (PyFloat_CheckExact(v)) {
745 Py_INCREF(v);
746 return (PyObject *)v;
747 }
748 else
749 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000750}
751
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000753float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000754{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000755 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756}
757
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000758static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000759float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000760{
761 return v->ob_fval != 0.0;
762}
763
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000765float_long(PyObject *v)
766{
767 double x = PyFloat_AsDouble(v);
768 return PyLong_FromDouble(x);
769}
770
771static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000772float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000773{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000774 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000775 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000776
777 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000778 /* Try to get out cheap if this fits in a Python int. The attempt
779 * to cast to long must be protected, as C doesn't define what
780 * happens if the double is too big to fit in a long. Some rare
781 * systems raise an exception then (RISCOS was mentioned as one,
782 * and someone using a non-default option on Sun also bumped into
783 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
784 * still be vulnerable: if a long has more bits of precision than
785 * a double, casting MIN/MAX to double may yield an approximation,
786 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
787 * yield true from the C expression wholepart<=LONG_MAX, despite
788 * that wholepart is actually greater than LONG_MAX.
789 */
790 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
791 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000792 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000793 }
794 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000795}
796
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000798float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000799{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000800 if (PyFloat_CheckExact(v))
801 Py_INCREF(v);
802 else
803 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000804 return v;
805}
806
807
Jeremy Hylton938ace62002-07-17 16:30:39 +0000808static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000809float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
810
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811static PyObject *
812float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
813{
814 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000815 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816
Guido van Rossumbef14172001-08-29 15:47:46 +0000817 if (type != &PyFloat_Type)
818 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
820 return NULL;
821 if (PyString_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000822 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823 return PyNumber_Float(x);
824}
825
Guido van Rossumbef14172001-08-29 15:47:46 +0000826/* Wimpy, slow approach to tp_new calls for subtypes of float:
827 first create a regular float from whatever arguments we got,
828 then allocate a subtype instance and initialize its ob_fval
829 from the regular float. The regular float is then thrown away.
830*/
831static PyObject *
832float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
833{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000834 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000835
836 assert(PyType_IsSubtype(type, &PyFloat_Type));
837 tmp = float_new(&PyFloat_Type, args, kwds);
838 if (tmp == NULL)
839 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000840 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841 newobj = type->tp_alloc(type, 0);
842 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000843 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000844 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000845 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000847 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000849}
850
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000851static PyObject *
852float_getnewargs(PyFloatObject *v)
853{
854 return Py_BuildValue("(d)", v->ob_fval);
855}
856
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000857/* this is for the benefit of the pack/unpack routines below */
858
859typedef enum {
860 unknown_format, ieee_big_endian_format, ieee_little_endian_format
861} float_format_type;
862
863static float_format_type double_format, float_format;
864static float_format_type detected_double_format, detected_float_format;
865
866static PyObject *
867float_getformat(PyTypeObject *v, PyObject* arg)
868{
869 char* s;
870 float_format_type r;
871
872 if (!PyString_Check(arg)) {
873 PyErr_Format(PyExc_TypeError,
874 "__getformat__() argument must be string, not %.500s",
875 arg->ob_type->tp_name);
876 return NULL;
877 }
878 s = PyString_AS_STRING(arg);
879 if (strcmp(s, "double") == 0) {
880 r = double_format;
881 }
882 else if (strcmp(s, "float") == 0) {
883 r = float_format;
884 }
885 else {
886 PyErr_SetString(PyExc_ValueError,
887 "__getformat__() argument 1 must be "
888 "'double' or 'float'");
889 return NULL;
890 }
891
892 switch (r) {
893 case unknown_format:
894 return PyString_FromString("unknown");
895 case ieee_little_endian_format:
896 return PyString_FromString("IEEE, little-endian");
897 case ieee_big_endian_format:
898 return PyString_FromString("IEEE, big-endian");
899 default:
900 Py_FatalError("insane float_format or double_format");
901 return NULL;
902 }
903}
904
905PyDoc_STRVAR(float_getformat_doc,
906"float.__getformat__(typestr) -> string\n"
907"\n"
908"You probably don't want to use this function. It exists mainly to be\n"
909"used in Python's test suite.\n"
910"\n"
911"typestr must be 'double' or 'float'. This function returns whichever of\n"
912"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
913"format of floating point numbers used by the C type named by typestr.");
914
915static PyObject *
916float_setformat(PyTypeObject *v, PyObject* args)
917{
918 char* typestr;
919 char* format;
920 float_format_type f;
921 float_format_type detected;
922 float_format_type *p;
923
924 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
925 return NULL;
926
927 if (strcmp(typestr, "double") == 0) {
928 p = &double_format;
929 detected = detected_double_format;
930 }
931 else if (strcmp(typestr, "float") == 0) {
932 p = &float_format;
933 detected = detected_float_format;
934 }
935 else {
936 PyErr_SetString(PyExc_ValueError,
937 "__setformat__() argument 1 must "
938 "be 'double' or 'float'");
939 return NULL;
940 }
941
942 if (strcmp(format, "unknown") == 0) {
943 f = unknown_format;
944 }
945 else if (strcmp(format, "IEEE, little-endian") == 0) {
946 f = ieee_little_endian_format;
947 }
948 else if (strcmp(format, "IEEE, big-endian") == 0) {
949 f = ieee_big_endian_format;
950 }
951 else {
952 PyErr_SetString(PyExc_ValueError,
953 "__setformat__() argument 2 must be "
954 "'unknown', 'IEEE, little-endian' or "
955 "'IEEE, big-endian'");
956 return NULL;
957
958 }
959
960 if (f != unknown_format && f != detected) {
961 PyErr_Format(PyExc_ValueError,
962 "can only set %s format to 'unknown' or the "
963 "detected platform value", typestr);
964 return NULL;
965 }
966
967 *p = f;
968 Py_RETURN_NONE;
969}
970
971PyDoc_STRVAR(float_setformat_doc,
972"float.__setformat__(typestr, fmt) -> None\n"
973"\n"
974"You probably don't want to use this function. It exists mainly to be\n"
975"used in Python's test suite.\n"
976"\n"
977"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
978"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
979"one of the latter two if it appears to match the underlying C reality.\n"
980"\n"
981"Overrides the automatic determination of C-level floating point type.\n"
982"This affects how floats are converted to and from binary strings.");
983
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000984static PyMethodDef float_methods[] = {
985 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000986 {"__getformat__", (PyCFunction)float_getformat,
987 METH_O|METH_CLASS, float_getformat_doc},
988 {"__setformat__", (PyCFunction)float_setformat,
989 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000990 {NULL, NULL} /* sentinel */
991};
992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000993PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000994"float(x) -> floating point number\n\
995\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000996Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997
998
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000999static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001000 float_add, /*nb_add*/
1001 float_sub, /*nb_subtract*/
1002 float_mul, /*nb_multiply*/
1003 float_rem, /*nb_remainder*/
1004 float_divmod, /*nb_divmod*/
1005 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001006 (unaryfunc)float_neg, /*nb_negative*/
1007 (unaryfunc)float_pos, /*nb_positive*/
1008 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001009 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001010 0, /*nb_invert*/
1011 0, /*nb_lshift*/
1012 0, /*nb_rshift*/
1013 0, /*nb_and*/
1014 0, /*nb_xor*/
1015 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001016 (coercion)0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001017 float_int, /*nb_int*/
1018 float_long, /*nb_long*/
1019 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001020 0, /* nb_oct */
1021 0, /* nb_hex */
1022 0, /* nb_inplace_add */
1023 0, /* nb_inplace_subtract */
1024 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001025 0, /* nb_inplace_remainder */
1026 0, /* nb_inplace_power */
1027 0, /* nb_inplace_lshift */
1028 0, /* nb_inplace_rshift */
1029 0, /* nb_inplace_and */
1030 0, /* nb_inplace_xor */
1031 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001032 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001033 float_div, /* nb_true_divide */
1034 0, /* nb_inplace_floor_divide */
1035 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001036};
1037
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038PyTypeObject PyFloat_Type = {
1039 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001040 0,
1041 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001042 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001043 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044 (destructor)float_dealloc, /* tp_dealloc */
1045 (printfunc)float_print, /* tp_print */
1046 0, /* tp_getattr */
1047 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001048 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049 (reprfunc)float_repr, /* tp_repr */
1050 &float_as_number, /* tp_as_number */
1051 0, /* tp_as_sequence */
1052 0, /* tp_as_mapping */
1053 (hashfunc)float_hash, /* tp_hash */
1054 0, /* tp_call */
1055 (reprfunc)float_str, /* tp_str */
1056 PyObject_GenericGetAttr, /* tp_getattro */
1057 0, /* tp_setattro */
1058 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001059 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001060 float_doc, /* tp_doc */
1061 0, /* tp_traverse */
1062 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001063 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 0, /* tp_weaklistoffset */
1065 0, /* tp_iter */
1066 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001067 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001068 0, /* tp_members */
1069 0, /* tp_getset */
1070 0, /* tp_base */
1071 0, /* tp_dict */
1072 0, /* tp_descr_get */
1073 0, /* tp_descr_set */
1074 0, /* tp_dictoffset */
1075 0, /* tp_init */
1076 0, /* tp_alloc */
1077 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001078};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001079
1080void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001081_PyFloat_Init(void)
1082{
1083 /* We attempt to determine if this machine is using IEEE
1084 floating point formats by peering at the bits of some
1085 carefully chosen values. If it looks like we are on an
1086 IEEE platform, the float packing/unpacking routines can
1087 just copy bits, if not they resort to arithmetic & shifts
1088 and masks. The shifts & masks approach works on all finite
1089 values, but what happens to infinities, NaNs and signed
1090 zeroes on packing is an accident, and attempting to unpack
1091 a NaN or an infinity will raise an exception.
1092
1093 Note that if we're on some whacked-out platform which uses
1094 IEEE formats but isn't strictly little-endian or big-
1095 endian, we will fall back to the portable shifts & masks
1096 method. */
1097
1098#if SIZEOF_DOUBLE == 8
1099 {
1100 double x = 9006104071832581.0;
1101 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1102 detected_double_format = ieee_big_endian_format;
1103 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1104 detected_double_format = ieee_little_endian_format;
1105 else
1106 detected_double_format = unknown_format;
1107 }
1108#else
1109 detected_double_format = unknown_format;
1110#endif
1111
1112#if SIZEOF_FLOAT == 4
1113 {
1114 float y = 16711938.0;
1115 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1116 detected_float_format = ieee_big_endian_format;
1117 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1118 detected_float_format = ieee_little_endian_format;
1119 else
1120 detected_float_format = unknown_format;
1121 }
1122#else
1123 detected_float_format = unknown_format;
1124#endif
1125
1126 double_format = detected_double_format;
1127 float_format = detected_float_format;
1128}
1129
1130void
Fred Drakefd99de62000-07-09 05:02:18 +00001131PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001132{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001133 PyFloatObject *p;
1134 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001135 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001136 int bc, bf; /* block count, number of freed blocks */
1137 int frem, fsum; /* remaining unfreed floats per block, total */
1138
1139 bc = 0;
1140 bf = 0;
1141 fsum = 0;
1142 list = block_list;
1143 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001144 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001145 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001146 bc++;
1147 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001148 for (i = 0, p = &list->objects[0];
1149 i < N_FLOATOBJECTS;
1150 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001151 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001152 frem++;
1153 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001154 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001155 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001156 list->next = block_list;
1157 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001158 for (i = 0, p = &list->objects[0];
1159 i < N_FLOATOBJECTS;
1160 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001161 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +00001162 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001163 p->ob_type = (struct _typeobject *)
1164 free_list;
1165 free_list = p;
1166 }
1167 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001168 }
1169 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001170 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001171 bf++;
1172 }
1173 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001174 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001175 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001176 if (!Py_VerboseFlag)
1177 return;
1178 fprintf(stderr, "# cleanup floats");
1179 if (!fsum) {
1180 fprintf(stderr, "\n");
1181 }
1182 else {
1183 fprintf(stderr,
1184 ": %d unfreed float%s in %d out of %d block%s\n",
1185 fsum, fsum == 1 ? "" : "s",
1186 bc - bf, bc, bc == 1 ? "" : "s");
1187 }
1188 if (Py_VerboseFlag > 1) {
1189 list = block_list;
1190 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001191 for (i = 0, p = &list->objects[0];
1192 i < N_FLOATOBJECTS;
1193 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001194 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +00001195 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001196 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001197 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001198 /* XXX(twouters) cast refcount to
1199 long until %zd is universally
1200 available
1201 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001202 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001203 "# <float at %p, refcnt=%ld, val=%s>\n",
1204 p, (long)p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001205 }
1206 }
1207 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001208 }
1209 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001210}
Tim Peters9905b942003-03-20 20:53:32 +00001211
1212/*----------------------------------------------------------------------------
1213 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1214 *
1215 * TODO: On platforms that use the standard IEEE-754 single and double
1216 * formats natively, these routines could simply copy the bytes.
1217 */
1218int
1219_PyFloat_Pack4(double x, unsigned char *p, int le)
1220{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001221 if (float_format == unknown_format) {
1222 unsigned char sign;
1223 int e;
1224 double f;
1225 unsigned int fbits;
1226 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001227
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001228 if (le) {
1229 p += 3;
1230 incr = -1;
1231 }
Tim Peters9905b942003-03-20 20:53:32 +00001232
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001233 if (x < 0) {
1234 sign = 1;
1235 x = -x;
1236 }
1237 else
1238 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001239
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001240 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001241
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001242 /* Normalize f to be in the range [1.0, 2.0) */
1243 if (0.5 <= f && f < 1.0) {
1244 f *= 2.0;
1245 e--;
1246 }
1247 else if (f == 0.0)
1248 e = 0;
1249 else {
1250 PyErr_SetString(PyExc_SystemError,
1251 "frexp() result out of range");
1252 return -1;
1253 }
1254
1255 if (e >= 128)
1256 goto Overflow;
1257 else if (e < -126) {
1258 /* Gradual underflow */
1259 f = ldexp(f, 126 + e);
1260 e = 0;
1261 }
1262 else if (!(e == 0 && f == 0.0)) {
1263 e += 127;
1264 f -= 1.0; /* Get rid of leading 1 */
1265 }
1266
1267 f *= 8388608.0; /* 2**23 */
1268 fbits = (unsigned int)(f + 0.5); /* Round */
1269 assert(fbits <= 8388608);
1270 if (fbits >> 23) {
1271 /* The carry propagated out of a string of 23 1 bits. */
1272 fbits = 0;
1273 ++e;
1274 if (e >= 255)
1275 goto Overflow;
1276 }
1277
1278 /* First byte */
1279 *p = (sign << 7) | (e >> 1);
1280 p += incr;
1281
1282 /* Second byte */
1283 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1284 p += incr;
1285
1286 /* Third byte */
1287 *p = (fbits >> 8) & 0xFF;
1288 p += incr;
1289
1290 /* Fourth byte */
1291 *p = fbits & 0xFF;
1292
1293 /* Done */
1294 return 0;
1295
1296 Overflow:
1297 PyErr_SetString(PyExc_OverflowError,
1298 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001299 return -1;
1300 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001301 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001302 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001303 const char *s = (char*)&y;
1304 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001305
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001306 if ((float_format == ieee_little_endian_format && !le)
1307 || (float_format == ieee_big_endian_format && le)) {
1308 p += 3;
1309 incr = -1;
1310 }
1311
1312 for (i = 0; i < 4; i++) {
1313 *p = *s++;
1314 p += incr;
1315 }
1316 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001317 }
Tim Peters9905b942003-03-20 20:53:32 +00001318}
1319
1320int
1321_PyFloat_Pack8(double x, unsigned char *p, int le)
1322{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001323 if (double_format == unknown_format) {
1324 unsigned char sign;
1325 int e;
1326 double f;
1327 unsigned int fhi, flo;
1328 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001329
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001330 if (le) {
1331 p += 7;
1332 incr = -1;
1333 }
Tim Peters9905b942003-03-20 20:53:32 +00001334
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001335 if (x < 0) {
1336 sign = 1;
1337 x = -x;
1338 }
1339 else
1340 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001341
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001342 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001343
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001344 /* Normalize f to be in the range [1.0, 2.0) */
1345 if (0.5 <= f && f < 1.0) {
1346 f *= 2.0;
1347 e--;
1348 }
1349 else if (f == 0.0)
1350 e = 0;
1351 else {
1352 PyErr_SetString(PyExc_SystemError,
1353 "frexp() result out of range");
1354 return -1;
1355 }
1356
1357 if (e >= 1024)
1358 goto Overflow;
1359 else if (e < -1022) {
1360 /* Gradual underflow */
1361 f = ldexp(f, 1022 + e);
1362 e = 0;
1363 }
1364 else if (!(e == 0 && f == 0.0)) {
1365 e += 1023;
1366 f -= 1.0; /* Get rid of leading 1 */
1367 }
1368
1369 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1370 f *= 268435456.0; /* 2**28 */
1371 fhi = (unsigned int)f; /* Truncate */
1372 assert(fhi < 268435456);
1373
1374 f -= (double)fhi;
1375 f *= 16777216.0; /* 2**24 */
1376 flo = (unsigned int)(f + 0.5); /* Round */
1377 assert(flo <= 16777216);
1378 if (flo >> 24) {
1379 /* The carry propagated out of a string of 24 1 bits. */
1380 flo = 0;
1381 ++fhi;
1382 if (fhi >> 28) {
1383 /* And it also progagated out of the next 28 bits. */
1384 fhi = 0;
1385 ++e;
1386 if (e >= 2047)
1387 goto Overflow;
1388 }
1389 }
1390
1391 /* First byte */
1392 *p = (sign << 7) | (e >> 4);
1393 p += incr;
1394
1395 /* Second byte */
1396 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1397 p += incr;
1398
1399 /* Third byte */
1400 *p = (fhi >> 16) & 0xFF;
1401 p += incr;
1402
1403 /* Fourth byte */
1404 *p = (fhi >> 8) & 0xFF;
1405 p += incr;
1406
1407 /* Fifth byte */
1408 *p = fhi & 0xFF;
1409 p += incr;
1410
1411 /* Sixth byte */
1412 *p = (flo >> 16) & 0xFF;
1413 p += incr;
1414
1415 /* Seventh byte */
1416 *p = (flo >> 8) & 0xFF;
1417 p += incr;
1418
1419 /* Eighth byte */
1420 *p = flo & 0xFF;
1421 p += incr;
1422
1423 /* Done */
1424 return 0;
1425
1426 Overflow:
1427 PyErr_SetString(PyExc_OverflowError,
1428 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001429 return -1;
1430 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001431 else {
1432 const char *s = (char*)&x;
1433 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001434
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001435 if ((double_format == ieee_little_endian_format && !le)
1436 || (double_format == ieee_big_endian_format && le)) {
1437 p += 7;
1438 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001439 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001440
1441 for (i = 0; i < 8; i++) {
1442 *p = *s++;
1443 p += incr;
1444 }
1445 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001446 }
Tim Peters9905b942003-03-20 20:53:32 +00001447}
1448
Neal Norwitz545686b2006-12-28 04:45:06 +00001449/* Should only be used by marshal. */
1450int
1451_PyFloat_Repr(double x, char *p, size_t len)
1452{
1453 format_double(p, len, x, PREC_REPR);
1454 return (int)strlen(p);
1455}
1456
Tim Peters9905b942003-03-20 20:53:32 +00001457double
1458_PyFloat_Unpack4(const unsigned char *p, int le)
1459{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001460 if (float_format == unknown_format) {
1461 unsigned char sign;
1462 int e;
1463 unsigned int f;
1464 double x;
1465 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001466
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001467 if (le) {
1468 p += 3;
1469 incr = -1;
1470 }
1471
1472 /* First byte */
1473 sign = (*p >> 7) & 1;
1474 e = (*p & 0x7F) << 1;
1475 p += incr;
1476
1477 /* Second byte */
1478 e |= (*p >> 7) & 1;
1479 f = (*p & 0x7F) << 16;
1480 p += incr;
1481
1482 if (e == 255) {
1483 PyErr_SetString(
1484 PyExc_ValueError,
1485 "can't unpack IEEE 754 special value "
1486 "on non-IEEE platform");
1487 return -1;
1488 }
1489
1490 /* Third byte */
1491 f |= *p << 8;
1492 p += incr;
1493
1494 /* Fourth byte */
1495 f |= *p;
1496
1497 x = (double)f / 8388608.0;
1498
1499 /* XXX This sadly ignores Inf/NaN issues */
1500 if (e == 0)
1501 e = -126;
1502 else {
1503 x += 1.0;
1504 e -= 127;
1505 }
1506 x = ldexp(x, e);
1507
1508 if (sign)
1509 x = -x;
1510
1511 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001512 }
Tim Peters9905b942003-03-20 20:53:32 +00001513 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001514 float x;
1515
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001516 if ((float_format == ieee_little_endian_format && !le)
1517 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001518 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001519 char *d = &buf[3];
1520 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001521
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001522 for (i = 0; i < 4; i++) {
1523 *d-- = *p++;
1524 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001525 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001526 }
1527 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001528 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001529 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001530
1531 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001532 }
Tim Peters9905b942003-03-20 20:53:32 +00001533}
1534
1535double
1536_PyFloat_Unpack8(const unsigned char *p, int le)
1537{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001538 if (double_format == unknown_format) {
1539 unsigned char sign;
1540 int e;
1541 unsigned int fhi, flo;
1542 double x;
1543 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001544
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001545 if (le) {
1546 p += 7;
1547 incr = -1;
1548 }
1549
1550 /* First byte */
1551 sign = (*p >> 7) & 1;
1552 e = (*p & 0x7F) << 4;
1553
1554 p += incr;
1555
1556 /* Second byte */
1557 e |= (*p >> 4) & 0xF;
1558 fhi = (*p & 0xF) << 24;
1559 p += incr;
1560
1561 if (e == 2047) {
1562 PyErr_SetString(
1563 PyExc_ValueError,
1564 "can't unpack IEEE 754 special value "
1565 "on non-IEEE platform");
1566 return -1.0;
1567 }
1568
1569 /* Third byte */
1570 fhi |= *p << 16;
1571 p += incr;
1572
1573 /* Fourth byte */
1574 fhi |= *p << 8;
1575 p += incr;
1576
1577 /* Fifth byte */
1578 fhi |= *p;
1579 p += incr;
1580
1581 /* Sixth byte */
1582 flo = *p << 16;
1583 p += incr;
1584
1585 /* Seventh byte */
1586 flo |= *p << 8;
1587 p += incr;
1588
1589 /* Eighth byte */
1590 flo |= *p;
1591
1592 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1593 x /= 268435456.0; /* 2**28 */
1594
1595 if (e == 0)
1596 e = -1022;
1597 else {
1598 x += 1.0;
1599 e -= 1023;
1600 }
1601 x = ldexp(x, e);
1602
1603 if (sign)
1604 x = -x;
1605
1606 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001607 }
Tim Peters9905b942003-03-20 20:53:32 +00001608 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001609 double x;
1610
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001611 if ((double_format == ieee_little_endian_format && !le)
1612 || (double_format == ieee_big_endian_format && le)) {
1613 char buf[8];
1614 char *d = &buf[7];
1615 int i;
1616
1617 for (i = 0; i < 8; i++) {
1618 *d-- = *p++;
1619 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001620 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621 }
1622 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001623 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001625
1626 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001627 }
Tim Peters9905b942003-03-20 20:53:32 +00001628}