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