blob: eb540e691a7984661728026a2276de11b2c0861a [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
Eric Smith8c663262007-08-25 02:26:07 +00009#include "formatter_unicode.h"
10
Guido van Rossum3f5da241990-12-20 15:06:42 +000011#include <ctype.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Jack Janseneddc1442003-11-20 01:44:59 +000013#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000014extern double fmod(double, double);
15extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000016#endif
17
Guido van Rossum93ad0df1997-05-13 21:00:42 +000018/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000019#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000020#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000021#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000022
Guido van Rossum3fce8831999-03-12 19:43:17 +000023struct _floatblock {
24 struct _floatblock *next;
25 PyFloatObject objects[N_FLOATOBJECTS];
26};
27
28typedef struct _floatblock PyFloatBlock;
29
30static PyFloatBlock *block_list = NULL;
31static PyFloatObject *free_list = NULL;
32
Guido van Rossum93ad0df1997-05-13 21:00:42 +000033static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000034fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000035{
36 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000037 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
38 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000040 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000041 ((PyFloatBlock *)p)->next = block_list;
42 block_list = (PyFloatBlock *)p;
43 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044 q = p + N_FLOATOBJECTS;
45 while (--q > p)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000046 Py_Type(q) = (struct _typeobject *)(q-1);
47 Py_Type(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 return p + N_FLOATOBJECTS - 1;
49}
50
Guido van Rossumc0b618a1997-05-02 03:12:38 +000051PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000052PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053{
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 register PyFloatObject *op;
55 if (free_list == NULL) {
56 if ((free_list = fill_free_list()) == NULL)
57 return NULL;
58 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +000059 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000060 op = free_list;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000061 free_list = (PyFloatObject *)Py_Type(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +000062 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +000063 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065}
66
Barry Warsaw226ae6c1999-10-12 19:54:53 +000067PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +000068PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +000069{
Guido van Rossum4c08d552000-03-10 22:55:18 +000070 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000071 double x;
Tim Petersef14d732000-09-23 03:39:17 +000072 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +000073 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +000074 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +000075 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000076
Neal Norwitz6ea45d32007-08-26 04:19:43 +000077 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +000078 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
79 if (s_buffer == NULL)
80 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +000081 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +000082 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +000083 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +000084 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +000085 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +000086 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +000087 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +000088 }
Guido van Rossum4c08d552000-03-10 22:55:18 +000089 else if (PyObject_AsCharBuffer(v, &s, &len)) {
90 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +000091 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +000092 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +000093 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +000094
Guido van Rossum4c08d552000-03-10 22:55:18 +000095 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000096 while (*s && isspace(Py_CHARMASK(*s)))
97 s++;
Tim Petersef14d732000-09-23 03:39:17 +000098 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +000099 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000100 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000101 }
Tim Petersef14d732000-09-23 03:39:17 +0000102 /* We don't care about overflow or underflow. If the platform supports
103 * them, infinities and signed zeroes (on underflow) are fine.
104 * However, strtod can return 0 for denormalized numbers, where atof
105 * does not. So (alas!) we special-case a zero result. Note that
106 * whether strtod sets errno on underflow is not defined, so we can't
107 * key off errno.
108 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000109 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000110 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000111 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000112 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000113 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000114 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000115 if (end > last)
116 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000117 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000118 PyOS_snprintf(buffer, sizeof(buffer),
119 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000120 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000121 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000122 }
123 /* Since end != s, the platform made *some* kind of sense out
124 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000125 while (*end && isspace(Py_CHARMASK(*end)))
126 end++;
127 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000128 PyOS_snprintf(buffer, sizeof(buffer),
129 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000130 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000131 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000132 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000133 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000134 PyErr_SetString(PyExc_ValueError,
135 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000136 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000137 }
Tim Petersef14d732000-09-23 03:39:17 +0000138 if (x == 0.0) {
139 /* See above -- may have been strtod being anal
140 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000141 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000142 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000143 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000144 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000145 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000146 result = PyFloat_FromDouble(x);
147 error:
148 if (s_buffer)
149 PyMem_FREE(s_buffer);
150 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000151}
152
Guido van Rossum234f9421993-06-17 12:35:49 +0000153static void
Fred Drakefd99de62000-07-09 05:02:18 +0000154float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000155{
Guido van Rossum9475a232001-10-05 20:51:39 +0000156 if (PyFloat_CheckExact(op)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000157 Py_Type(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000158 free_list = op;
159 }
160 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000161 Py_Type(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000162}
163
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164double
Fred Drakefd99de62000-07-09 05:02:18 +0000165PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000167 PyNumberMethods *nb;
168 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000169 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000170
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 if (op && PyFloat_Check(op))
172 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000173
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000174 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176 return -1;
177 }
Tim Petersd2364e82001-11-01 20:09:42 +0000178
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000179 if ((nb = Py_Type(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000180 PyErr_SetString(PyExc_TypeError, "a float is required");
181 return -1;
182 }
183
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000184 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000185 if (fo == NULL)
186 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187 if (!PyFloat_Check(fo)) {
188 PyErr_SetString(PyExc_TypeError,
189 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000190 return -1;
191 }
Tim Petersd2364e82001-11-01 20:09:42 +0000192
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 val = PyFloat_AS_DOUBLE(fo);
194 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000195
Guido van Rossumb6775db1994-08-01 11:34:53 +0000196 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197}
198
199/* Methods */
200
Tim Peters97019e42001-11-28 22:43:45 +0000201static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000202format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203{
204 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000205 char format[32];
Guido van Rossum04dbf3b2007-08-07 19:51:00 +0000206 /* Subroutine for float_repr, float_str, and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207 We want float numbers to be recognizable as such,
208 i.e., they should contain a decimal point or an exponent.
209 However, %g may print the number as an integer;
210 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000211
Martin v. Löwis737ea822004-06-08 18:52:54 +0000212 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000213 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214 cp = buf;
215 if (*cp == '-')
216 cp++;
217 for (; *cp != '\0'; cp++) {
218 /* Any non-digit means it's not an integer;
219 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000220 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221 break;
222 }
223 if (*cp == '\0') {
224 *cp++ = '.';
225 *cp++ = '0';
226 *cp++ = '\0';
227 }
228}
229
Neal Norwitz545686b2006-12-28 04:45:06 +0000230static void
231format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000232{
Neal Norwitz545686b2006-12-28 04:45:06 +0000233 assert(PyFloat_Check(v));
234 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000235}
236
Neil Schemenauer32117e52001-01-04 01:44:34 +0000237/* Macro and helper that convert PyObject obj to a C double and store
238 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000239 slot function. If conversion to double raises an exception, obj is
240 set to NULL, and the function invoking this macro returns NULL. If
241 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
242 stored in obj, and returned from the function invoking this macro.
243*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000244#define CONVERT_TO_DOUBLE(obj, dbl) \
245 if (PyFloat_Check(obj)) \
246 dbl = PyFloat_AS_DOUBLE(obj); \
247 else if (convert_to_double(&(obj), &(dbl)) < 0) \
248 return obj;
249
250static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000251convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000252{
253 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000254
Guido van Rossumddefaf32007-01-14 03:31:43 +0000255 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000256 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000257 if (*dbl == -1.0 && PyErr_Occurred()) {
258 *v = NULL;
259 return -1;
260 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000261 }
262 else {
263 Py_INCREF(Py_NotImplemented);
264 *v = Py_NotImplemented;
265 return -1;
266 }
267 return 0;
268}
269
Guido van Rossum57072eb1999-12-23 19:00:28 +0000270/* Precisions used by repr() and str(), respectively.
271
272 The repr() precision (17 significant decimal digits) is the minimal number
273 that is guaranteed to have enough precision so that if the number is read
274 back in the exact same binary value is recreated. This is true for IEEE
275 floating point by design, and also happens to work for all other modern
276 hardware.
277
278 The str() precision is chosen so that in most cases, the rounding noise
279 created by various operations is suppressed, while giving plenty of
280 precision for practical use.
281
282*/
283
284#define PREC_REPR 17
285#define PREC_STR 12
286
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000288float_repr(PyFloatObject *v)
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, PREC_REPR);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000292 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000293}
294
295static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000296float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000297{
298 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000299 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000300 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301}
302
Tim Peters307fa782004-09-23 08:06:40 +0000303/* Comparison is pretty much a nightmare. When comparing float to float,
304 * we do it as straightforwardly (and long-windedly) as conceivable, so
305 * that, e.g., Python x == y delivers the same result as the platform
306 * C x == y when x and/or y is a NaN.
307 * When mixing float with an integer type, there's no good *uniform* approach.
308 * Converting the double to an integer obviously doesn't work, since we
309 * may lose info from fractional bits. Converting the integer to a double
310 * also has two failure modes: (1) a long int may trigger overflow (too
311 * large to fit in the dynamic range of a C double); (2) even a C long may have
312 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
313 * 63 bits of precision, but a C double probably has only 53), and then
314 * we can falsely claim equality when low-order integer bits are lost by
315 * coercion to double. So this part is painful too.
316 */
317
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000318static PyObject*
319float_richcompare(PyObject *v, PyObject *w, int op)
320{
321 double i, j;
322 int r = 0;
323
Tim Peters307fa782004-09-23 08:06:40 +0000324 assert(PyFloat_Check(v));
325 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000326
Tim Peters307fa782004-09-23 08:06:40 +0000327 /* Switch on the type of w. Set i and j to doubles to be compared,
328 * and op to the richcomp to use.
329 */
330 if (PyFloat_Check(w))
331 j = PyFloat_AS_DOUBLE(w);
332
Thomas Wouters477c8d52006-05-27 19:21:47 +0000333 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000334 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000335 /* If i is an infinity, its magnitude exceeds any
336 * finite integer, so it doesn't matter which int we
337 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000338 */
339 j = 0.0;
340 else
341 goto Unimplemented;
342 }
343
Tim Peters307fa782004-09-23 08:06:40 +0000344 else if (PyLong_Check(w)) {
345 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
346 int wsign = _PyLong_Sign(w);
347 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000348 int exponent;
349
350 if (vsign != wsign) {
351 /* Magnitudes are irrelevant -- the signs alone
352 * determine the outcome.
353 */
354 i = (double)vsign;
355 j = (double)wsign;
356 goto Compare;
357 }
358 /* The signs are the same. */
359 /* Convert w to a double if it fits. In particular, 0 fits. */
360 nbits = _PyLong_NumBits(w);
361 if (nbits == (size_t)-1 && PyErr_Occurred()) {
362 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000363 * to hold the # of bits. Replace with little doubles
364 * that give the same outcome -- w is so large that
365 * its magnitude must exceed the magnitude of any
366 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000367 */
368 PyErr_Clear();
369 i = (double)vsign;
370 assert(wsign != 0);
371 j = wsign * 2.0;
372 goto Compare;
373 }
374 if (nbits <= 48) {
375 j = PyLong_AsDouble(w);
376 /* It's impossible that <= 48 bits overflowed. */
377 assert(j != -1.0 || ! PyErr_Occurred());
378 goto Compare;
379 }
380 assert(wsign != 0); /* else nbits was 0 */
381 assert(vsign != 0); /* if vsign were 0, then since wsign is
382 * not 0, we would have taken the
383 * vsign != wsign branch at the start */
384 /* We want to work with non-negative numbers. */
385 if (vsign < 0) {
386 /* "Multiply both sides" by -1; this also swaps the
387 * comparator.
388 */
389 i = -i;
390 op = _Py_SwappedOp[op];
391 }
392 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000393 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000394 /* exponent is the # of bits in v before the radix point;
395 * we know that nbits (the # of bits in w) > 48 at this point
396 */
397 if (exponent < 0 || (size_t)exponent < nbits) {
398 i = 1.0;
399 j = 2.0;
400 goto Compare;
401 }
402 if ((size_t)exponent > nbits) {
403 i = 2.0;
404 j = 1.0;
405 goto Compare;
406 }
407 /* v and w have the same number of bits before the radix
408 * point. Construct two longs that have the same comparison
409 * outcome.
410 */
411 {
412 double fracpart;
413 double intpart;
414 PyObject *result = NULL;
415 PyObject *one = NULL;
416 PyObject *vv = NULL;
417 PyObject *ww = w;
418
419 if (wsign < 0) {
420 ww = PyNumber_Negative(w);
421 if (ww == NULL)
422 goto Error;
423 }
424 else
425 Py_INCREF(ww);
426
427 fracpart = modf(i, &intpart);
428 vv = PyLong_FromDouble(intpart);
429 if (vv == NULL)
430 goto Error;
431
432 if (fracpart != 0.0) {
433 /* Shift left, and or a 1 bit into vv
434 * to represent the lost fraction.
435 */
436 PyObject *temp;
437
438 one = PyInt_FromLong(1);
439 if (one == NULL)
440 goto Error;
441
442 temp = PyNumber_Lshift(ww, one);
443 if (temp == NULL)
444 goto Error;
445 Py_DECREF(ww);
446 ww = temp;
447
448 temp = PyNumber_Lshift(vv, one);
449 if (temp == NULL)
450 goto Error;
451 Py_DECREF(vv);
452 vv = temp;
453
454 temp = PyNumber_Or(vv, one);
455 if (temp == NULL)
456 goto Error;
457 Py_DECREF(vv);
458 vv = temp;
459 }
460
461 r = PyObject_RichCompareBool(vv, ww, op);
462 if (r < 0)
463 goto Error;
464 result = PyBool_FromLong(r);
465 Error:
466 Py_XDECREF(vv);
467 Py_XDECREF(ww);
468 Py_XDECREF(one);
469 return result;
470 }
471 } /* else if (PyLong_Check(w)) */
472
473 else /* w isn't float, int, or long */
474 goto Unimplemented;
475
476 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000477 PyFPE_START_PROTECT("richcompare", return NULL)
478 switch (op) {
479 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000480 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000481 break;
482 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000483 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000484 break;
485 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000486 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000487 break;
488 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000489 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000490 break;
491 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000492 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000493 break;
494 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000495 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000496 break;
497 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000498 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000499 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000500
501 Unimplemented:
502 Py_INCREF(Py_NotImplemented);
503 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000504}
505
Guido van Rossum9bfef441993-03-29 10:43:31 +0000506static long
Fred Drakefd99de62000-07-09 05:02:18 +0000507float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000508{
Tim Peters39dce292000-08-15 03:34:48 +0000509 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000510}
511
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000513float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000514{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000515 double a,b;
516 CONVERT_TO_DOUBLE(v, a);
517 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000518 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000519 a = a + b;
520 PyFPE_END_PROTECT(a)
521 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000522}
523
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000525float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000526{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000527 double a,b;
528 CONVERT_TO_DOUBLE(v, a);
529 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000530 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000531 a = a - b;
532 PyFPE_END_PROTECT(a)
533 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000534}
535
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000539 double a,b;
540 CONVERT_TO_DOUBLE(v, a);
541 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000542 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543 a = a * b;
544 PyFPE_END_PROTECT(a)
545 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000549float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000551 double a,b;
552 CONVERT_TO_DOUBLE(v, a);
553 CONVERT_TO_DOUBLE(w, b);
554 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556 return NULL;
557 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000558 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000559 a = a / b;
560 PyFPE_END_PROTECT(a)
561 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000567 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000568 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000569 CONVERT_TO_DOUBLE(v, vx);
570 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000571 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573 return NULL;
574 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000575 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000576 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000577 /* note: checking mod*wx < 0 is incorrect -- underflows to
578 0 if wx < sqrt(smallest nonzero double) */
579 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000580 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000581 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000582 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584}
585
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000587float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000588{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000589 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000590 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000591 CONVERT_TO_DOUBLE(v, vx);
592 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000593 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000594 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000595 return NULL;
596 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000597 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000598 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000599 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000600 exact multiple of wx. But this is fp arithmetic, and fp
601 vx - mod is an approximation; the result is that div may
602 not be an exact integral value after the division, although
603 it will always be very close to one.
604 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000605 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000606 if (mod) {
607 /* ensure the remainder has the same sign as the denominator */
608 if ((wx < 0) != (mod < 0)) {
609 mod += wx;
610 div -= 1.0;
611 }
612 }
613 else {
614 /* the remainder is zero, and in the presence of signed zeroes
615 fmod returns different results across platforms; ensure
616 it has the same sign as the denominator; we'd like to do
617 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000618 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000619 if (wx < 0.0)
620 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000621 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000622 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000623 if (div) {
624 floordiv = floor(div);
625 if (div - floordiv > 0.5)
626 floordiv += 1.0;
627 }
628 else {
629 /* div is zero - get the same sign as the true quotient */
630 div *= div; /* hide "div = +0" from optimizers */
631 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
632 }
633 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000634 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000635}
636
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000638float_floor_div(PyObject *v, PyObject *w)
639{
640 PyObject *t, *r;
641
642 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000643 if (t == NULL || t == Py_NotImplemented)
644 return t;
645 assert(PyTuple_CheckExact(t));
646 r = PyTuple_GET_ITEM(t, 0);
647 Py_INCREF(r);
648 Py_DECREF(t);
649 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000650}
651
652static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000653float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000654{
655 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000656
657 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000658 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000659 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000660 return NULL;
661 }
662
Neil Schemenauer32117e52001-01-04 01:44:34 +0000663 CONVERT_TO_DOUBLE(v, iv);
664 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000665
666 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000667 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000668 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000669 }
Tim Peters96685bf2001-08-23 22:31:37 +0000670 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000671 if (iw < 0.0) {
672 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000673 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000674 return NULL;
675 }
676 return PyFloat_FromDouble(0.0);
677 }
Tim Peterse87568d2003-05-24 20:18:24 +0000678 if (iv < 0.0) {
679 /* Whether this is an error is a mess, and bumps into libm
680 * bugs so we have to figure it out ourselves.
681 */
682 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000683 /* Negative numbers raised to fractional powers
684 * become complex.
685 */
686 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000687 }
688 /* iw is an exact integer, albeit perhaps a very large one.
689 * -1 raised to an exact integer should never be exceptional.
690 * Alas, some libms (chiefly glibc as of early 2003) return
691 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
692 * happen to be representable in a *C* integer. That's a
693 * bug; we let that slide in math.pow() (which currently
694 * reflects all platform accidents), but not for Python's **.
695 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000697 /* Return 1 if iw is even, -1 if iw is odd; there's
698 * no guarantee that any C integral type is big
699 * enough to hold iw, so we have to check this
700 * indirectly.
701 */
702 ix = floor(iw * 0.5) * 2.0;
703 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
704 }
705 /* Else iv != -1.0, and overflow or underflow are possible.
706 * Unless we're to write pow() ourselves, we have to trust
707 * the platform to do this correctly.
708 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000709 }
Tim Peters96685bf2001-08-23 22:31:37 +0000710 errno = 0;
711 PyFPE_START_PROTECT("pow", return NULL)
712 ix = pow(iv, iw);
713 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000714 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000715 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000716 /* We don't expect any errno value other than ERANGE, but
717 * the range of libm bugs appears unbounded.
718 */
719 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
720 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000722 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000723 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000724}
725
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000727float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730}
731
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000733float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000734{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000735 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736}
737
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000738static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000739float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000740{
741 return v->ob_fval != 0.0;
742}
743
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000745float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000746{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000748 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000749
750 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000751 /* Try to get out cheap if this fits in a Python int. The attempt
752 * to cast to long must be protected, as C doesn't define what
753 * happens if the double is too big to fit in a long. Some rare
754 * systems raise an exception then (RISCOS was mentioned as one,
755 * and someone using a non-default option on Sun also bumped into
756 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
757 * still be vulnerable: if a long has more bits of precision than
758 * a double, casting MIN/MAX to double may yield an approximation,
759 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
760 * yield true from the C expression wholepart<=LONG_MAX, despite
761 * that wholepart is actually greater than LONG_MAX.
762 */
763 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
764 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000765 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000766 }
767 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000768}
769
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000771float_round(PyObject *v, PyObject *args)
772{
773#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
774 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000775 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000776 double flr, cil;
777 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000778 int ndigits = UNDEF_NDIGITS;
779
780 if (!PyArg_ParseTuple(args, "|i", &ndigits))
781 return NULL;
782
783 x = PyFloat_AsDouble(v);
784
785 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000786 f = pow(10.0, ndigits);
787 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000788 }
789
790 flr = floor(x);
791 cil = ceil(x);
792
793 if (x-flr > 0.5)
794 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000795 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000796 rounded = fmod(flr, 2) == 0 ? flr : cil;
797 else
798 rounded = flr;
799
800 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000801 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000802 return PyFloat_FromDouble(rounded);
803 }
804
805 return PyLong_FromDouble(rounded);
806#undef UNDEF_NDIGITS
807}
808
809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000811{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000812 if (PyFloat_CheckExact(v))
813 Py_INCREF(v);
814 else
815 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000816 return v;
817}
818
819
Jeremy Hylton938ace62002-07-17 16:30:39 +0000820static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000821float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
822
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823static PyObject *
824float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
825{
826 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000827 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828
Guido van Rossumbef14172001-08-29 15:47:46 +0000829 if (type != &PyFloat_Type)
830 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
832 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000833 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000834 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 return PyNumber_Float(x);
836}
837
Guido van Rossumbef14172001-08-29 15:47:46 +0000838/* Wimpy, slow approach to tp_new calls for subtypes of float:
839 first create a regular float from whatever arguments we got,
840 then allocate a subtype instance and initialize its ob_fval
841 from the regular float. The regular float is then thrown away.
842*/
843static PyObject *
844float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
845{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000847
848 assert(PyType_IsSubtype(type, &PyFloat_Type));
849 tmp = float_new(&PyFloat_Type, args, kwds);
850 if (tmp == NULL)
851 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000852 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000853 newobj = type->tp_alloc(type, 0);
854 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000855 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000856 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000857 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000859 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000860 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000861}
862
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000863static PyObject *
864float_getnewargs(PyFloatObject *v)
865{
866 return Py_BuildValue("(d)", v->ob_fval);
867}
868
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000869/* this is for the benefit of the pack/unpack routines below */
870
871typedef enum {
872 unknown_format, ieee_big_endian_format, ieee_little_endian_format
873} float_format_type;
874
875static float_format_type double_format, float_format;
876static float_format_type detected_double_format, detected_float_format;
877
878static PyObject *
879float_getformat(PyTypeObject *v, PyObject* arg)
880{
881 char* s;
882 float_format_type r;
883
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000884 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000885 PyErr_Format(PyExc_TypeError,
886 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000887 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000888 return NULL;
889 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000890 s = PyUnicode_AsString(arg);
891 if (s == NULL)
892 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000893 if (strcmp(s, "double") == 0) {
894 r = double_format;
895 }
896 else if (strcmp(s, "float") == 0) {
897 r = float_format;
898 }
899 else {
900 PyErr_SetString(PyExc_ValueError,
901 "__getformat__() argument 1 must be "
902 "'double' or 'float'");
903 return NULL;
904 }
905
906 switch (r) {
907 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000908 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000909 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000910 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000911 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000912 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000913 default:
914 Py_FatalError("insane float_format or double_format");
915 return NULL;
916 }
917}
918
919PyDoc_STRVAR(float_getformat_doc,
920"float.__getformat__(typestr) -> string\n"
921"\n"
922"You probably don't want to use this function. It exists mainly to be\n"
923"used in Python's test suite.\n"
924"\n"
925"typestr must be 'double' or 'float'. This function returns whichever of\n"
926"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
927"format of floating point numbers used by the C type named by typestr.");
928
929static PyObject *
930float_setformat(PyTypeObject *v, PyObject* args)
931{
932 char* typestr;
933 char* format;
934 float_format_type f;
935 float_format_type detected;
936 float_format_type *p;
937
938 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
939 return NULL;
940
941 if (strcmp(typestr, "double") == 0) {
942 p = &double_format;
943 detected = detected_double_format;
944 }
945 else if (strcmp(typestr, "float") == 0) {
946 p = &float_format;
947 detected = detected_float_format;
948 }
949 else {
950 PyErr_SetString(PyExc_ValueError,
951 "__setformat__() argument 1 must "
952 "be 'double' or 'float'");
953 return NULL;
954 }
955
956 if (strcmp(format, "unknown") == 0) {
957 f = unknown_format;
958 }
959 else if (strcmp(format, "IEEE, little-endian") == 0) {
960 f = ieee_little_endian_format;
961 }
962 else if (strcmp(format, "IEEE, big-endian") == 0) {
963 f = ieee_big_endian_format;
964 }
965 else {
966 PyErr_SetString(PyExc_ValueError,
967 "__setformat__() argument 2 must be "
968 "'unknown', 'IEEE, little-endian' or "
969 "'IEEE, big-endian'");
970 return NULL;
971
972 }
973
974 if (f != unknown_format && f != detected) {
975 PyErr_Format(PyExc_ValueError,
976 "can only set %s format to 'unknown' or the "
977 "detected platform value", typestr);
978 return NULL;
979 }
980
981 *p = f;
982 Py_RETURN_NONE;
983}
984
985PyDoc_STRVAR(float_setformat_doc,
986"float.__setformat__(typestr, fmt) -> None\n"
987"\n"
988"You probably don't want to use this function. It exists mainly to be\n"
989"used in Python's test suite.\n"
990"\n"
991"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
992"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
993"one of the latter two if it appears to match the underlying C reality.\n"
994"\n"
995"Overrides the automatic determination of C-level floating point type.\n"
996"This affects how floats are converted to and from binary strings.");
997
Guido van Rossumb43daf72007-08-01 18:08:08 +0000998static PyObject *
999float_getzero(PyObject *v, void *closure)
1000{
1001 return PyFloat_FromDouble(0.0);
1002}
1003
Eric Smith8c663262007-08-25 02:26:07 +00001004static PyObject *
1005float__format__(PyObject *self, PyObject *args)
1006{
1007 /* when back porting this to 2.6, check type of the format_spec
1008 and call either unicode_long__format__ or
1009 string_long__format__ */
1010 return unicode_float__format__(self, args);
1011}
1012
1013PyDoc_STRVAR(float__format__doc,
1014"float.__format__(format_spec) -> string\n"
1015"\n"
1016"Formats the float according to format_spec.");
1017
1018
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001019static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001020 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1021 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001022 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1023 "Returns the Integral closest to x between 0 and x."},
1024 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1025 "Returns the Integral closest to x, rounding half toward even.\n"
1026 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001027 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001028 {"__getformat__", (PyCFunction)float_getformat,
1029 METH_O|METH_CLASS, float_getformat_doc},
1030 {"__setformat__", (PyCFunction)float_setformat,
1031 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001032 {"__format__", (PyCFunction)float__format__,
1033 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001034 {NULL, NULL} /* sentinel */
1035};
1036
Guido van Rossumb43daf72007-08-01 18:08:08 +00001037static PyGetSetDef float_getset[] = {
1038 {"real",
1039 (getter)float_float, (setter)NULL,
1040 "the real part of a complex number",
1041 NULL},
1042 {"imag",
1043 (getter)float_getzero, (setter)NULL,
1044 "the imaginary part of a complex number",
1045 NULL},
1046 {NULL} /* Sentinel */
1047};
1048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001049PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050"float(x) -> floating point number\n\
1051\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001052Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053
1054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001055static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001056 float_add, /*nb_add*/
1057 float_sub, /*nb_subtract*/
1058 float_mul, /*nb_multiply*/
1059 float_rem, /*nb_remainder*/
1060 float_divmod, /*nb_divmod*/
1061 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001062 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001063 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001064 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001065 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001066 0, /*nb_invert*/
1067 0, /*nb_lshift*/
1068 0, /*nb_rshift*/
1069 0, /*nb_and*/
1070 0, /*nb_xor*/
1071 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001072 (coercion)0, /*nb_coerce*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001073 float_trunc, /*nb_int*/
1074 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001075 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001076 0, /* nb_oct */
1077 0, /* nb_hex */
1078 0, /* nb_inplace_add */
1079 0, /* nb_inplace_subtract */
1080 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001081 0, /* nb_inplace_remainder */
1082 0, /* nb_inplace_power */
1083 0, /* nb_inplace_lshift */
1084 0, /* nb_inplace_rshift */
1085 0, /* nb_inplace_and */
1086 0, /* nb_inplace_xor */
1087 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001088 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001089 float_div, /* nb_true_divide */
1090 0, /* nb_inplace_floor_divide */
1091 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001092};
1093
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001094PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001095 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001096 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001097 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001098 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001100 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 0, /* tp_getattr */
1102 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001103 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104 (reprfunc)float_repr, /* tp_repr */
1105 &float_as_number, /* tp_as_number */
1106 0, /* tp_as_sequence */
1107 0, /* tp_as_mapping */
1108 (hashfunc)float_hash, /* tp_hash */
1109 0, /* tp_call */
1110 (reprfunc)float_str, /* tp_str */
1111 PyObject_GenericGetAttr, /* tp_getattro */
1112 0, /* tp_setattro */
1113 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001114 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 float_doc, /* tp_doc */
1116 0, /* tp_traverse */
1117 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001118 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 0, /* tp_weaklistoffset */
1120 0, /* tp_iter */
1121 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001122 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001124 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 0, /* tp_base */
1126 0, /* tp_dict */
1127 0, /* tp_descr_get */
1128 0, /* tp_descr_set */
1129 0, /* tp_dictoffset */
1130 0, /* tp_init */
1131 0, /* tp_alloc */
1132 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001133};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001134
1135void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001136_PyFloat_Init(void)
1137{
1138 /* We attempt to determine if this machine is using IEEE
1139 floating point formats by peering at the bits of some
1140 carefully chosen values. If it looks like we are on an
1141 IEEE platform, the float packing/unpacking routines can
1142 just copy bits, if not they resort to arithmetic & shifts
1143 and masks. The shifts & masks approach works on all finite
1144 values, but what happens to infinities, NaNs and signed
1145 zeroes on packing is an accident, and attempting to unpack
1146 a NaN or an infinity will raise an exception.
1147
1148 Note that if we're on some whacked-out platform which uses
1149 IEEE formats but isn't strictly little-endian or big-
1150 endian, we will fall back to the portable shifts & masks
1151 method. */
1152
1153#if SIZEOF_DOUBLE == 8
1154 {
1155 double x = 9006104071832581.0;
1156 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1157 detected_double_format = ieee_big_endian_format;
1158 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1159 detected_double_format = ieee_little_endian_format;
1160 else
1161 detected_double_format = unknown_format;
1162 }
1163#else
1164 detected_double_format = unknown_format;
1165#endif
1166
1167#if SIZEOF_FLOAT == 4
1168 {
1169 float y = 16711938.0;
1170 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1171 detected_float_format = ieee_big_endian_format;
1172 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1173 detected_float_format = ieee_little_endian_format;
1174 else
1175 detected_float_format = unknown_format;
1176 }
1177#else
1178 detected_float_format = unknown_format;
1179#endif
1180
1181 double_format = detected_double_format;
1182 float_format = detected_float_format;
1183}
1184
1185void
Fred Drakefd99de62000-07-09 05:02:18 +00001186PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001187{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001188 PyFloatObject *p;
1189 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001190 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001191 int bc, bf; /* block count, number of freed blocks */
1192 int frem, fsum; /* remaining unfreed floats per block, total */
1193
1194 bc = 0;
1195 bf = 0;
1196 fsum = 0;
1197 list = block_list;
1198 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001199 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001200 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001201 bc++;
1202 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001203 for (i = 0, p = &list->objects[0];
1204 i < N_FLOATOBJECTS;
1205 i++, p++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001206 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001207 frem++;
1208 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001209 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001210 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001211 list->next = block_list;
1212 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001213 for (i = 0, p = &list->objects[0];
1214 i < N_FLOATOBJECTS;
1215 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001216 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001217 Py_Refcnt(p) == 0) {
1218 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001219 free_list;
1220 free_list = p;
1221 }
1222 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001223 }
1224 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001225 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001226 bf++;
1227 }
1228 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001229 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001230 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001231 if (!Py_VerboseFlag)
1232 return;
1233 fprintf(stderr, "# cleanup floats");
1234 if (!fsum) {
1235 fprintf(stderr, "\n");
1236 }
1237 else {
1238 fprintf(stderr,
1239 ": %d unfreed float%s in %d out of %d block%s\n",
1240 fsum, fsum == 1 ? "" : "s",
1241 bc - bf, bc, bc == 1 ? "" : "s");
1242 }
1243 if (Py_VerboseFlag > 1) {
1244 list = block_list;
1245 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001246 for (i = 0, p = &list->objects[0];
1247 i < N_FLOATOBJECTS;
1248 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001249 if (PyFloat_CheckExact(p) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001250 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001251 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001252 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001253 /* XXX(twouters) cast refcount to
1254 long until %zd is universally
1255 available
1256 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001257 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001258 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001259 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001260 }
1261 }
1262 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001263 }
1264 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001265}
Tim Peters9905b942003-03-20 20:53:32 +00001266
1267/*----------------------------------------------------------------------------
1268 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1269 *
1270 * TODO: On platforms that use the standard IEEE-754 single and double
1271 * formats natively, these routines could simply copy the bytes.
1272 */
1273int
1274_PyFloat_Pack4(double x, unsigned char *p, int le)
1275{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001276 if (float_format == unknown_format) {
1277 unsigned char sign;
1278 int e;
1279 double f;
1280 unsigned int fbits;
1281 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001282
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001283 if (le) {
1284 p += 3;
1285 incr = -1;
1286 }
Tim Peters9905b942003-03-20 20:53:32 +00001287
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001288 if (x < 0) {
1289 sign = 1;
1290 x = -x;
1291 }
1292 else
1293 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001294
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001295 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001296
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001297 /* Normalize f to be in the range [1.0, 2.0) */
1298 if (0.5 <= f && f < 1.0) {
1299 f *= 2.0;
1300 e--;
1301 }
1302 else if (f == 0.0)
1303 e = 0;
1304 else {
1305 PyErr_SetString(PyExc_SystemError,
1306 "frexp() result out of range");
1307 return -1;
1308 }
1309
1310 if (e >= 128)
1311 goto Overflow;
1312 else if (e < -126) {
1313 /* Gradual underflow */
1314 f = ldexp(f, 126 + e);
1315 e = 0;
1316 }
1317 else if (!(e == 0 && f == 0.0)) {
1318 e += 127;
1319 f -= 1.0; /* Get rid of leading 1 */
1320 }
1321
1322 f *= 8388608.0; /* 2**23 */
1323 fbits = (unsigned int)(f + 0.5); /* Round */
1324 assert(fbits <= 8388608);
1325 if (fbits >> 23) {
1326 /* The carry propagated out of a string of 23 1 bits. */
1327 fbits = 0;
1328 ++e;
1329 if (e >= 255)
1330 goto Overflow;
1331 }
1332
1333 /* First byte */
1334 *p = (sign << 7) | (e >> 1);
1335 p += incr;
1336
1337 /* Second byte */
1338 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1339 p += incr;
1340
1341 /* Third byte */
1342 *p = (fbits >> 8) & 0xFF;
1343 p += incr;
1344
1345 /* Fourth byte */
1346 *p = fbits & 0xFF;
1347
1348 /* Done */
1349 return 0;
1350
1351 Overflow:
1352 PyErr_SetString(PyExc_OverflowError,
1353 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001354 return -1;
1355 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001356 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001357 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001358 const char *s = (char*)&y;
1359 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001360
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001361 if ((float_format == ieee_little_endian_format && !le)
1362 || (float_format == ieee_big_endian_format && le)) {
1363 p += 3;
1364 incr = -1;
1365 }
1366
1367 for (i = 0; i < 4; i++) {
1368 *p = *s++;
1369 p += incr;
1370 }
1371 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001372 }
Tim Peters9905b942003-03-20 20:53:32 +00001373}
1374
1375int
1376_PyFloat_Pack8(double x, unsigned char *p, int le)
1377{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001378 if (double_format == unknown_format) {
1379 unsigned char sign;
1380 int e;
1381 double f;
1382 unsigned int fhi, flo;
1383 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001384
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001385 if (le) {
1386 p += 7;
1387 incr = -1;
1388 }
Tim Peters9905b942003-03-20 20:53:32 +00001389
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001390 if (x < 0) {
1391 sign = 1;
1392 x = -x;
1393 }
1394 else
1395 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001396
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001397 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001398
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001399 /* Normalize f to be in the range [1.0, 2.0) */
1400 if (0.5 <= f && f < 1.0) {
1401 f *= 2.0;
1402 e--;
1403 }
1404 else if (f == 0.0)
1405 e = 0;
1406 else {
1407 PyErr_SetString(PyExc_SystemError,
1408 "frexp() result out of range");
1409 return -1;
1410 }
1411
1412 if (e >= 1024)
1413 goto Overflow;
1414 else if (e < -1022) {
1415 /* Gradual underflow */
1416 f = ldexp(f, 1022 + e);
1417 e = 0;
1418 }
1419 else if (!(e == 0 && f == 0.0)) {
1420 e += 1023;
1421 f -= 1.0; /* Get rid of leading 1 */
1422 }
1423
1424 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1425 f *= 268435456.0; /* 2**28 */
1426 fhi = (unsigned int)f; /* Truncate */
1427 assert(fhi < 268435456);
1428
1429 f -= (double)fhi;
1430 f *= 16777216.0; /* 2**24 */
1431 flo = (unsigned int)(f + 0.5); /* Round */
1432 assert(flo <= 16777216);
1433 if (flo >> 24) {
1434 /* The carry propagated out of a string of 24 1 bits. */
1435 flo = 0;
1436 ++fhi;
1437 if (fhi >> 28) {
1438 /* And it also progagated out of the next 28 bits. */
1439 fhi = 0;
1440 ++e;
1441 if (e >= 2047)
1442 goto Overflow;
1443 }
1444 }
1445
1446 /* First byte */
1447 *p = (sign << 7) | (e >> 4);
1448 p += incr;
1449
1450 /* Second byte */
1451 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1452 p += incr;
1453
1454 /* Third byte */
1455 *p = (fhi >> 16) & 0xFF;
1456 p += incr;
1457
1458 /* Fourth byte */
1459 *p = (fhi >> 8) & 0xFF;
1460 p += incr;
1461
1462 /* Fifth byte */
1463 *p = fhi & 0xFF;
1464 p += incr;
1465
1466 /* Sixth byte */
1467 *p = (flo >> 16) & 0xFF;
1468 p += incr;
1469
1470 /* Seventh byte */
1471 *p = (flo >> 8) & 0xFF;
1472 p += incr;
1473
1474 /* Eighth byte */
1475 *p = flo & 0xFF;
1476 p += incr;
1477
1478 /* Done */
1479 return 0;
1480
1481 Overflow:
1482 PyErr_SetString(PyExc_OverflowError,
1483 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001484 return -1;
1485 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001486 else {
1487 const char *s = (char*)&x;
1488 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001489
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001490 if ((double_format == ieee_little_endian_format && !le)
1491 || (double_format == ieee_big_endian_format && le)) {
1492 p += 7;
1493 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001494 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001495
1496 for (i = 0; i < 8; i++) {
1497 *p = *s++;
1498 p += incr;
1499 }
1500 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001501 }
Tim Peters9905b942003-03-20 20:53:32 +00001502}
1503
Neal Norwitz545686b2006-12-28 04:45:06 +00001504/* Should only be used by marshal. */
1505int
1506_PyFloat_Repr(double x, char *p, size_t len)
1507{
1508 format_double(p, len, x, PREC_REPR);
1509 return (int)strlen(p);
1510}
1511
Tim Peters9905b942003-03-20 20:53:32 +00001512double
1513_PyFloat_Unpack4(const unsigned char *p, int le)
1514{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001515 if (float_format == unknown_format) {
1516 unsigned char sign;
1517 int e;
1518 unsigned int f;
1519 double x;
1520 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001521
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001522 if (le) {
1523 p += 3;
1524 incr = -1;
1525 }
1526
1527 /* First byte */
1528 sign = (*p >> 7) & 1;
1529 e = (*p & 0x7F) << 1;
1530 p += incr;
1531
1532 /* Second byte */
1533 e |= (*p >> 7) & 1;
1534 f = (*p & 0x7F) << 16;
1535 p += incr;
1536
1537 if (e == 255) {
1538 PyErr_SetString(
1539 PyExc_ValueError,
1540 "can't unpack IEEE 754 special value "
1541 "on non-IEEE platform");
1542 return -1;
1543 }
1544
1545 /* Third byte */
1546 f |= *p << 8;
1547 p += incr;
1548
1549 /* Fourth byte */
1550 f |= *p;
1551
1552 x = (double)f / 8388608.0;
1553
1554 /* XXX This sadly ignores Inf/NaN issues */
1555 if (e == 0)
1556 e = -126;
1557 else {
1558 x += 1.0;
1559 e -= 127;
1560 }
1561 x = ldexp(x, e);
1562
1563 if (sign)
1564 x = -x;
1565
1566 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001567 }
Tim Peters9905b942003-03-20 20:53:32 +00001568 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001569 float x;
1570
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001571 if ((float_format == ieee_little_endian_format && !le)
1572 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001573 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001574 char *d = &buf[3];
1575 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001576
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001577 for (i = 0; i < 4; i++) {
1578 *d-- = *p++;
1579 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001580 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581 }
1582 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001583 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001584 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001585
1586 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001587 }
Tim Peters9905b942003-03-20 20:53:32 +00001588}
1589
1590double
1591_PyFloat_Unpack8(const unsigned char *p, int le)
1592{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001593 if (double_format == unknown_format) {
1594 unsigned char sign;
1595 int e;
1596 unsigned int fhi, flo;
1597 double x;
1598 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001599
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001600 if (le) {
1601 p += 7;
1602 incr = -1;
1603 }
1604
1605 /* First byte */
1606 sign = (*p >> 7) & 1;
1607 e = (*p & 0x7F) << 4;
1608
1609 p += incr;
1610
1611 /* Second byte */
1612 e |= (*p >> 4) & 0xF;
1613 fhi = (*p & 0xF) << 24;
1614 p += incr;
1615
1616 if (e == 2047) {
1617 PyErr_SetString(
1618 PyExc_ValueError,
1619 "can't unpack IEEE 754 special value "
1620 "on non-IEEE platform");
1621 return -1.0;
1622 }
1623
1624 /* Third byte */
1625 fhi |= *p << 16;
1626 p += incr;
1627
1628 /* Fourth byte */
1629 fhi |= *p << 8;
1630 p += incr;
1631
1632 /* Fifth byte */
1633 fhi |= *p;
1634 p += incr;
1635
1636 /* Sixth byte */
1637 flo = *p << 16;
1638 p += incr;
1639
1640 /* Seventh byte */
1641 flo |= *p << 8;
1642 p += incr;
1643
1644 /* Eighth byte */
1645 flo |= *p;
1646
1647 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1648 x /= 268435456.0; /* 2**28 */
1649
1650 if (e == 0)
1651 e = -1022;
1652 else {
1653 x += 1.0;
1654 e -= 1023;
1655 }
1656 x = ldexp(x, e);
1657
1658 if (sign)
1659 x = -x;
1660
1661 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001662 }
Tim Peters9905b942003-03-20 20:53:32 +00001663 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001664 double x;
1665
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001666 if ((double_format == ieee_little_endian_format && !le)
1667 || (double_format == ieee_big_endian_format && le)) {
1668 char buf[8];
1669 char *d = &buf[7];
1670 int i;
1671
1672 for (i = 0; i < 8; i++) {
1673 *d-- = *p++;
1674 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001675 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676 }
1677 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001678 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001679 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001680
1681 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001682 }
Tim Peters9905b942003-03-20 20:53:32 +00001683}