blob: 908258cb3a69fd47a9f92b1aa5ed7ae42e02c8d5 [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 *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000746float_long(PyObject *v)
747{
748 double x = PyFloat_AsDouble(v);
749 return PyLong_FromDouble(x);
750}
751
752static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000753float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000754{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000756 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000757
758 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000759 /* Try to get out cheap if this fits in a Python int. The attempt
760 * to cast to long must be protected, as C doesn't define what
761 * happens if the double is too big to fit in a long. Some rare
762 * systems raise an exception then (RISCOS was mentioned as one,
763 * and someone using a non-default option on Sun also bumped into
764 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
765 * still be vulnerable: if a long has more bits of precision than
766 * a double, casting MIN/MAX to double may yield an approximation,
767 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
768 * yield true from the C expression wholepart<=LONG_MAX, despite
769 * that wholepart is actually greater than LONG_MAX.
770 */
771 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
772 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000773 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000774 }
775 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000779float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000780{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000781 if (PyFloat_CheckExact(v))
782 Py_INCREF(v);
783 else
784 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000785 return v;
786}
787
788
Jeremy Hylton938ace62002-07-17 16:30:39 +0000789static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000790float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
791
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792static PyObject *
793float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
794{
795 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000796 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797
Guido van Rossumbef14172001-08-29 15:47:46 +0000798 if (type != &PyFloat_Type)
799 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
801 return NULL;
802 if (PyString_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +0000803 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000804 return PyNumber_Float(x);
805}
806
Guido van Rossumbef14172001-08-29 15:47:46 +0000807/* Wimpy, slow approach to tp_new calls for subtypes of float:
808 first create a regular float from whatever arguments we got,
809 then allocate a subtype instance and initialize its ob_fval
810 from the regular float. The regular float is then thrown away.
811*/
812static PyObject *
813float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
814{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000816
817 assert(PyType_IsSubtype(type, &PyFloat_Type));
818 tmp = float_new(&PyFloat_Type, args, kwds);
819 if (tmp == NULL)
820 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000821 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822 newobj = type->tp_alloc(type, 0);
823 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000824 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000825 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000826 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000827 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000828 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000829 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000830}
831
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000832static PyObject *
833float_getnewargs(PyFloatObject *v)
834{
835 return Py_BuildValue("(d)", v->ob_fval);
836}
837
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000838/* this is for the benefit of the pack/unpack routines below */
839
840typedef enum {
841 unknown_format, ieee_big_endian_format, ieee_little_endian_format
842} float_format_type;
843
844static float_format_type double_format, float_format;
845static float_format_type detected_double_format, detected_float_format;
846
847static PyObject *
848float_getformat(PyTypeObject *v, PyObject* arg)
849{
850 char* s;
851 float_format_type r;
852
Guido van Rossum2be161d2007-05-15 20:43:51 +0000853 if (PyUnicode_Check(arg)) {
854 arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
855 if (arg == NULL)
856 return NULL;
857 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000858 if (!PyString_Check(arg)) {
859 PyErr_Format(PyExc_TypeError,
860 "__getformat__() argument must be string, not %.500s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000861 Py_Type(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000862 return NULL;
863 }
864 s = PyString_AS_STRING(arg);
865 if (strcmp(s, "double") == 0) {
866 r = double_format;
867 }
868 else if (strcmp(s, "float") == 0) {
869 r = float_format;
870 }
871 else {
872 PyErr_SetString(PyExc_ValueError,
873 "__getformat__() argument 1 must be "
874 "'double' or 'float'");
875 return NULL;
876 }
877
878 switch (r) {
879 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000880 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000881 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000882 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000883 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +0000884 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000885 default:
886 Py_FatalError("insane float_format or double_format");
887 return NULL;
888 }
889}
890
891PyDoc_STRVAR(float_getformat_doc,
892"float.__getformat__(typestr) -> string\n"
893"\n"
894"You probably don't want to use this function. It exists mainly to be\n"
895"used in Python's test suite.\n"
896"\n"
897"typestr must be 'double' or 'float'. This function returns whichever of\n"
898"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
899"format of floating point numbers used by the C type named by typestr.");
900
901static PyObject *
902float_setformat(PyTypeObject *v, PyObject* args)
903{
904 char* typestr;
905 char* format;
906 float_format_type f;
907 float_format_type detected;
908 float_format_type *p;
909
910 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
911 return NULL;
912
913 if (strcmp(typestr, "double") == 0) {
914 p = &double_format;
915 detected = detected_double_format;
916 }
917 else if (strcmp(typestr, "float") == 0) {
918 p = &float_format;
919 detected = detected_float_format;
920 }
921 else {
922 PyErr_SetString(PyExc_ValueError,
923 "__setformat__() argument 1 must "
924 "be 'double' or 'float'");
925 return NULL;
926 }
927
928 if (strcmp(format, "unknown") == 0) {
929 f = unknown_format;
930 }
931 else if (strcmp(format, "IEEE, little-endian") == 0) {
932 f = ieee_little_endian_format;
933 }
934 else if (strcmp(format, "IEEE, big-endian") == 0) {
935 f = ieee_big_endian_format;
936 }
937 else {
938 PyErr_SetString(PyExc_ValueError,
939 "__setformat__() argument 2 must be "
940 "'unknown', 'IEEE, little-endian' or "
941 "'IEEE, big-endian'");
942 return NULL;
943
944 }
945
946 if (f != unknown_format && f != detected) {
947 PyErr_Format(PyExc_ValueError,
948 "can only set %s format to 'unknown' or the "
949 "detected platform value", typestr);
950 return NULL;
951 }
952
953 *p = f;
954 Py_RETURN_NONE;
955}
956
957PyDoc_STRVAR(float_setformat_doc,
958"float.__setformat__(typestr, fmt) -> None\n"
959"\n"
960"You probably don't want to use this function. It exists mainly to be\n"
961"used in Python's test suite.\n"
962"\n"
963"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
964"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
965"one of the latter two if it appears to match the underlying C reality.\n"
966"\n"
967"Overrides the automatic determination of C-level floating point type.\n"
968"This affects how floats are converted to and from binary strings.");
969
Guido van Rossumb43daf72007-08-01 18:08:08 +0000970static PyObject *
971float_getzero(PyObject *v, void *closure)
972{
973 return PyFloat_FromDouble(0.0);
974}
975
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000976static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +0000977 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
978 "Returns self, the complex conjugate of any float."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000979 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000980 {"__getformat__", (PyCFunction)float_getformat,
981 METH_O|METH_CLASS, float_getformat_doc},
982 {"__setformat__", (PyCFunction)float_setformat,
983 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000984 {NULL, NULL} /* sentinel */
985};
986
Guido van Rossumb43daf72007-08-01 18:08:08 +0000987static PyGetSetDef float_getset[] = {
988 {"real",
989 (getter)float_float, (setter)NULL,
990 "the real part of a complex number",
991 NULL},
992 {"imag",
993 (getter)float_getzero, (setter)NULL,
994 "the imaginary part of a complex number",
995 NULL},
996 {NULL} /* Sentinel */
997};
998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000999PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000"float(x) -> floating point number\n\
1001\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001002Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003
1004
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001005static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001006 float_add, /*nb_add*/
1007 float_sub, /*nb_subtract*/
1008 float_mul, /*nb_multiply*/
1009 float_rem, /*nb_remainder*/
1010 float_divmod, /*nb_divmod*/
1011 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001012 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001013 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001014 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001015 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001016 0, /*nb_invert*/
1017 0, /*nb_lshift*/
1018 0, /*nb_rshift*/
1019 0, /*nb_and*/
1020 0, /*nb_xor*/
1021 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001022 (coercion)0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001023 float_int, /*nb_int*/
1024 float_long, /*nb_long*/
1025 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001026 0, /* nb_oct */
1027 0, /* nb_hex */
1028 0, /* nb_inplace_add */
1029 0, /* nb_inplace_subtract */
1030 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001031 0, /* nb_inplace_remainder */
1032 0, /* nb_inplace_power */
1033 0, /* nb_inplace_lshift */
1034 0, /* nb_inplace_rshift */
1035 0, /* nb_inplace_and */
1036 0, /* nb_inplace_xor */
1037 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001038 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001039 float_div, /* nb_true_divide */
1040 0, /* nb_inplace_floor_divide */
1041 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001042};
1043
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001044PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001045 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001046 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001047 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001048 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001050 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051 0, /* tp_getattr */
1052 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001053 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 (reprfunc)float_repr, /* tp_repr */
1055 &float_as_number, /* tp_as_number */
1056 0, /* tp_as_sequence */
1057 0, /* tp_as_mapping */
1058 (hashfunc)float_hash, /* tp_hash */
1059 0, /* tp_call */
1060 (reprfunc)float_str, /* tp_str */
1061 PyObject_GenericGetAttr, /* tp_getattro */
1062 0, /* tp_setattro */
1063 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001064 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001065 float_doc, /* tp_doc */
1066 0, /* tp_traverse */
1067 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001068 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069 0, /* tp_weaklistoffset */
1070 0, /* tp_iter */
1071 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001072 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001074 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 0, /* tp_base */
1076 0, /* tp_dict */
1077 0, /* tp_descr_get */
1078 0, /* tp_descr_set */
1079 0, /* tp_dictoffset */
1080 0, /* tp_init */
1081 0, /* tp_alloc */
1082 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001083};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001084
1085void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001086_PyFloat_Init(void)
1087{
1088 /* We attempt to determine if this machine is using IEEE
1089 floating point formats by peering at the bits of some
1090 carefully chosen values. If it looks like we are on an
1091 IEEE platform, the float packing/unpacking routines can
1092 just copy bits, if not they resort to arithmetic & shifts
1093 and masks. The shifts & masks approach works on all finite
1094 values, but what happens to infinities, NaNs and signed
1095 zeroes on packing is an accident, and attempting to unpack
1096 a NaN or an infinity will raise an exception.
1097
1098 Note that if we're on some whacked-out platform which uses
1099 IEEE formats but isn't strictly little-endian or big-
1100 endian, we will fall back to the portable shifts & masks
1101 method. */
1102
1103#if SIZEOF_DOUBLE == 8
1104 {
1105 double x = 9006104071832581.0;
1106 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1107 detected_double_format = ieee_big_endian_format;
1108 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1109 detected_double_format = ieee_little_endian_format;
1110 else
1111 detected_double_format = unknown_format;
1112 }
1113#else
1114 detected_double_format = unknown_format;
1115#endif
1116
1117#if SIZEOF_FLOAT == 4
1118 {
1119 float y = 16711938.0;
1120 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1121 detected_float_format = ieee_big_endian_format;
1122 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1123 detected_float_format = ieee_little_endian_format;
1124 else
1125 detected_float_format = unknown_format;
1126 }
1127#else
1128 detected_float_format = unknown_format;
1129#endif
1130
1131 double_format = detected_double_format;
1132 float_format = detected_float_format;
1133}
1134
1135void
Fred Drakefd99de62000-07-09 05:02:18 +00001136PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001137{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001138 PyFloatObject *p;
1139 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001140 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001141 int bc, bf; /* block count, number of freed blocks */
1142 int frem, fsum; /* remaining unfreed floats per block, total */
1143
1144 bc = 0;
1145 bf = 0;
1146 fsum = 0;
1147 list = block_list;
1148 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001149 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001150 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001151 bc++;
1152 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001153 for (i = 0, p = &list->objects[0];
1154 i < N_FLOATOBJECTS;
1155 i++, p++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001156 if (PyFloat_CheckExact(p) && Py_Refcnt(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001157 frem++;
1158 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001159 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001160 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001161 list->next = block_list;
1162 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001163 for (i = 0, p = &list->objects[0];
1164 i < N_FLOATOBJECTS;
1165 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001166 if (!PyFloat_CheckExact(p) ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001167 Py_Refcnt(p) == 0) {
1168 Py_Type(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001169 free_list;
1170 free_list = p;
1171 }
1172 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001173 }
1174 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001175 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001176 bf++;
1177 }
1178 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001179 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001180 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001181 if (!Py_VerboseFlag)
1182 return;
1183 fprintf(stderr, "# cleanup floats");
1184 if (!fsum) {
1185 fprintf(stderr, "\n");
1186 }
1187 else {
1188 fprintf(stderr,
1189 ": %d unfreed float%s in %d out of %d block%s\n",
1190 fsum, fsum == 1 ? "" : "s",
1191 bc - bf, bc, bc == 1 ? "" : "s");
1192 }
1193 if (Py_VerboseFlag > 1) {
1194 list = block_list;
1195 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001196 for (i = 0, p = &list->objects[0];
1197 i < N_FLOATOBJECTS;
1198 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001199 if (PyFloat_CheckExact(p) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001200 Py_Refcnt(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001201 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001202 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001203 /* XXX(twouters) cast refcount to
1204 long until %zd is universally
1205 available
1206 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001207 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001208 "# <float at %p, refcnt=%ld, val=%s>\n",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001209 p, (long)Py_Refcnt(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001210 }
1211 }
1212 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001213 }
1214 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001215}
Tim Peters9905b942003-03-20 20:53:32 +00001216
1217/*----------------------------------------------------------------------------
1218 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1219 *
1220 * TODO: On platforms that use the standard IEEE-754 single and double
1221 * formats natively, these routines could simply copy the bytes.
1222 */
1223int
1224_PyFloat_Pack4(double x, unsigned char *p, int le)
1225{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001226 if (float_format == unknown_format) {
1227 unsigned char sign;
1228 int e;
1229 double f;
1230 unsigned int fbits;
1231 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001232
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001233 if (le) {
1234 p += 3;
1235 incr = -1;
1236 }
Tim Peters9905b942003-03-20 20:53:32 +00001237
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001238 if (x < 0) {
1239 sign = 1;
1240 x = -x;
1241 }
1242 else
1243 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001244
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001245 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001246
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001247 /* Normalize f to be in the range [1.0, 2.0) */
1248 if (0.5 <= f && f < 1.0) {
1249 f *= 2.0;
1250 e--;
1251 }
1252 else if (f == 0.0)
1253 e = 0;
1254 else {
1255 PyErr_SetString(PyExc_SystemError,
1256 "frexp() result out of range");
1257 return -1;
1258 }
1259
1260 if (e >= 128)
1261 goto Overflow;
1262 else if (e < -126) {
1263 /* Gradual underflow */
1264 f = ldexp(f, 126 + e);
1265 e = 0;
1266 }
1267 else if (!(e == 0 && f == 0.0)) {
1268 e += 127;
1269 f -= 1.0; /* Get rid of leading 1 */
1270 }
1271
1272 f *= 8388608.0; /* 2**23 */
1273 fbits = (unsigned int)(f + 0.5); /* Round */
1274 assert(fbits <= 8388608);
1275 if (fbits >> 23) {
1276 /* The carry propagated out of a string of 23 1 bits. */
1277 fbits = 0;
1278 ++e;
1279 if (e >= 255)
1280 goto Overflow;
1281 }
1282
1283 /* First byte */
1284 *p = (sign << 7) | (e >> 1);
1285 p += incr;
1286
1287 /* Second byte */
1288 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1289 p += incr;
1290
1291 /* Third byte */
1292 *p = (fbits >> 8) & 0xFF;
1293 p += incr;
1294
1295 /* Fourth byte */
1296 *p = fbits & 0xFF;
1297
1298 /* Done */
1299 return 0;
1300
1301 Overflow:
1302 PyErr_SetString(PyExc_OverflowError,
1303 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001304 return -1;
1305 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001306 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001307 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001308 const char *s = (char*)&y;
1309 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001310
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001311 if ((float_format == ieee_little_endian_format && !le)
1312 || (float_format == ieee_big_endian_format && le)) {
1313 p += 3;
1314 incr = -1;
1315 }
1316
1317 for (i = 0; i < 4; i++) {
1318 *p = *s++;
1319 p += incr;
1320 }
1321 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001322 }
Tim Peters9905b942003-03-20 20:53:32 +00001323}
1324
1325int
1326_PyFloat_Pack8(double x, unsigned char *p, int le)
1327{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001328 if (double_format == unknown_format) {
1329 unsigned char sign;
1330 int e;
1331 double f;
1332 unsigned int fhi, flo;
1333 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001334
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001335 if (le) {
1336 p += 7;
1337 incr = -1;
1338 }
Tim Peters9905b942003-03-20 20:53:32 +00001339
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001340 if (x < 0) {
1341 sign = 1;
1342 x = -x;
1343 }
1344 else
1345 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001346
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001347 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001348
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001349 /* Normalize f to be in the range [1.0, 2.0) */
1350 if (0.5 <= f && f < 1.0) {
1351 f *= 2.0;
1352 e--;
1353 }
1354 else if (f == 0.0)
1355 e = 0;
1356 else {
1357 PyErr_SetString(PyExc_SystemError,
1358 "frexp() result out of range");
1359 return -1;
1360 }
1361
1362 if (e >= 1024)
1363 goto Overflow;
1364 else if (e < -1022) {
1365 /* Gradual underflow */
1366 f = ldexp(f, 1022 + e);
1367 e = 0;
1368 }
1369 else if (!(e == 0 && f == 0.0)) {
1370 e += 1023;
1371 f -= 1.0; /* Get rid of leading 1 */
1372 }
1373
1374 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1375 f *= 268435456.0; /* 2**28 */
1376 fhi = (unsigned int)f; /* Truncate */
1377 assert(fhi < 268435456);
1378
1379 f -= (double)fhi;
1380 f *= 16777216.0; /* 2**24 */
1381 flo = (unsigned int)(f + 0.5); /* Round */
1382 assert(flo <= 16777216);
1383 if (flo >> 24) {
1384 /* The carry propagated out of a string of 24 1 bits. */
1385 flo = 0;
1386 ++fhi;
1387 if (fhi >> 28) {
1388 /* And it also progagated out of the next 28 bits. */
1389 fhi = 0;
1390 ++e;
1391 if (e >= 2047)
1392 goto Overflow;
1393 }
1394 }
1395
1396 /* First byte */
1397 *p = (sign << 7) | (e >> 4);
1398 p += incr;
1399
1400 /* Second byte */
1401 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1402 p += incr;
1403
1404 /* Third byte */
1405 *p = (fhi >> 16) & 0xFF;
1406 p += incr;
1407
1408 /* Fourth byte */
1409 *p = (fhi >> 8) & 0xFF;
1410 p += incr;
1411
1412 /* Fifth byte */
1413 *p = fhi & 0xFF;
1414 p += incr;
1415
1416 /* Sixth byte */
1417 *p = (flo >> 16) & 0xFF;
1418 p += incr;
1419
1420 /* Seventh byte */
1421 *p = (flo >> 8) & 0xFF;
1422 p += incr;
1423
1424 /* Eighth byte */
1425 *p = flo & 0xFF;
1426 p += incr;
1427
1428 /* Done */
1429 return 0;
1430
1431 Overflow:
1432 PyErr_SetString(PyExc_OverflowError,
1433 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001434 return -1;
1435 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001436 else {
1437 const char *s = (char*)&x;
1438 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001439
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001440 if ((double_format == ieee_little_endian_format && !le)
1441 || (double_format == ieee_big_endian_format && le)) {
1442 p += 7;
1443 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001444 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001445
1446 for (i = 0; i < 8; i++) {
1447 *p = *s++;
1448 p += incr;
1449 }
1450 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001451 }
Tim Peters9905b942003-03-20 20:53:32 +00001452}
1453
Neal Norwitz545686b2006-12-28 04:45:06 +00001454/* Should only be used by marshal. */
1455int
1456_PyFloat_Repr(double x, char *p, size_t len)
1457{
1458 format_double(p, len, x, PREC_REPR);
1459 return (int)strlen(p);
1460}
1461
Tim Peters9905b942003-03-20 20:53:32 +00001462double
1463_PyFloat_Unpack4(const unsigned char *p, int le)
1464{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001465 if (float_format == unknown_format) {
1466 unsigned char sign;
1467 int e;
1468 unsigned int f;
1469 double x;
1470 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001471
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001472 if (le) {
1473 p += 3;
1474 incr = -1;
1475 }
1476
1477 /* First byte */
1478 sign = (*p >> 7) & 1;
1479 e = (*p & 0x7F) << 1;
1480 p += incr;
1481
1482 /* Second byte */
1483 e |= (*p >> 7) & 1;
1484 f = (*p & 0x7F) << 16;
1485 p += incr;
1486
1487 if (e == 255) {
1488 PyErr_SetString(
1489 PyExc_ValueError,
1490 "can't unpack IEEE 754 special value "
1491 "on non-IEEE platform");
1492 return -1;
1493 }
1494
1495 /* Third byte */
1496 f |= *p << 8;
1497 p += incr;
1498
1499 /* Fourth byte */
1500 f |= *p;
1501
1502 x = (double)f / 8388608.0;
1503
1504 /* XXX This sadly ignores Inf/NaN issues */
1505 if (e == 0)
1506 e = -126;
1507 else {
1508 x += 1.0;
1509 e -= 127;
1510 }
1511 x = ldexp(x, e);
1512
1513 if (sign)
1514 x = -x;
1515
1516 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001517 }
Tim Peters9905b942003-03-20 20:53:32 +00001518 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001519 float x;
1520
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001521 if ((float_format == ieee_little_endian_format && !le)
1522 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001523 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001524 char *d = &buf[3];
1525 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001526
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001527 for (i = 0; i < 4; i++) {
1528 *d-- = *p++;
1529 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001530 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001531 }
1532 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001533 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001534 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001535
1536 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001537 }
Tim Peters9905b942003-03-20 20:53:32 +00001538}
1539
1540double
1541_PyFloat_Unpack8(const unsigned char *p, int le)
1542{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001543 if (double_format == unknown_format) {
1544 unsigned char sign;
1545 int e;
1546 unsigned int fhi, flo;
1547 double x;
1548 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001549
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001550 if (le) {
1551 p += 7;
1552 incr = -1;
1553 }
1554
1555 /* First byte */
1556 sign = (*p >> 7) & 1;
1557 e = (*p & 0x7F) << 4;
1558
1559 p += incr;
1560
1561 /* Second byte */
1562 e |= (*p >> 4) & 0xF;
1563 fhi = (*p & 0xF) << 24;
1564 p += incr;
1565
1566 if (e == 2047) {
1567 PyErr_SetString(
1568 PyExc_ValueError,
1569 "can't unpack IEEE 754 special value "
1570 "on non-IEEE platform");
1571 return -1.0;
1572 }
1573
1574 /* Third byte */
1575 fhi |= *p << 16;
1576 p += incr;
1577
1578 /* Fourth byte */
1579 fhi |= *p << 8;
1580 p += incr;
1581
1582 /* Fifth byte */
1583 fhi |= *p;
1584 p += incr;
1585
1586 /* Sixth byte */
1587 flo = *p << 16;
1588 p += incr;
1589
1590 /* Seventh byte */
1591 flo |= *p << 8;
1592 p += incr;
1593
1594 /* Eighth byte */
1595 flo |= *p;
1596
1597 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1598 x /= 268435456.0; /* 2**28 */
1599
1600 if (e == 0)
1601 e = -1022;
1602 else {
1603 x += 1.0;
1604 e -= 1023;
1605 }
1606 x = ldexp(x, e);
1607
1608 if (sign)
1609 x = -x;
1610
1611 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001612 }
Tim Peters9905b942003-03-20 20:53:32 +00001613 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001614 double x;
1615
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001616 if ((double_format == ieee_little_endian_format && !le)
1617 || (double_format == ieee_big_endian_format && le)) {
1618 char buf[8];
1619 char *d = &buf[7];
1620 int i;
1621
1622 for (i = 0; i < 8; i++) {
1623 *d-- = *p++;
1624 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001625 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001626 }
1627 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001628 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001629 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001630
1631 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001632 }
Tim Peters9905b942003-03-20 20:53:32 +00001633}