blob: f2f53bab362ce86adca8040339321331458bd7a5 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Jack Janseneddc1442003-11-20 01:44:59 +000011#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000012extern double fmod(double, double);
13extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000014#endif
15
Guido van Rossum93ad0df1997-05-13 21:00:42 +000016/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000017#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000018#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000019#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000020
Guido van Rossum3fce8831999-03-12 19:43:17 +000021struct _floatblock {
22 struct _floatblock *next;
23 PyFloatObject objects[N_FLOATOBJECTS];
24};
25
26typedef struct _floatblock PyFloatBlock;
27
28static PyFloatBlock *block_list = NULL;
29static PyFloatObject *free_list = NULL;
30
Guido van Rossum93ad0df1997-05-13 21:00:42 +000031static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000032fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000033{
34 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000035 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
36 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000037 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000038 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000039 ((PyFloatBlock *)p)->next = block_list;
40 block_list = (PyFloatBlock *)p;
41 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042 q = p + N_FLOATOBJECTS;
43 while (--q > p)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000044 Py_Type(q) = (struct _typeobject *)(q-1);
45 Py_Type(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046 return p + N_FLOATOBJECTS - 1;
47}
48
Guido van Rossumc0b618a1997-05-02 03:12:38 +000049PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000050PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051{
Guido van Rossum93ad0df1997-05-13 21:00:42 +000052 register PyFloatObject *op;
53 if (free_list == NULL) {
54 if ((free_list = fill_free_list()) == NULL)
55 return NULL;
56 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +000057 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 op = free_list;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000059 free_list = (PyFloatObject *)Py_Type(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +000060 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +000061 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063}
64
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 */
Guido van Rossum2be161d2007-05-15 20:43:51 +000071 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +000072 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +000073 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000074
Guido van Rossum4c08d552000-03-10 22:55:18 +000075 if (PyString_Check(v)) {
76 s = PyString_AS_STRING(v);
77 len = PyString_GET_SIZE(v);
78 }
Guido van Rossum9e896b32000-04-05 20:11:21 +000079 else if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +000080 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
81 if (s_buffer == NULL)
82 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +000083 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +000084 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +000085 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +000086 NULL))
87 return NULL;
88 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +000089 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +000090 }
Guido van Rossum4c08d552000-03-10 22:55:18 +000091 else if (PyObject_AsCharBuffer(v, &s, &len)) {
92 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +000093 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +000094 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +000095 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +000096
Guido van Rossum4c08d552000-03-10 22:55:18 +000097 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000098 while (*s && isspace(Py_CHARMASK(*s)))
99 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000100 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000101 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000102 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000103 }
Tim Petersef14d732000-09-23 03:39:17 +0000104 /* We don't care about overflow or underflow. If the platform supports
105 * them, infinities and signed zeroes (on underflow) are fine.
106 * However, strtod can return 0 for denormalized numbers, where atof
107 * does not. So (alas!) we special-case a zero result. Note that
108 * whether strtod sets errno on underflow is not defined, so we can't
109 * key off errno.
110 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000111 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000112 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000113 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000114 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000115 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000116 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000117 if (end > last)
118 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000119 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000120 PyOS_snprintf(buffer, sizeof(buffer),
121 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000122 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000123 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000124 }
125 /* Since end != s, the platform made *some* kind of sense out
126 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000127 while (*end && isspace(Py_CHARMASK(*end)))
128 end++;
129 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000130 PyOS_snprintf(buffer, sizeof(buffer),
131 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000132 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000133 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000134 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000135 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000136 PyErr_SetString(PyExc_ValueError,
137 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000138 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000139 }
Tim Petersef14d732000-09-23 03:39:17 +0000140 if (x == 0.0) {
141 /* See above -- may have been strtod being anal
142 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000143 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000144 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000145 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000146 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000147 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000148 result = PyFloat_FromDouble(x);
149 error:
150 if (s_buffer)
151 PyMem_FREE(s_buffer);
152 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000153}
154
Guido van Rossum234f9421993-06-17 12:35:49 +0000155static void
Fred Drakefd99de62000-07-09 05:02:18 +0000156float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000157{
Guido van Rossum9475a232001-10-05 20:51:39 +0000158 if (PyFloat_CheckExact(op)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000159 Py_Type(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000160 free_list = op;
161 }
162 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000163 Py_Type(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000164}
165
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166double
Fred Drakefd99de62000-07-09 05:02:18 +0000167PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 PyNumberMethods *nb;
170 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000171 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 if (op && PyFloat_Check(op))
174 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000175
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000176 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000177 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178 return -1;
179 }
Tim Petersd2364e82001-11-01 20:09:42 +0000180
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000181 if ((nb = Py_Type(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000182 PyErr_SetString(PyExc_TypeError, "a float is required");
183 return -1;
184 }
185
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000187 if (fo == NULL)
188 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000189 if (!PyFloat_Check(fo)) {
190 PyErr_SetString(PyExc_TypeError,
191 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000192 return -1;
193 }
Tim Petersd2364e82001-11-01 20:09:42 +0000194
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 val = PyFloat_AS_DOUBLE(fo);
196 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000197
Guido van Rossumb6775db1994-08-01 11:34:53 +0000198 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199}
200
201/* Methods */
202
Tim Peters97019e42001-11-28 22:43:45 +0000203static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000204format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000205{
206 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000207 char format[32];
Neal Norwitz545686b2006-12-28 04:45:06 +0000208 /* Subroutine for float_repr, float_str, float_print and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209 We want float numbers to be recognizable as such,
210 i.e., they should contain a decimal point or an exponent.
211 However, %g may print the number as an integer;
212 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000213
Martin v. Löwis737ea822004-06-08 18:52:54 +0000214 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000215 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216 cp = buf;
217 if (*cp == '-')
218 cp++;
219 for (; *cp != '\0'; cp++) {
220 /* Any non-digit means it's not an integer;
221 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000222 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223 break;
224 }
225 if (*cp == '\0') {
226 *cp++ = '.';
227 *cp++ = '0';
228 *cp++ = '\0';
229 }
230}
231
Neal Norwitz545686b2006-12-28 04:45:06 +0000232static void
233format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000234{
Neal Norwitz545686b2006-12-28 04:45:06 +0000235 assert(PyFloat_Check(v));
236 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000237}
238
Neil Schemenauer32117e52001-01-04 01:44:34 +0000239/* Macro and helper that convert PyObject obj to a C double and store
240 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000241 slot function. If conversion to double raises an exception, obj is
242 set to NULL, and the function invoking this macro returns NULL. If
243 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
244 stored in obj, and returned from the function invoking this macro.
245*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000246#define CONVERT_TO_DOUBLE(obj, dbl) \
247 if (PyFloat_Check(obj)) \
248 dbl = PyFloat_AS_DOUBLE(obj); \
249 else if (convert_to_double(&(obj), &(dbl)) < 0) \
250 return obj;
251
252static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000253convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000254{
255 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000256
Guido van Rossumddefaf32007-01-14 03:31:43 +0000257 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000258 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000259 if (*dbl == -1.0 && PyErr_Occurred()) {
260 *v = NULL;
261 return -1;
262 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000263 }
264 else {
265 Py_INCREF(Py_NotImplemented);
266 *v = Py_NotImplemented;
267 return -1;
268 }
269 return 0;
270}
271
Guido van Rossum57072eb1999-12-23 19:00:28 +0000272/* Precisions used by repr() and str(), respectively.
273
274 The repr() precision (17 significant decimal digits) is the minimal number
275 that is guaranteed to have enough precision so that if the number is read
276 back in the exact same binary value is recreated. This is true for IEEE
277 floating point by design, and also happens to work for all other modern
278 hardware.
279
280 The str() precision is chosen so that in most cases, the rounding noise
281 created by various operations is suppressed, while giving plenty of
282 precision for practical use.
283
284*/
285
286#define PREC_REPR 17
287#define PREC_STR 12
288
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000289/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000290static int
Fred Drakefd99de62000-07-09 05:02:18 +0000291float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292{
293 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000294 format_float(buf, sizeof(buf), v,
295 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000297 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298}
299
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000301float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000302{
303 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000304 format_float(buf, sizeof(buf), v, PREC_REPR);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000305 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000306}
307
308static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000309float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000310{
311 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000312 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000313 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314}
315
Tim Peters307fa782004-09-23 08:06:40 +0000316/* Comparison is pretty much a nightmare. When comparing float to float,
317 * we do it as straightforwardly (and long-windedly) as conceivable, so
318 * that, e.g., Python x == y delivers the same result as the platform
319 * C x == y when x and/or y is a NaN.
320 * When mixing float with an integer type, there's no good *uniform* approach.
321 * Converting the double to an integer obviously doesn't work, since we
322 * may lose info from fractional bits. Converting the integer to a double
323 * also has two failure modes: (1) a long int may trigger overflow (too
324 * large to fit in the dynamic range of a C double); (2) even a C long may have
325 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
326 * 63 bits of precision, but a C double probably has only 53), and then
327 * we can falsely claim equality when low-order integer bits are lost by
328 * coercion to double. So this part is painful too.
329 */
330
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000331static PyObject*
332float_richcompare(PyObject *v, PyObject *w, int op)
333{
334 double i, j;
335 int r = 0;
336
Tim Peters307fa782004-09-23 08:06:40 +0000337 assert(PyFloat_Check(v));
338 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000339
Tim Peters307fa782004-09-23 08:06:40 +0000340 /* Switch on the type of w. Set i and j to doubles to be compared,
341 * and op to the richcomp to use.
342 */
343 if (PyFloat_Check(w))
344 j = PyFloat_AS_DOUBLE(w);
345
Thomas Wouters477c8d52006-05-27 19:21:47 +0000346 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000347 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000348 /* If i is an infinity, its magnitude exceeds any
349 * finite integer, so it doesn't matter which int we
350 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000351 */
352 j = 0.0;
353 else
354 goto Unimplemented;
355 }
356
Tim Peters307fa782004-09-23 08:06:40 +0000357 else if (PyLong_Check(w)) {
358 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
359 int wsign = _PyLong_Sign(w);
360 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000361 int exponent;
362
363 if (vsign != wsign) {
364 /* Magnitudes are irrelevant -- the signs alone
365 * determine the outcome.
366 */
367 i = (double)vsign;
368 j = (double)wsign;
369 goto Compare;
370 }
371 /* The signs are the same. */
372 /* Convert w to a double if it fits. In particular, 0 fits. */
373 nbits = _PyLong_NumBits(w);
374 if (nbits == (size_t)-1 && PyErr_Occurred()) {
375 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000376 * to hold the # of bits. Replace with little doubles
377 * that give the same outcome -- w is so large that
378 * its magnitude must exceed the magnitude of any
379 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000380 */
381 PyErr_Clear();
382 i = (double)vsign;
383 assert(wsign != 0);
384 j = wsign * 2.0;
385 goto Compare;
386 }
387 if (nbits <= 48) {
388 j = PyLong_AsDouble(w);
389 /* It's impossible that <= 48 bits overflowed. */
390 assert(j != -1.0 || ! PyErr_Occurred());
391 goto Compare;
392 }
393 assert(wsign != 0); /* else nbits was 0 */
394 assert(vsign != 0); /* if vsign were 0, then since wsign is
395 * not 0, we would have taken the
396 * vsign != wsign branch at the start */
397 /* We want to work with non-negative numbers. */
398 if (vsign < 0) {
399 /* "Multiply both sides" by -1; this also swaps the
400 * comparator.
401 */
402 i = -i;
403 op = _Py_SwappedOp[op];
404 }
405 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000406 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000407 /* exponent is the # of bits in v before the radix point;
408 * we know that nbits (the # of bits in w) > 48 at this point
409 */
410 if (exponent < 0 || (size_t)exponent < nbits) {
411 i = 1.0;
412 j = 2.0;
413 goto Compare;
414 }
415 if ((size_t)exponent > nbits) {
416 i = 2.0;
417 j = 1.0;
418 goto Compare;
419 }
420 /* v and w have the same number of bits before the radix
421 * point. Construct two longs that have the same comparison
422 * outcome.
423 */
424 {
425 double fracpart;
426 double intpart;
427 PyObject *result = NULL;
428 PyObject *one = NULL;
429 PyObject *vv = NULL;
430 PyObject *ww = w;
431
432 if (wsign < 0) {
433 ww = PyNumber_Negative(w);
434 if (ww == NULL)
435 goto Error;
436 }
437 else
438 Py_INCREF(ww);
439
440 fracpart = modf(i, &intpart);
441 vv = PyLong_FromDouble(intpart);
442 if (vv == NULL)
443 goto Error;
444
445 if (fracpart != 0.0) {
446 /* Shift left, and or a 1 bit into vv
447 * to represent the lost fraction.
448 */
449 PyObject *temp;
450
451 one = PyInt_FromLong(1);
452 if (one == NULL)
453 goto Error;
454
455 temp = PyNumber_Lshift(ww, one);
456 if (temp == NULL)
457 goto Error;
458 Py_DECREF(ww);
459 ww = temp;
460
461 temp = PyNumber_Lshift(vv, one);
462 if (temp == NULL)
463 goto Error;
464 Py_DECREF(vv);
465 vv = temp;
466
467 temp = PyNumber_Or(vv, one);
468 if (temp == NULL)
469 goto Error;
470 Py_DECREF(vv);
471 vv = temp;
472 }
473
474 r = PyObject_RichCompareBool(vv, ww, op);
475 if (r < 0)
476 goto Error;
477 result = PyBool_FromLong(r);
478 Error:
479 Py_XDECREF(vv);
480 Py_XDECREF(ww);
481 Py_XDECREF(one);
482 return result;
483 }
484 } /* else if (PyLong_Check(w)) */
485
486 else /* w isn't float, int, or long */
487 goto Unimplemented;
488
489 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000490 PyFPE_START_PROTECT("richcompare", return NULL)
491 switch (op) {
492 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000493 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000494 break;
495 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000496 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000497 break;
498 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000499 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000500 break;
501 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000502 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000503 break;
504 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000505 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000506 break;
507 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000508 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000509 break;
510 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000511 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000512 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000513
514 Unimplemented:
515 Py_INCREF(Py_NotImplemented);
516 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000517}
518
Guido van Rossum9bfef441993-03-29 10:43:31 +0000519static long
Fred Drakefd99de62000-07-09 05:02:18 +0000520float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000521{
Tim Peters39dce292000-08-15 03:34:48 +0000522 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000523}
524
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000525static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000526float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000527{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000528 double a,b;
529 CONVERT_TO_DOUBLE(v, a);
530 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000531 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000532 a = a + b;
533 PyFPE_END_PROTECT(a)
534 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535}
536
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000538float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000539{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000540 double a,b;
541 CONVERT_TO_DOUBLE(v, a);
542 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000543 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000544 a = a - b;
545 PyFPE_END_PROTECT(a)
546 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547}
548
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000550float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000551{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000552 double a,b;
553 CONVERT_TO_DOUBLE(v, a);
554 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000555 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000556 a = a * b;
557 PyFPE_END_PROTECT(a)
558 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000559}
560
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000562float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000564 double a,b;
565 CONVERT_TO_DOUBLE(v, a);
566 CONVERT_TO_DOUBLE(w, b);
567 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000568 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569 return NULL;
570 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000571 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572 a = a / b;
573 PyFPE_END_PROTECT(a)
574 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575}
576
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000578float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000579{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000580 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000581 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000582 CONVERT_TO_DOUBLE(v, vx);
583 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586 return NULL;
587 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000588 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000589 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000590 /* note: checking mod*wx < 0 is incorrect -- underflows to
591 0 if wx < sqrt(smallest nonzero double) */
592 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000593 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000594 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000595 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597}
598
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000599static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000600float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000601{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000602 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000603 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000604 CONVERT_TO_DOUBLE(v, vx);
605 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000606 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000608 return NULL;
609 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000610 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000611 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000612 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000613 exact multiple of wx. But this is fp arithmetic, and fp
614 vx - mod is an approximation; the result is that div may
615 not be an exact integral value after the division, although
616 it will always be very close to one.
617 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000618 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000619 if (mod) {
620 /* ensure the remainder has the same sign as the denominator */
621 if ((wx < 0) != (mod < 0)) {
622 mod += wx;
623 div -= 1.0;
624 }
625 }
626 else {
627 /* the remainder is zero, and in the presence of signed zeroes
628 fmod returns different results across platforms; ensure
629 it has the same sign as the denominator; we'd like to do
630 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000631 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000632 if (wx < 0.0)
633 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000634 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000635 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000636 if (div) {
637 floordiv = floor(div);
638 if (div - floordiv > 0.5)
639 floordiv += 1.0;
640 }
641 else {
642 /* div is zero - get the same sign as the true quotient */
643 div *= div; /* hide "div = +0" from optimizers */
644 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
645 }
646 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000647 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000648}
649
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000651float_floor_div(PyObject *v, PyObject *w)
652{
653 PyObject *t, *r;
654
655 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000656 if (t == NULL || t == Py_NotImplemented)
657 return t;
658 assert(PyTuple_CheckExact(t));
659 r = PyTuple_GET_ITEM(t, 0);
660 Py_INCREF(r);
661 Py_DECREF(t);
662 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000663}
664
665static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000666float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667{
668 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000669
670 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000671 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000672 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000673 return NULL;
674 }
675
Neil Schemenauer32117e52001-01-04 01:44:34 +0000676 CONVERT_TO_DOUBLE(v, iv);
677 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000678
679 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000680 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000681 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000682 }
Tim Peters96685bf2001-08-23 22:31:37 +0000683 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000684 if (iw < 0.0) {
685 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000686 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000687 return NULL;
688 }
689 return PyFloat_FromDouble(0.0);
690 }
Tim Peterse87568d2003-05-24 20:18:24 +0000691 if (iv < 0.0) {
692 /* Whether this is an error is a mess, and bumps into libm
693 * bugs so we have to figure it out ourselves.
694 */
695 if (iw != floor(iw)) {
696 PyErr_SetString(PyExc_ValueError, "negative number "
697 "cannot be raised to a fractional power");
698 return NULL;
699 }
700 /* iw is an exact integer, albeit perhaps a very large one.
701 * -1 raised to an exact integer should never be exceptional.
702 * Alas, some libms (chiefly glibc as of early 2003) return
703 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
704 * happen to be representable in a *C* integer. That's a
705 * bug; we let that slide in math.pow() (which currently
706 * reflects all platform accidents), but not for Python's **.
707 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000709 /* Return 1 if iw is even, -1 if iw is odd; there's
710 * no guarantee that any C integral type is big
711 * enough to hold iw, so we have to check this
712 * indirectly.
713 */
714 ix = floor(iw * 0.5) * 2.0;
715 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
716 }
717 /* Else iv != -1.0, and overflow or underflow are possible.
718 * Unless we're to write pow() ourselves, we have to trust
719 * the platform to do this correctly.
720 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000721 }
Tim Peters96685bf2001-08-23 22:31:37 +0000722 errno = 0;
723 PyFPE_START_PROTECT("pow", return NULL)
724 ix = pow(iv, iw);
725 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000726 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000727 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000728 /* We don't expect any errno value other than ERANGE, but
729 * the range of libm bugs appears unbounded.
730 */
731 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
732 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000734 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736}
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000739float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000740{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000742}
743
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000745float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000746{
Tim Peters0280cf72001-09-11 21:53:35 +0000747 if (PyFloat_CheckExact(v)) {
748 Py_INCREF(v);
749 return (PyObject *)v;
750 }
751 else
752 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000753}
754
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000756float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000757{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000758 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759}
760
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000761static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000762float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000763{
764 return v->ob_fval != 0.0;
765}
766
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000768float_long(PyObject *v)
769{
770 double x = PyFloat_AsDouble(v);
771 return PyLong_FromDouble(x);
772}
773
774static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000775float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000776{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000777 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000778 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000779
780 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000781 /* Try to get out cheap if this fits in a Python int. The attempt
782 * to cast to long must be protected, as C doesn't define what
783 * happens if the double is too big to fit in a long. Some rare
784 * systems raise an exception then (RISCOS was mentioned as one,
785 * and someone using a non-default option on Sun also bumped into
786 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
787 * still be vulnerable: if a long has more bits of precision than
788 * a double, casting MIN/MAX to double may yield an approximation,
789 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
790 * yield true from the C expression wholepart<=LONG_MAX, despite
791 * that wholepart is actually greater than LONG_MAX.
792 */
793 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
794 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000795 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000796 }
797 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000798}
799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000801float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000802{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000803 if (PyFloat_CheckExact(v))
804 Py_INCREF(v);
805 else
806 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000807 return v;
808}
809
810
Jeremy Hylton938ace62002-07-17 16:30:39 +0000811static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000812float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
813
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814static PyObject *
815float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
816{
817 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000818 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819
Guido van Rossumbef14172001-08-29 15:47:46 +0000820 if (type != &PyFloat_Type)
821 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
823 return NULL;
824 if (PyString_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000825 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826 return PyNumber_Float(x);
827}
828
Guido van Rossumbef14172001-08-29 15:47:46 +0000829/* Wimpy, slow approach to tp_new calls for subtypes of float:
830 first create a regular float from whatever arguments we got,
831 then allocate a subtype instance and initialize its ob_fval
832 from the regular float. The regular float is then thrown away.
833*/
834static PyObject *
835float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
836{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000838
839 assert(PyType_IsSubtype(type, &PyFloat_Type));
840 tmp = float_new(&PyFloat_Type, args, kwds);
841 if (tmp == NULL)
842 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000843 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844 newobj = type->tp_alloc(type, 0);
845 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000846 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000847 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000848 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000849 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000850 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000851 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000852}
853
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000854static PyObject *
855float_getnewargs(PyFloatObject *v)
856{
857 return Py_BuildValue("(d)", v->ob_fval);
858}
859
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000860/* this is for the benefit of the pack/unpack routines below */
861
862typedef enum {
863 unknown_format, ieee_big_endian_format, ieee_little_endian_format
864} float_format_type;
865
866static float_format_type double_format, float_format;
867static float_format_type detected_double_format, detected_float_format;
868
869static PyObject *
870float_getformat(PyTypeObject *v, PyObject* arg)
871{
872 char* s;
873 float_format_type r;
874
Guido van Rossum2be161d2007-05-15 20:43:51 +0000875 if (PyUnicode_Check(arg)) {
876 arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
877 if (arg == NULL)
878 return NULL;
879 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000880 if (!PyString_Check(arg)) {
881 PyErr_Format(PyExc_TypeError,
882 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000883 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000884 return NULL;
885 }
886 s = PyString_AS_STRING(arg);
887 if (strcmp(s, "double") == 0) {
888 r = double_format;
889 }
890 else if (strcmp(s, "float") == 0) {
891 r = float_format;
892 }
893 else {
894 PyErr_SetString(PyExc_ValueError,
895 "__getformat__() argument 1 must be "
896 "'double' or 'float'");
897 return NULL;
898 }
899
900 switch (r) {
901 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000902 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000903 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000904 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000905 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000906 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000907 default:
908 Py_FatalError("insane float_format or double_format");
909 return NULL;
910 }
911}
912
913PyDoc_STRVAR(float_getformat_doc,
914"float.__getformat__(typestr) -> string\n"
915"\n"
916"You probably don't want to use this function. It exists mainly to be\n"
917"used in Python's test suite.\n"
918"\n"
919"typestr must be 'double' or 'float'. This function returns whichever of\n"
920"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
921"format of floating point numbers used by the C type named by typestr.");
922
923static PyObject *
924float_setformat(PyTypeObject *v, PyObject* args)
925{
926 char* typestr;
927 char* format;
928 float_format_type f;
929 float_format_type detected;
930 float_format_type *p;
931
932 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
933 return NULL;
934
935 if (strcmp(typestr, "double") == 0) {
936 p = &double_format;
937 detected = detected_double_format;
938 }
939 else if (strcmp(typestr, "float") == 0) {
940 p = &float_format;
941 detected = detected_float_format;
942 }
943 else {
944 PyErr_SetString(PyExc_ValueError,
945 "__setformat__() argument 1 must "
946 "be 'double' or 'float'");
947 return NULL;
948 }
949
950 if (strcmp(format, "unknown") == 0) {
951 f = unknown_format;
952 }
953 else if (strcmp(format, "IEEE, little-endian") == 0) {
954 f = ieee_little_endian_format;
955 }
956 else if (strcmp(format, "IEEE, big-endian") == 0) {
957 f = ieee_big_endian_format;
958 }
959 else {
960 PyErr_SetString(PyExc_ValueError,
961 "__setformat__() argument 2 must be "
962 "'unknown', 'IEEE, little-endian' or "
963 "'IEEE, big-endian'");
964 return NULL;
965
966 }
967
968 if (f != unknown_format && f != detected) {
969 PyErr_Format(PyExc_ValueError,
970 "can only set %s format to 'unknown' or the "
971 "detected platform value", typestr);
972 return NULL;
973 }
974
975 *p = f;
976 Py_RETURN_NONE;
977}
978
979PyDoc_STRVAR(float_setformat_doc,
980"float.__setformat__(typestr, fmt) -> None\n"
981"\n"
982"You probably don't want to use this function. It exists mainly to be\n"
983"used in Python's test suite.\n"
984"\n"
985"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
986"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
987"one of the latter two if it appears to match the underlying C reality.\n"
988"\n"
989"Overrides the automatic determination of C-level floating point type.\n"
990"This affects how floats are converted to and from binary strings.");
991
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000992static PyMethodDef float_methods[] = {
993 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000994 {"__getformat__", (PyCFunction)float_getformat,
995 METH_O|METH_CLASS, float_getformat_doc},
996 {"__setformat__", (PyCFunction)float_setformat,
997 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000998 {NULL, NULL} /* sentinel */
999};
1000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001001PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002"float(x) -> floating point number\n\
1003\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001004Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005
1006
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001007static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001008 float_add, /*nb_add*/
1009 float_sub, /*nb_subtract*/
1010 float_mul, /*nb_multiply*/
1011 float_rem, /*nb_remainder*/
1012 float_divmod, /*nb_divmod*/
1013 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001014 (unaryfunc)float_neg, /*nb_negative*/
1015 (unaryfunc)float_pos, /*nb_positive*/
1016 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001017 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001018 0, /*nb_invert*/
1019 0, /*nb_lshift*/
1020 0, /*nb_rshift*/
1021 0, /*nb_and*/
1022 0, /*nb_xor*/
1023 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001024 (coercion)0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001025 float_int, /*nb_int*/
1026 float_long, /*nb_long*/
1027 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001028 0, /* nb_oct */
1029 0, /* nb_hex */
1030 0, /* nb_inplace_add */
1031 0, /* nb_inplace_subtract */
1032 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001033 0, /* nb_inplace_remainder */
1034 0, /* nb_inplace_power */
1035 0, /* nb_inplace_lshift */
1036 0, /* nb_inplace_rshift */
1037 0, /* nb_inplace_and */
1038 0, /* nb_inplace_xor */
1039 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001040 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001041 float_div, /* nb_true_divide */
1042 0, /* nb_inplace_floor_divide */
1043 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001044};
1045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001046PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001047 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001048 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001050 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051 (destructor)float_dealloc, /* tp_dealloc */
1052 (printfunc)float_print, /* tp_print */
1053 0, /* tp_getattr */
1054 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001055 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 (reprfunc)float_repr, /* tp_repr */
1057 &float_as_number, /* tp_as_number */
1058 0, /* tp_as_sequence */
1059 0, /* tp_as_mapping */
1060 (hashfunc)float_hash, /* tp_hash */
1061 0, /* tp_call */
1062 (reprfunc)float_str, /* tp_str */
1063 PyObject_GenericGetAttr, /* tp_getattro */
1064 0, /* tp_setattro */
1065 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001066 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067 float_doc, /* tp_doc */
1068 0, /* tp_traverse */
1069 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001070 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071 0, /* tp_weaklistoffset */
1072 0, /* tp_iter */
1073 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001074 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 0, /* tp_members */
1076 0, /* tp_getset */
1077 0, /* tp_base */
1078 0, /* tp_dict */
1079 0, /* tp_descr_get */
1080 0, /* tp_descr_set */
1081 0, /* tp_dictoffset */
1082 0, /* tp_init */
1083 0, /* tp_alloc */
1084 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001085};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001086
1087void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001088_PyFloat_Init(void)
1089{
1090 /* We attempt to determine if this machine is using IEEE
1091 floating point formats by peering at the bits of some
1092 carefully chosen values. If it looks like we are on an
1093 IEEE platform, the float packing/unpacking routines can
1094 just copy bits, if not they resort to arithmetic & shifts
1095 and masks. The shifts & masks approach works on all finite
1096 values, but what happens to infinities, NaNs and signed
1097 zeroes on packing is an accident, and attempting to unpack
1098 a NaN or an infinity will raise an exception.
1099
1100 Note that if we're on some whacked-out platform which uses
1101 IEEE formats but isn't strictly little-endian or big-
1102 endian, we will fall back to the portable shifts & masks
1103 method. */
1104
1105#if SIZEOF_DOUBLE == 8
1106 {
1107 double x = 9006104071832581.0;
1108 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1109 detected_double_format = ieee_big_endian_format;
1110 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1111 detected_double_format = ieee_little_endian_format;
1112 else
1113 detected_double_format = unknown_format;
1114 }
1115#else
1116 detected_double_format = unknown_format;
1117#endif
1118
1119#if SIZEOF_FLOAT == 4
1120 {
1121 float y = 16711938.0;
1122 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1123 detected_float_format = ieee_big_endian_format;
1124 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1125 detected_float_format = ieee_little_endian_format;
1126 else
1127 detected_float_format = unknown_format;
1128 }
1129#else
1130 detected_float_format = unknown_format;
1131#endif
1132
1133 double_format = detected_double_format;
1134 float_format = detected_float_format;
1135}
1136
1137void
Fred Drakefd99de62000-07-09 05:02:18 +00001138PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001139{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001140 PyFloatObject *p;
1141 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001142 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001143 int bc, bf; /* block count, number of freed blocks */
1144 int frem, fsum; /* remaining unfreed floats per block, total */
1145
1146 bc = 0;
1147 bf = 0;
1148 fsum = 0;
1149 list = block_list;
1150 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001151 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001152 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001153 bc++;
1154 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001155 for (i = 0, p = &list->objects[0];
1156 i < N_FLOATOBJECTS;
1157 i++, p++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001158 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001159 frem++;
1160 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001161 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001162 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001163 list->next = block_list;
1164 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001165 for (i = 0, p = &list->objects[0];
1166 i < N_FLOATOBJECTS;
1167 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001168 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001169 Py_Refcnt(p) == 0) {
1170 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001171 free_list;
1172 free_list = p;
1173 }
1174 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001175 }
1176 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001177 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001178 bf++;
1179 }
1180 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001181 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001182 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001183 if (!Py_VerboseFlag)
1184 return;
1185 fprintf(stderr, "# cleanup floats");
1186 if (!fsum) {
1187 fprintf(stderr, "\n");
1188 }
1189 else {
1190 fprintf(stderr,
1191 ": %d unfreed float%s in %d out of %d block%s\n",
1192 fsum, fsum == 1 ? "" : "s",
1193 bc - bf, bc, bc == 1 ? "" : "s");
1194 }
1195 if (Py_VerboseFlag > 1) {
1196 list = block_list;
1197 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001198 for (i = 0, p = &list->objects[0];
1199 i < N_FLOATOBJECTS;
1200 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001201 if (PyFloat_CheckExact(p) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001202 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001203 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001204 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001205 /* XXX(twouters) cast refcount to
1206 long until %zd is universally
1207 available
1208 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001209 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001210 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001211 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001212 }
1213 }
1214 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001215 }
1216 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001217}
Tim Peters9905b942003-03-20 20:53:32 +00001218
1219/*----------------------------------------------------------------------------
1220 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1221 *
1222 * TODO: On platforms that use the standard IEEE-754 single and double
1223 * formats natively, these routines could simply copy the bytes.
1224 */
1225int
1226_PyFloat_Pack4(double x, unsigned char *p, int le)
1227{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001228 if (float_format == unknown_format) {
1229 unsigned char sign;
1230 int e;
1231 double f;
1232 unsigned int fbits;
1233 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001234
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001235 if (le) {
1236 p += 3;
1237 incr = -1;
1238 }
Tim Peters9905b942003-03-20 20:53:32 +00001239
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001240 if (x < 0) {
1241 sign = 1;
1242 x = -x;
1243 }
1244 else
1245 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001246
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001247 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001248
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001249 /* Normalize f to be in the range [1.0, 2.0) */
1250 if (0.5 <= f && f < 1.0) {
1251 f *= 2.0;
1252 e--;
1253 }
1254 else if (f == 0.0)
1255 e = 0;
1256 else {
1257 PyErr_SetString(PyExc_SystemError,
1258 "frexp() result out of range");
1259 return -1;
1260 }
1261
1262 if (e >= 128)
1263 goto Overflow;
1264 else if (e < -126) {
1265 /* Gradual underflow */
1266 f = ldexp(f, 126 + e);
1267 e = 0;
1268 }
1269 else if (!(e == 0 && f == 0.0)) {
1270 e += 127;
1271 f -= 1.0; /* Get rid of leading 1 */
1272 }
1273
1274 f *= 8388608.0; /* 2**23 */
1275 fbits = (unsigned int)(f + 0.5); /* Round */
1276 assert(fbits <= 8388608);
1277 if (fbits >> 23) {
1278 /* The carry propagated out of a string of 23 1 bits. */
1279 fbits = 0;
1280 ++e;
1281 if (e >= 255)
1282 goto Overflow;
1283 }
1284
1285 /* First byte */
1286 *p = (sign << 7) | (e >> 1);
1287 p += incr;
1288
1289 /* Second byte */
1290 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1291 p += incr;
1292
1293 /* Third byte */
1294 *p = (fbits >> 8) & 0xFF;
1295 p += incr;
1296
1297 /* Fourth byte */
1298 *p = fbits & 0xFF;
1299
1300 /* Done */
1301 return 0;
1302
1303 Overflow:
1304 PyErr_SetString(PyExc_OverflowError,
1305 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001306 return -1;
1307 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001308 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001309 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001310 const char *s = (char*)&y;
1311 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001312
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001313 if ((float_format == ieee_little_endian_format && !le)
1314 || (float_format == ieee_big_endian_format && le)) {
1315 p += 3;
1316 incr = -1;
1317 }
1318
1319 for (i = 0; i < 4; i++) {
1320 *p = *s++;
1321 p += incr;
1322 }
1323 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001324 }
Tim Peters9905b942003-03-20 20:53:32 +00001325}
1326
1327int
1328_PyFloat_Pack8(double x, unsigned char *p, int le)
1329{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001330 if (double_format == unknown_format) {
1331 unsigned char sign;
1332 int e;
1333 double f;
1334 unsigned int fhi, flo;
1335 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001336
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001337 if (le) {
1338 p += 7;
1339 incr = -1;
1340 }
Tim Peters9905b942003-03-20 20:53:32 +00001341
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001342 if (x < 0) {
1343 sign = 1;
1344 x = -x;
1345 }
1346 else
1347 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001348
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001349 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001350
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001351 /* Normalize f to be in the range [1.0, 2.0) */
1352 if (0.5 <= f && f < 1.0) {
1353 f *= 2.0;
1354 e--;
1355 }
1356 else if (f == 0.0)
1357 e = 0;
1358 else {
1359 PyErr_SetString(PyExc_SystemError,
1360 "frexp() result out of range");
1361 return -1;
1362 }
1363
1364 if (e >= 1024)
1365 goto Overflow;
1366 else if (e < -1022) {
1367 /* Gradual underflow */
1368 f = ldexp(f, 1022 + e);
1369 e = 0;
1370 }
1371 else if (!(e == 0 && f == 0.0)) {
1372 e += 1023;
1373 f -= 1.0; /* Get rid of leading 1 */
1374 }
1375
1376 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1377 f *= 268435456.0; /* 2**28 */
1378 fhi = (unsigned int)f; /* Truncate */
1379 assert(fhi < 268435456);
1380
1381 f -= (double)fhi;
1382 f *= 16777216.0; /* 2**24 */
1383 flo = (unsigned int)(f + 0.5); /* Round */
1384 assert(flo <= 16777216);
1385 if (flo >> 24) {
1386 /* The carry propagated out of a string of 24 1 bits. */
1387 flo = 0;
1388 ++fhi;
1389 if (fhi >> 28) {
1390 /* And it also progagated out of the next 28 bits. */
1391 fhi = 0;
1392 ++e;
1393 if (e >= 2047)
1394 goto Overflow;
1395 }
1396 }
1397
1398 /* First byte */
1399 *p = (sign << 7) | (e >> 4);
1400 p += incr;
1401
1402 /* Second byte */
1403 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1404 p += incr;
1405
1406 /* Third byte */
1407 *p = (fhi >> 16) & 0xFF;
1408 p += incr;
1409
1410 /* Fourth byte */
1411 *p = (fhi >> 8) & 0xFF;
1412 p += incr;
1413
1414 /* Fifth byte */
1415 *p = fhi & 0xFF;
1416 p += incr;
1417
1418 /* Sixth byte */
1419 *p = (flo >> 16) & 0xFF;
1420 p += incr;
1421
1422 /* Seventh byte */
1423 *p = (flo >> 8) & 0xFF;
1424 p += incr;
1425
1426 /* Eighth byte */
1427 *p = flo & 0xFF;
1428 p += incr;
1429
1430 /* Done */
1431 return 0;
1432
1433 Overflow:
1434 PyErr_SetString(PyExc_OverflowError,
1435 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001436 return -1;
1437 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001438 else {
1439 const char *s = (char*)&x;
1440 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001441
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001442 if ((double_format == ieee_little_endian_format && !le)
1443 || (double_format == ieee_big_endian_format && le)) {
1444 p += 7;
1445 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001446 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001447
1448 for (i = 0; i < 8; i++) {
1449 *p = *s++;
1450 p += incr;
1451 }
1452 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001453 }
Tim Peters9905b942003-03-20 20:53:32 +00001454}
1455
Neal Norwitz545686b2006-12-28 04:45:06 +00001456/* Should only be used by marshal. */
1457int
1458_PyFloat_Repr(double x, char *p, size_t len)
1459{
1460 format_double(p, len, x, PREC_REPR);
1461 return (int)strlen(p);
1462}
1463
Tim Peters9905b942003-03-20 20:53:32 +00001464double
1465_PyFloat_Unpack4(const unsigned char *p, int le)
1466{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001467 if (float_format == unknown_format) {
1468 unsigned char sign;
1469 int e;
1470 unsigned int f;
1471 double x;
1472 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001473
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001474 if (le) {
1475 p += 3;
1476 incr = -1;
1477 }
1478
1479 /* First byte */
1480 sign = (*p >> 7) & 1;
1481 e = (*p & 0x7F) << 1;
1482 p += incr;
1483
1484 /* Second byte */
1485 e |= (*p >> 7) & 1;
1486 f = (*p & 0x7F) << 16;
1487 p += incr;
1488
1489 if (e == 255) {
1490 PyErr_SetString(
1491 PyExc_ValueError,
1492 "can't unpack IEEE 754 special value "
1493 "on non-IEEE platform");
1494 return -1;
1495 }
1496
1497 /* Third byte */
1498 f |= *p << 8;
1499 p += incr;
1500
1501 /* Fourth byte */
1502 f |= *p;
1503
1504 x = (double)f / 8388608.0;
1505
1506 /* XXX This sadly ignores Inf/NaN issues */
1507 if (e == 0)
1508 e = -126;
1509 else {
1510 x += 1.0;
1511 e -= 127;
1512 }
1513 x = ldexp(x, e);
1514
1515 if (sign)
1516 x = -x;
1517
1518 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001519 }
Tim Peters9905b942003-03-20 20:53:32 +00001520 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001521 float x;
1522
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001523 if ((float_format == ieee_little_endian_format && !le)
1524 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001525 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001526 char *d = &buf[3];
1527 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001528
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001529 for (i = 0; i < 4; i++) {
1530 *d-- = *p++;
1531 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001532 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001533 }
1534 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001535 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001536 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001537
1538 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001539 }
Tim Peters9905b942003-03-20 20:53:32 +00001540}
1541
1542double
1543_PyFloat_Unpack8(const unsigned char *p, int le)
1544{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001545 if (double_format == unknown_format) {
1546 unsigned char sign;
1547 int e;
1548 unsigned int fhi, flo;
1549 double x;
1550 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001551
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001552 if (le) {
1553 p += 7;
1554 incr = -1;
1555 }
1556
1557 /* First byte */
1558 sign = (*p >> 7) & 1;
1559 e = (*p & 0x7F) << 4;
1560
1561 p += incr;
1562
1563 /* Second byte */
1564 e |= (*p >> 4) & 0xF;
1565 fhi = (*p & 0xF) << 24;
1566 p += incr;
1567
1568 if (e == 2047) {
1569 PyErr_SetString(
1570 PyExc_ValueError,
1571 "can't unpack IEEE 754 special value "
1572 "on non-IEEE platform");
1573 return -1.0;
1574 }
1575
1576 /* Third byte */
1577 fhi |= *p << 16;
1578 p += incr;
1579
1580 /* Fourth byte */
1581 fhi |= *p << 8;
1582 p += incr;
1583
1584 /* Fifth byte */
1585 fhi |= *p;
1586 p += incr;
1587
1588 /* Sixth byte */
1589 flo = *p << 16;
1590 p += incr;
1591
1592 /* Seventh byte */
1593 flo |= *p << 8;
1594 p += incr;
1595
1596 /* Eighth byte */
1597 flo |= *p;
1598
1599 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1600 x /= 268435456.0; /* 2**28 */
1601
1602 if (e == 0)
1603 e = -1022;
1604 else {
1605 x += 1.0;
1606 e -= 1023;
1607 }
1608 x = ldexp(x, e);
1609
1610 if (sign)
1611 x = -x;
1612
1613 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001614 }
Tim Peters9905b942003-03-20 20:53:32 +00001615 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001616 double x;
1617
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618 if ((double_format == ieee_little_endian_format && !le)
1619 || (double_format == ieee_big_endian_format && le)) {
1620 char buf[8];
1621 char *d = &buf[7];
1622 int i;
1623
1624 for (i = 0; i < 8; i++) {
1625 *d-- = *p++;
1626 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001627 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001628 }
1629 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001630 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001631 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001632
1633 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001634 }
Tim Peters9905b942003-03-20 20:53:32 +00001635}