blob: 09efa12c65d2436f15dfc9038dad11074ca3a980 [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))
Neal Norwitz447e7c32007-08-12 07:11:25 +000087 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +000088 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];
Guido van Rossum04dbf3b2007-08-07 19:51:00 +0000208 /* Subroutine for float_repr, float_str, 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 Rossumc0b618a1997-05-02 03:12:38 +0000289static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000290float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291{
292 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000293 format_float(buf, sizeof(buf), v, PREC_REPR);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000294 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000295}
296
297static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000298float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000299{
300 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000301 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000302 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303}
304
Tim Peters307fa782004-09-23 08:06:40 +0000305/* Comparison is pretty much a nightmare. When comparing float to float,
306 * we do it as straightforwardly (and long-windedly) as conceivable, so
307 * that, e.g., Python x == y delivers the same result as the platform
308 * C x == y when x and/or y is a NaN.
309 * When mixing float with an integer type, there's no good *uniform* approach.
310 * Converting the double to an integer obviously doesn't work, since we
311 * may lose info from fractional bits. Converting the integer to a double
312 * also has two failure modes: (1) a long int may trigger overflow (too
313 * large to fit in the dynamic range of a C double); (2) even a C long may have
314 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
315 * 63 bits of precision, but a C double probably has only 53), and then
316 * we can falsely claim equality when low-order integer bits are lost by
317 * coercion to double. So this part is painful too.
318 */
319
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000320static PyObject*
321float_richcompare(PyObject *v, PyObject *w, int op)
322{
323 double i, j;
324 int r = 0;
325
Tim Peters307fa782004-09-23 08:06:40 +0000326 assert(PyFloat_Check(v));
327 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000328
Tim Peters307fa782004-09-23 08:06:40 +0000329 /* Switch on the type of w. Set i and j to doubles to be compared,
330 * and op to the richcomp to use.
331 */
332 if (PyFloat_Check(w))
333 j = PyFloat_AS_DOUBLE(w);
334
Thomas Wouters477c8d52006-05-27 19:21:47 +0000335 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000336 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000337 /* If i is an infinity, its magnitude exceeds any
338 * finite integer, so it doesn't matter which int we
339 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000340 */
341 j = 0.0;
342 else
343 goto Unimplemented;
344 }
345
Tim Peters307fa782004-09-23 08:06:40 +0000346 else if (PyLong_Check(w)) {
347 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
348 int wsign = _PyLong_Sign(w);
349 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000350 int exponent;
351
352 if (vsign != wsign) {
353 /* Magnitudes are irrelevant -- the signs alone
354 * determine the outcome.
355 */
356 i = (double)vsign;
357 j = (double)wsign;
358 goto Compare;
359 }
360 /* The signs are the same. */
361 /* Convert w to a double if it fits. In particular, 0 fits. */
362 nbits = _PyLong_NumBits(w);
363 if (nbits == (size_t)-1 && PyErr_Occurred()) {
364 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000365 * to hold the # of bits. Replace with little doubles
366 * that give the same outcome -- w is so large that
367 * its magnitude must exceed the magnitude of any
368 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000369 */
370 PyErr_Clear();
371 i = (double)vsign;
372 assert(wsign != 0);
373 j = wsign * 2.0;
374 goto Compare;
375 }
376 if (nbits <= 48) {
377 j = PyLong_AsDouble(w);
378 /* It's impossible that <= 48 bits overflowed. */
379 assert(j != -1.0 || ! PyErr_Occurred());
380 goto Compare;
381 }
382 assert(wsign != 0); /* else nbits was 0 */
383 assert(vsign != 0); /* if vsign were 0, then since wsign is
384 * not 0, we would have taken the
385 * vsign != wsign branch at the start */
386 /* We want to work with non-negative numbers. */
387 if (vsign < 0) {
388 /* "Multiply both sides" by -1; this also swaps the
389 * comparator.
390 */
391 i = -i;
392 op = _Py_SwappedOp[op];
393 }
394 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000395 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000396 /* exponent is the # of bits in v before the radix point;
397 * we know that nbits (the # of bits in w) > 48 at this point
398 */
399 if (exponent < 0 || (size_t)exponent < nbits) {
400 i = 1.0;
401 j = 2.0;
402 goto Compare;
403 }
404 if ((size_t)exponent > nbits) {
405 i = 2.0;
406 j = 1.0;
407 goto Compare;
408 }
409 /* v and w have the same number of bits before the radix
410 * point. Construct two longs that have the same comparison
411 * outcome.
412 */
413 {
414 double fracpart;
415 double intpart;
416 PyObject *result = NULL;
417 PyObject *one = NULL;
418 PyObject *vv = NULL;
419 PyObject *ww = w;
420
421 if (wsign < 0) {
422 ww = PyNumber_Negative(w);
423 if (ww == NULL)
424 goto Error;
425 }
426 else
427 Py_INCREF(ww);
428
429 fracpart = modf(i, &intpart);
430 vv = PyLong_FromDouble(intpart);
431 if (vv == NULL)
432 goto Error;
433
434 if (fracpart != 0.0) {
435 /* Shift left, and or a 1 bit into vv
436 * to represent the lost fraction.
437 */
438 PyObject *temp;
439
440 one = PyInt_FromLong(1);
441 if (one == NULL)
442 goto Error;
443
444 temp = PyNumber_Lshift(ww, one);
445 if (temp == NULL)
446 goto Error;
447 Py_DECREF(ww);
448 ww = temp;
449
450 temp = PyNumber_Lshift(vv, one);
451 if (temp == NULL)
452 goto Error;
453 Py_DECREF(vv);
454 vv = temp;
455
456 temp = PyNumber_Or(vv, one);
457 if (temp == NULL)
458 goto Error;
459 Py_DECREF(vv);
460 vv = temp;
461 }
462
463 r = PyObject_RichCompareBool(vv, ww, op);
464 if (r < 0)
465 goto Error;
466 result = PyBool_FromLong(r);
467 Error:
468 Py_XDECREF(vv);
469 Py_XDECREF(ww);
470 Py_XDECREF(one);
471 return result;
472 }
473 } /* else if (PyLong_Check(w)) */
474
475 else /* w isn't float, int, or long */
476 goto Unimplemented;
477
478 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000479 PyFPE_START_PROTECT("richcompare", return NULL)
480 switch (op) {
481 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000482 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000483 break;
484 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000485 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000486 break;
487 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000488 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000489 break;
490 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000491 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000492 break;
493 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000494 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000495 break;
496 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000497 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000498 break;
499 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000500 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000501 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000502
503 Unimplemented:
504 Py_INCREF(Py_NotImplemented);
505 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000506}
507
Guido van Rossum9bfef441993-03-29 10:43:31 +0000508static long
Fred Drakefd99de62000-07-09 05:02:18 +0000509float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000510{
Tim Peters39dce292000-08-15 03:34:48 +0000511 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000512}
513
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000515float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000517 double a,b;
518 CONVERT_TO_DOUBLE(v, a);
519 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000520 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000521 a = a + b;
522 PyFPE_END_PROTECT(a)
523 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524}
525
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000527float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529 double a,b;
530 CONVERT_TO_DOUBLE(v, a);
531 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000532 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000533 a = a - b;
534 PyFPE_END_PROTECT(a)
535 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000536}
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000539float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541 double a,b;
542 CONVERT_TO_DOUBLE(v, a);
543 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000544 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000545 a = a * b;
546 PyFPE_END_PROTECT(a)
547 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548}
549
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000551float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000553 double a,b;
554 CONVERT_TO_DOUBLE(v, a);
555 CONVERT_TO_DOUBLE(w, b);
556 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558 return NULL;
559 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000560 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000561 a = a / b;
562 PyFPE_END_PROTECT(a)
563 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564}
565
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000567float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000569 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000570 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000571 CONVERT_TO_DOUBLE(v, vx);
572 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575 return NULL;
576 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000577 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000578 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000579 /* note: checking mod*wx < 0 is incorrect -- underflows to
580 0 if wx < sqrt(smallest nonzero double) */
581 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000582 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000583 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000584 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586}
587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000589float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000590{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000591 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000592 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000593 CONVERT_TO_DOUBLE(v, vx);
594 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000595 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000597 return NULL;
598 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000599 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000600 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000601 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000602 exact multiple of wx. But this is fp arithmetic, and fp
603 vx - mod is an approximation; the result is that div may
604 not be an exact integral value after the division, although
605 it will always be very close to one.
606 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000607 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000608 if (mod) {
609 /* ensure the remainder has the same sign as the denominator */
610 if ((wx < 0) != (mod < 0)) {
611 mod += wx;
612 div -= 1.0;
613 }
614 }
615 else {
616 /* the remainder is zero, and in the presence of signed zeroes
617 fmod returns different results across platforms; ensure
618 it has the same sign as the denominator; we'd like to do
619 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000620 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000621 if (wx < 0.0)
622 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000623 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000624 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000625 if (div) {
626 floordiv = floor(div);
627 if (div - floordiv > 0.5)
628 floordiv += 1.0;
629 }
630 else {
631 /* div is zero - get the same sign as the true quotient */
632 div *= div; /* hide "div = +0" from optimizers */
633 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
634 }
635 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000636 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000640float_floor_div(PyObject *v, PyObject *w)
641{
642 PyObject *t, *r;
643
644 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000645 if (t == NULL || t == Py_NotImplemented)
646 return t;
647 assert(PyTuple_CheckExact(t));
648 r = PyTuple_GET_ITEM(t, 0);
649 Py_INCREF(r);
650 Py_DECREF(t);
651 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000652}
653
654static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000655float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000656{
657 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000658
659 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000660 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000661 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000662 return NULL;
663 }
664
Neil Schemenauer32117e52001-01-04 01:44:34 +0000665 CONVERT_TO_DOUBLE(v, iv);
666 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000667
668 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000669 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000670 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000671 }
Tim Peters96685bf2001-08-23 22:31:37 +0000672 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000673 if (iw < 0.0) {
674 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000675 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000676 return NULL;
677 }
678 return PyFloat_FromDouble(0.0);
679 }
Tim Peterse87568d2003-05-24 20:18:24 +0000680 if (iv < 0.0) {
681 /* Whether this is an error is a mess, and bumps into libm
682 * bugs so we have to figure it out ourselves.
683 */
684 if (iw != floor(iw)) {
685 PyErr_SetString(PyExc_ValueError, "negative number "
686 "cannot be raised to a fractional power");
687 return NULL;
688 }
689 /* iw is an exact integer, albeit perhaps a very large one.
690 * -1 raised to an exact integer should never be exceptional.
691 * Alas, some libms (chiefly glibc as of early 2003) return
692 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
693 * happen to be representable in a *C* integer. That's a
694 * bug; we let that slide in math.pow() (which currently
695 * reflects all platform accidents), but not for Python's **.
696 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000697 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000698 /* Return 1 if iw is even, -1 if iw is odd; there's
699 * no guarantee that any C integral type is big
700 * enough to hold iw, so we have to check this
701 * indirectly.
702 */
703 ix = floor(iw * 0.5) * 2.0;
704 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
705 }
706 /* Else iv != -1.0, and overflow or underflow are possible.
707 * Unless we're to write pow() ourselves, we have to trust
708 * the platform to do this correctly.
709 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000710 }
Tim Peters96685bf2001-08-23 22:31:37 +0000711 errno = 0;
712 PyFPE_START_PROTECT("pow", return NULL)
713 ix = pow(iv, iw);
714 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000715 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000716 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000717 /* We don't expect any errno value other than ERANGE, but
718 * the range of libm bugs appears unbounded.
719 */
720 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
721 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000723 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000725}
726
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000728float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000730 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731}
732
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000733static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000734float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000735{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000736 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737}
738
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000739static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000740float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000741{
742 return v->ob_fval != 0.0;
743}
744
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000745static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000746float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000747{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000749 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000750
751 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000752 /* Try to get out cheap if this fits in a Python int. The attempt
753 * to cast to long must be protected, as C doesn't define what
754 * happens if the double is too big to fit in a long. Some rare
755 * systems raise an exception then (RISCOS was mentioned as one,
756 * and someone using a non-default option on Sun also bumped into
757 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
758 * still be vulnerable: if a long has more bits of precision than
759 * a double, casting MIN/MAX to double may yield an approximation,
760 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
761 * yield true from the C expression wholepart<=LONG_MAX, despite
762 * that wholepart is actually greater than LONG_MAX.
763 */
764 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
765 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000766 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000767 }
768 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000769}
770
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000772float_round(PyObject *v, PyObject *args)
773{
774#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
775 double x;
776 double f;
777 double flr, cil;
778 double rounded;
779 int i;
780 int ndigits = UNDEF_NDIGITS;
781
782 if (!PyArg_ParseTuple(args, "|i", &ndigits))
783 return NULL;
784
785 x = PyFloat_AsDouble(v);
786
787 if (ndigits != UNDEF_NDIGITS) {
788 f = 1.0;
789 i = abs(ndigits);
790 while (--i >= 0)
791 f = f*10.0;
792 if (ndigits < 0)
793 x /= f;
794 else
795 x *= f;
796 }
797
798 flr = floor(x);
799 cil = ceil(x);
800
801 if (x-flr > 0.5)
802 rounded = cil;
803 else if (x-flr == 0.5)
804 rounded = fmod(flr, 2) == 0 ? flr : cil;
805 else
806 rounded = flr;
807
808 if (ndigits != UNDEF_NDIGITS) {
809 if (ndigits < 0)
810 rounded *= f;
811 else
812 rounded /= f;
813 return PyFloat_FromDouble(rounded);
814 }
815
816 return PyLong_FromDouble(rounded);
817#undef UNDEF_NDIGITS
818}
819
820static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000821float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000822{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000823 if (PyFloat_CheckExact(v))
824 Py_INCREF(v);
825 else
826 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000827 return v;
828}
829
830
Jeremy Hylton938ace62002-07-17 16:30:39 +0000831static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000832float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
833
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834static PyObject *
835float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
836{
837 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000838 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839
Guido van Rossumbef14172001-08-29 15:47:46 +0000840 if (type != &PyFloat_Type)
841 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
843 return NULL;
844 if (PyString_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000845 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846 return PyNumber_Float(x);
847}
848
Guido van Rossumbef14172001-08-29 15:47:46 +0000849/* Wimpy, slow approach to tp_new calls for subtypes of float:
850 first create a regular float from whatever arguments we got,
851 then allocate a subtype instance and initialize its ob_fval
852 from the regular float. The regular float is then thrown away.
853*/
854static PyObject *
855float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
856{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000858
859 assert(PyType_IsSubtype(type, &PyFloat_Type));
860 tmp = float_new(&PyFloat_Type, args, kwds);
861 if (tmp == NULL)
862 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000863 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000864 newobj = type->tp_alloc(type, 0);
865 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000866 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000867 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000868 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000869 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000870 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000871 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000872}
873
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000874static PyObject *
875float_getnewargs(PyFloatObject *v)
876{
877 return Py_BuildValue("(d)", v->ob_fval);
878}
879
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000880/* this is for the benefit of the pack/unpack routines below */
881
882typedef enum {
883 unknown_format, ieee_big_endian_format, ieee_little_endian_format
884} float_format_type;
885
886static float_format_type double_format, float_format;
887static float_format_type detected_double_format, detected_float_format;
888
889static PyObject *
890float_getformat(PyTypeObject *v, PyObject* arg)
891{
892 char* s;
893 float_format_type r;
894
Guido van Rossum2be161d2007-05-15 20:43:51 +0000895 if (PyUnicode_Check(arg)) {
896 arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
897 if (arg == NULL)
898 return NULL;
899 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000900 if (!PyString_Check(arg)) {
901 PyErr_Format(PyExc_TypeError,
902 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000903 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000904 return NULL;
905 }
906 s = PyString_AS_STRING(arg);
907 if (strcmp(s, "double") == 0) {
908 r = double_format;
909 }
910 else if (strcmp(s, "float") == 0) {
911 r = float_format;
912 }
913 else {
914 PyErr_SetString(PyExc_ValueError,
915 "__getformat__() argument 1 must be "
916 "'double' or 'float'");
917 return NULL;
918 }
919
920 switch (r) {
921 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000922 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000923 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000924 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000925 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000926 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000927 default:
928 Py_FatalError("insane float_format or double_format");
929 return NULL;
930 }
931}
932
933PyDoc_STRVAR(float_getformat_doc,
934"float.__getformat__(typestr) -> string\n"
935"\n"
936"You probably don't want to use this function. It exists mainly to be\n"
937"used in Python's test suite.\n"
938"\n"
939"typestr must be 'double' or 'float'. This function returns whichever of\n"
940"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
941"format of floating point numbers used by the C type named by typestr.");
942
943static PyObject *
944float_setformat(PyTypeObject *v, PyObject* args)
945{
946 char* typestr;
947 char* format;
948 float_format_type f;
949 float_format_type detected;
950 float_format_type *p;
951
952 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
953 return NULL;
954
955 if (strcmp(typestr, "double") == 0) {
956 p = &double_format;
957 detected = detected_double_format;
958 }
959 else if (strcmp(typestr, "float") == 0) {
960 p = &float_format;
961 detected = detected_float_format;
962 }
963 else {
964 PyErr_SetString(PyExc_ValueError,
965 "__setformat__() argument 1 must "
966 "be 'double' or 'float'");
967 return NULL;
968 }
969
970 if (strcmp(format, "unknown") == 0) {
971 f = unknown_format;
972 }
973 else if (strcmp(format, "IEEE, little-endian") == 0) {
974 f = ieee_little_endian_format;
975 }
976 else if (strcmp(format, "IEEE, big-endian") == 0) {
977 f = ieee_big_endian_format;
978 }
979 else {
980 PyErr_SetString(PyExc_ValueError,
981 "__setformat__() argument 2 must be "
982 "'unknown', 'IEEE, little-endian' or "
983 "'IEEE, big-endian'");
984 return NULL;
985
986 }
987
988 if (f != unknown_format && f != detected) {
989 PyErr_Format(PyExc_ValueError,
990 "can only set %s format to 'unknown' or the "
991 "detected platform value", typestr);
992 return NULL;
993 }
994
995 *p = f;
996 Py_RETURN_NONE;
997}
998
999PyDoc_STRVAR(float_setformat_doc,
1000"float.__setformat__(typestr, fmt) -> None\n"
1001"\n"
1002"You probably don't want to use this function. It exists mainly to be\n"
1003"used in Python's test suite.\n"
1004"\n"
1005"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1006"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1007"one of the latter two if it appears to match the underlying C reality.\n"
1008"\n"
1009"Overrides the automatic determination of C-level floating point type.\n"
1010"This affects how floats are converted to and from binary strings.");
1011
Guido van Rossumb43daf72007-08-01 18:08:08 +00001012static PyObject *
1013float_getzero(PyObject *v, void *closure)
1014{
1015 return PyFloat_FromDouble(0.0);
1016}
1017
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001018static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001019 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1020 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001021 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1022 "Returns the Integral closest to x between 0 and x."},
1023 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1024 "Returns the Integral closest to x, rounding half toward even.\n"
1025 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001026 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001027 {"__getformat__", (PyCFunction)float_getformat,
1028 METH_O|METH_CLASS, float_getformat_doc},
1029 {"__setformat__", (PyCFunction)float_setformat,
1030 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001031 {NULL, NULL} /* sentinel */
1032};
1033
Guido van Rossumb43daf72007-08-01 18:08:08 +00001034static PyGetSetDef float_getset[] = {
1035 {"real",
1036 (getter)float_float, (setter)NULL,
1037 "the real part of a complex number",
1038 NULL},
1039 {"imag",
1040 (getter)float_getzero, (setter)NULL,
1041 "the imaginary part of a complex number",
1042 NULL},
1043 {NULL} /* Sentinel */
1044};
1045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001046PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047"float(x) -> floating point number\n\
1048\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001049Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050
1051
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001052static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001053 float_add, /*nb_add*/
1054 float_sub, /*nb_subtract*/
1055 float_mul, /*nb_multiply*/
1056 float_rem, /*nb_remainder*/
1057 float_divmod, /*nb_divmod*/
1058 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001059 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001060 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001061 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001062 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001063 0, /*nb_invert*/
1064 0, /*nb_lshift*/
1065 0, /*nb_rshift*/
1066 0, /*nb_and*/
1067 0, /*nb_xor*/
1068 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001069 (coercion)0, /*nb_coerce*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001070 float_trunc, /*nb_int*/
1071 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001072 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001073 0, /* nb_oct */
1074 0, /* nb_hex */
1075 0, /* nb_inplace_add */
1076 0, /* nb_inplace_subtract */
1077 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001078 0, /* nb_inplace_remainder */
1079 0, /* nb_inplace_power */
1080 0, /* nb_inplace_lshift */
1081 0, /* nb_inplace_rshift */
1082 0, /* nb_inplace_and */
1083 0, /* nb_inplace_xor */
1084 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001085 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001086 float_div, /* nb_true_divide */
1087 0, /* nb_inplace_floor_divide */
1088 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001089};
1090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001091PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001092 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001093 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001094 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001095 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001097 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098 0, /* tp_getattr */
1099 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001100 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 (reprfunc)float_repr, /* tp_repr */
1102 &float_as_number, /* tp_as_number */
1103 0, /* tp_as_sequence */
1104 0, /* tp_as_mapping */
1105 (hashfunc)float_hash, /* tp_hash */
1106 0, /* tp_call */
1107 (reprfunc)float_str, /* tp_str */
1108 PyObject_GenericGetAttr, /* tp_getattro */
1109 0, /* tp_setattro */
1110 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001111 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 float_doc, /* tp_doc */
1113 0, /* tp_traverse */
1114 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001115 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 0, /* tp_weaklistoffset */
1117 0, /* tp_iter */
1118 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001119 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001121 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 0, /* tp_base */
1123 0, /* tp_dict */
1124 0, /* tp_descr_get */
1125 0, /* tp_descr_set */
1126 0, /* tp_dictoffset */
1127 0, /* tp_init */
1128 0, /* tp_alloc */
1129 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001130};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001131
1132void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001133_PyFloat_Init(void)
1134{
1135 /* We attempt to determine if this machine is using IEEE
1136 floating point formats by peering at the bits of some
1137 carefully chosen values. If it looks like we are on an
1138 IEEE platform, the float packing/unpacking routines can
1139 just copy bits, if not they resort to arithmetic & shifts
1140 and masks. The shifts & masks approach works on all finite
1141 values, but what happens to infinities, NaNs and signed
1142 zeroes on packing is an accident, and attempting to unpack
1143 a NaN or an infinity will raise an exception.
1144
1145 Note that if we're on some whacked-out platform which uses
1146 IEEE formats but isn't strictly little-endian or big-
1147 endian, we will fall back to the portable shifts & masks
1148 method. */
1149
1150#if SIZEOF_DOUBLE == 8
1151 {
1152 double x = 9006104071832581.0;
1153 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1154 detected_double_format = ieee_big_endian_format;
1155 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1156 detected_double_format = ieee_little_endian_format;
1157 else
1158 detected_double_format = unknown_format;
1159 }
1160#else
1161 detected_double_format = unknown_format;
1162#endif
1163
1164#if SIZEOF_FLOAT == 4
1165 {
1166 float y = 16711938.0;
1167 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1168 detected_float_format = ieee_big_endian_format;
1169 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1170 detected_float_format = ieee_little_endian_format;
1171 else
1172 detected_float_format = unknown_format;
1173 }
1174#else
1175 detected_float_format = unknown_format;
1176#endif
1177
1178 double_format = detected_double_format;
1179 float_format = detected_float_format;
1180}
1181
1182void
Fred Drakefd99de62000-07-09 05:02:18 +00001183PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001184{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001185 PyFloatObject *p;
1186 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001187 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001188 int bc, bf; /* block count, number of freed blocks */
1189 int frem, fsum; /* remaining unfreed floats per block, total */
1190
1191 bc = 0;
1192 bf = 0;
1193 fsum = 0;
1194 list = block_list;
1195 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001196 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001197 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001198 bc++;
1199 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001200 for (i = 0, p = &list->objects[0];
1201 i < N_FLOATOBJECTS;
1202 i++, p++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001203 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001204 frem++;
1205 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001206 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001207 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001208 list->next = block_list;
1209 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001210 for (i = 0, p = &list->objects[0];
1211 i < N_FLOATOBJECTS;
1212 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001213 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001214 Py_Refcnt(p) == 0) {
1215 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001216 free_list;
1217 free_list = p;
1218 }
1219 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001220 }
1221 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001222 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001223 bf++;
1224 }
1225 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001226 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001227 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001228 if (!Py_VerboseFlag)
1229 return;
1230 fprintf(stderr, "# cleanup floats");
1231 if (!fsum) {
1232 fprintf(stderr, "\n");
1233 }
1234 else {
1235 fprintf(stderr,
1236 ": %d unfreed float%s in %d out of %d block%s\n",
1237 fsum, fsum == 1 ? "" : "s",
1238 bc - bf, bc, bc == 1 ? "" : "s");
1239 }
1240 if (Py_VerboseFlag > 1) {
1241 list = block_list;
1242 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001243 for (i = 0, p = &list->objects[0];
1244 i < N_FLOATOBJECTS;
1245 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001246 if (PyFloat_CheckExact(p) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001247 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001248 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001249 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001250 /* XXX(twouters) cast refcount to
1251 long until %zd is universally
1252 available
1253 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001254 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001255 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001256 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001257 }
1258 }
1259 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001260 }
1261 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001262}
Tim Peters9905b942003-03-20 20:53:32 +00001263
1264/*----------------------------------------------------------------------------
1265 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1266 *
1267 * TODO: On platforms that use the standard IEEE-754 single and double
1268 * formats natively, these routines could simply copy the bytes.
1269 */
1270int
1271_PyFloat_Pack4(double x, unsigned char *p, int le)
1272{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001273 if (float_format == unknown_format) {
1274 unsigned char sign;
1275 int e;
1276 double f;
1277 unsigned int fbits;
1278 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001279
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001280 if (le) {
1281 p += 3;
1282 incr = -1;
1283 }
Tim Peters9905b942003-03-20 20:53:32 +00001284
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001285 if (x < 0) {
1286 sign = 1;
1287 x = -x;
1288 }
1289 else
1290 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001291
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001292 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001293
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001294 /* Normalize f to be in the range [1.0, 2.0) */
1295 if (0.5 <= f && f < 1.0) {
1296 f *= 2.0;
1297 e--;
1298 }
1299 else if (f == 0.0)
1300 e = 0;
1301 else {
1302 PyErr_SetString(PyExc_SystemError,
1303 "frexp() result out of range");
1304 return -1;
1305 }
1306
1307 if (e >= 128)
1308 goto Overflow;
1309 else if (e < -126) {
1310 /* Gradual underflow */
1311 f = ldexp(f, 126 + e);
1312 e = 0;
1313 }
1314 else if (!(e == 0 && f == 0.0)) {
1315 e += 127;
1316 f -= 1.0; /* Get rid of leading 1 */
1317 }
1318
1319 f *= 8388608.0; /* 2**23 */
1320 fbits = (unsigned int)(f + 0.5); /* Round */
1321 assert(fbits <= 8388608);
1322 if (fbits >> 23) {
1323 /* The carry propagated out of a string of 23 1 bits. */
1324 fbits = 0;
1325 ++e;
1326 if (e >= 255)
1327 goto Overflow;
1328 }
1329
1330 /* First byte */
1331 *p = (sign << 7) | (e >> 1);
1332 p += incr;
1333
1334 /* Second byte */
1335 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1336 p += incr;
1337
1338 /* Third byte */
1339 *p = (fbits >> 8) & 0xFF;
1340 p += incr;
1341
1342 /* Fourth byte */
1343 *p = fbits & 0xFF;
1344
1345 /* Done */
1346 return 0;
1347
1348 Overflow:
1349 PyErr_SetString(PyExc_OverflowError,
1350 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001351 return -1;
1352 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001353 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001354 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001355 const char *s = (char*)&y;
1356 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001357
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001358 if ((float_format == ieee_little_endian_format && !le)
1359 || (float_format == ieee_big_endian_format && le)) {
1360 p += 3;
1361 incr = -1;
1362 }
1363
1364 for (i = 0; i < 4; i++) {
1365 *p = *s++;
1366 p += incr;
1367 }
1368 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001369 }
Tim Peters9905b942003-03-20 20:53:32 +00001370}
1371
1372int
1373_PyFloat_Pack8(double x, unsigned char *p, int le)
1374{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001375 if (double_format == unknown_format) {
1376 unsigned char sign;
1377 int e;
1378 double f;
1379 unsigned int fhi, flo;
1380 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001381
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001382 if (le) {
1383 p += 7;
1384 incr = -1;
1385 }
Tim Peters9905b942003-03-20 20:53:32 +00001386
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001387 if (x < 0) {
1388 sign = 1;
1389 x = -x;
1390 }
1391 else
1392 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001393
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001394 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001395
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001396 /* Normalize f to be in the range [1.0, 2.0) */
1397 if (0.5 <= f && f < 1.0) {
1398 f *= 2.0;
1399 e--;
1400 }
1401 else if (f == 0.0)
1402 e = 0;
1403 else {
1404 PyErr_SetString(PyExc_SystemError,
1405 "frexp() result out of range");
1406 return -1;
1407 }
1408
1409 if (e >= 1024)
1410 goto Overflow;
1411 else if (e < -1022) {
1412 /* Gradual underflow */
1413 f = ldexp(f, 1022 + e);
1414 e = 0;
1415 }
1416 else if (!(e == 0 && f == 0.0)) {
1417 e += 1023;
1418 f -= 1.0; /* Get rid of leading 1 */
1419 }
1420
1421 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1422 f *= 268435456.0; /* 2**28 */
1423 fhi = (unsigned int)f; /* Truncate */
1424 assert(fhi < 268435456);
1425
1426 f -= (double)fhi;
1427 f *= 16777216.0; /* 2**24 */
1428 flo = (unsigned int)(f + 0.5); /* Round */
1429 assert(flo <= 16777216);
1430 if (flo >> 24) {
1431 /* The carry propagated out of a string of 24 1 bits. */
1432 flo = 0;
1433 ++fhi;
1434 if (fhi >> 28) {
1435 /* And it also progagated out of the next 28 bits. */
1436 fhi = 0;
1437 ++e;
1438 if (e >= 2047)
1439 goto Overflow;
1440 }
1441 }
1442
1443 /* First byte */
1444 *p = (sign << 7) | (e >> 4);
1445 p += incr;
1446
1447 /* Second byte */
1448 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1449 p += incr;
1450
1451 /* Third byte */
1452 *p = (fhi >> 16) & 0xFF;
1453 p += incr;
1454
1455 /* Fourth byte */
1456 *p = (fhi >> 8) & 0xFF;
1457 p += incr;
1458
1459 /* Fifth byte */
1460 *p = fhi & 0xFF;
1461 p += incr;
1462
1463 /* Sixth byte */
1464 *p = (flo >> 16) & 0xFF;
1465 p += incr;
1466
1467 /* Seventh byte */
1468 *p = (flo >> 8) & 0xFF;
1469 p += incr;
1470
1471 /* Eighth byte */
1472 *p = flo & 0xFF;
1473 p += incr;
1474
1475 /* Done */
1476 return 0;
1477
1478 Overflow:
1479 PyErr_SetString(PyExc_OverflowError,
1480 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001481 return -1;
1482 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001483 else {
1484 const char *s = (char*)&x;
1485 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001486
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001487 if ((double_format == ieee_little_endian_format && !le)
1488 || (double_format == ieee_big_endian_format && le)) {
1489 p += 7;
1490 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001491 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001492
1493 for (i = 0; i < 8; i++) {
1494 *p = *s++;
1495 p += incr;
1496 }
1497 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001498 }
Tim Peters9905b942003-03-20 20:53:32 +00001499}
1500
Neal Norwitz545686b2006-12-28 04:45:06 +00001501/* Should only be used by marshal. */
1502int
1503_PyFloat_Repr(double x, char *p, size_t len)
1504{
1505 format_double(p, len, x, PREC_REPR);
1506 return (int)strlen(p);
1507}
1508
Tim Peters9905b942003-03-20 20:53:32 +00001509double
1510_PyFloat_Unpack4(const unsigned char *p, int le)
1511{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001512 if (float_format == unknown_format) {
1513 unsigned char sign;
1514 int e;
1515 unsigned int f;
1516 double x;
1517 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001518
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001519 if (le) {
1520 p += 3;
1521 incr = -1;
1522 }
1523
1524 /* First byte */
1525 sign = (*p >> 7) & 1;
1526 e = (*p & 0x7F) << 1;
1527 p += incr;
1528
1529 /* Second byte */
1530 e |= (*p >> 7) & 1;
1531 f = (*p & 0x7F) << 16;
1532 p += incr;
1533
1534 if (e == 255) {
1535 PyErr_SetString(
1536 PyExc_ValueError,
1537 "can't unpack IEEE 754 special value "
1538 "on non-IEEE platform");
1539 return -1;
1540 }
1541
1542 /* Third byte */
1543 f |= *p << 8;
1544 p += incr;
1545
1546 /* Fourth byte */
1547 f |= *p;
1548
1549 x = (double)f / 8388608.0;
1550
1551 /* XXX This sadly ignores Inf/NaN issues */
1552 if (e == 0)
1553 e = -126;
1554 else {
1555 x += 1.0;
1556 e -= 127;
1557 }
1558 x = ldexp(x, e);
1559
1560 if (sign)
1561 x = -x;
1562
1563 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001564 }
Tim Peters9905b942003-03-20 20:53:32 +00001565 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001566 float x;
1567
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001568 if ((float_format == ieee_little_endian_format && !le)
1569 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001570 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001571 char *d = &buf[3];
1572 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001573
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001574 for (i = 0; i < 4; i++) {
1575 *d-- = *p++;
1576 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001577 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001578 }
1579 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001580 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001582
1583 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001584 }
Tim Peters9905b942003-03-20 20:53:32 +00001585}
1586
1587double
1588_PyFloat_Unpack8(const unsigned char *p, int le)
1589{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001590 if (double_format == unknown_format) {
1591 unsigned char sign;
1592 int e;
1593 unsigned int fhi, flo;
1594 double x;
1595 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001596
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597 if (le) {
1598 p += 7;
1599 incr = -1;
1600 }
1601
1602 /* First byte */
1603 sign = (*p >> 7) & 1;
1604 e = (*p & 0x7F) << 4;
1605
1606 p += incr;
1607
1608 /* Second byte */
1609 e |= (*p >> 4) & 0xF;
1610 fhi = (*p & 0xF) << 24;
1611 p += incr;
1612
1613 if (e == 2047) {
1614 PyErr_SetString(
1615 PyExc_ValueError,
1616 "can't unpack IEEE 754 special value "
1617 "on non-IEEE platform");
1618 return -1.0;
1619 }
1620
1621 /* Third byte */
1622 fhi |= *p << 16;
1623 p += incr;
1624
1625 /* Fourth byte */
1626 fhi |= *p << 8;
1627 p += incr;
1628
1629 /* Fifth byte */
1630 fhi |= *p;
1631 p += incr;
1632
1633 /* Sixth byte */
1634 flo = *p << 16;
1635 p += incr;
1636
1637 /* Seventh byte */
1638 flo |= *p << 8;
1639 p += incr;
1640
1641 /* Eighth byte */
1642 flo |= *p;
1643
1644 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1645 x /= 268435456.0; /* 2**28 */
1646
1647 if (e == 0)
1648 e = -1022;
1649 else {
1650 x += 1.0;
1651 e -= 1023;
1652 }
1653 x = ldexp(x, e);
1654
1655 if (sign)
1656 x = -x;
1657
1658 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001659 }
Tim Peters9905b942003-03-20 20:53:32 +00001660 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001661 double x;
1662
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001663 if ((double_format == ieee_little_endian_format && !le)
1664 || (double_format == ieee_big_endian_format && le)) {
1665 char buf[8];
1666 char *d = &buf[7];
1667 int i;
1668
1669 for (i = 0; i < 8; i++) {
1670 *d-- = *p++;
1671 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001672 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673 }
1674 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001675 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001676 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001677
1678 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001679 }
Tim Peters9905b942003-03-20 20:53:32 +00001680}