blob: 9c6dadf7406727766a19527fc45d16ebd7c462c3 [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
Tim Petersef14d732000-09-23 03:39:17 +000065/**************************************************************************
66RED_FLAG 22-Sep-2000 tim
67PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
68
691. If v was a regular string, *pend was set to point to its terminating
70 null byte. That's useless (the caller can find that without any
71 help from this function!).
72
732. If v was a Unicode string, or an object convertible to a character
74 buffer, *pend was set to point into stack trash (the auto temp
75 vector holding the character buffer). That was downright dangerous.
76
77Since we can't change the interface of a public API function, pend is
78still supported but now *officially* useless: if pend is not NULL,
79*pend is set to NULL.
80**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +000081PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000082PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +000083{
Guido van Rossum4c08d552000-03-10 22:55:18 +000084 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000085 double x;
Tim Petersef14d732000-09-23 03:39:17 +000086 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000087#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +000088 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000089#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +000090 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000091
Tim Petersef14d732000-09-23 03:39:17 +000092 if (pend)
93 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +000094 if (PyString_Check(v)) {
95 s = PyString_AS_STRING(v);
96 len = PyString_GET_SIZE(v);
97 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +000098#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +000099 else if (PyUnicode_Check(v)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000100 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000101 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000102 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000103 return NULL;
104 }
Tim Petersef14d732000-09-23 03:39:17 +0000105 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000106 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000107 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000108 NULL))
109 return NULL;
110 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000111 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000112 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000113#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000114 else if (PyObject_AsCharBuffer(v, &s, &len)) {
115 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000116 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000117 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000118 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000119
Guido van Rossum4c08d552000-03-10 22:55:18 +0000120 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000121 while (*s && isspace(Py_CHARMASK(*s)))
122 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000123 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000124 PyErr_SetString(PyExc_ValueError, "empty string for float()");
125 return NULL;
126 }
Tim Petersef14d732000-09-23 03:39:17 +0000127 /* We don't care about overflow or underflow. If the platform supports
128 * them, infinities and signed zeroes (on underflow) are fine.
129 * However, strtod can return 0 for denormalized numbers, where atof
130 * does not. So (alas!) we special-case a zero result. Note that
131 * whether strtod sets errno on underflow is not defined, so we can't
132 * key off errno.
133 */
Tim Peters858346e2000-09-25 21:01:28 +0000134 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000135 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000136 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000137 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000138 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000139 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000140 if (end > last)
141 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000142 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000143 PyOS_snprintf(buffer, sizeof(buffer),
144 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000145 PyErr_SetString(PyExc_ValueError, buffer);
146 return NULL;
147 }
148 /* Since end != s, the platform made *some* kind of sense out
149 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000150 while (*end && isspace(Py_CHARMASK(*end)))
151 end++;
152 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000153 PyOS_snprintf(buffer, sizeof(buffer),
154 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000155 PyErr_SetString(PyExc_ValueError, buffer);
156 return NULL;
157 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000158 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159 PyErr_SetString(PyExc_ValueError,
160 "null byte in argument for float()");
161 return NULL;
162 }
Tim Petersef14d732000-09-23 03:39:17 +0000163 if (x == 0.0) {
164 /* See above -- may have been strtod being anal
165 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000166 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000167 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000168 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000169 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000170 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 return PyFloat_FromDouble(x);
172}
173
Guido van Rossum234f9421993-06-17 12:35:49 +0000174static void
Fred Drakefd99de62000-07-09 05:02:18 +0000175float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000176{
Guido van Rossum9475a232001-10-05 20:51:39 +0000177 if (PyFloat_CheckExact(op)) {
178 op->ob_type = (struct _typeobject *)free_list;
179 free_list = op;
180 }
181 else
182 op->ob_type->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000183}
184
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185double
Fred Drakefd99de62000-07-09 05:02:18 +0000186PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 PyNumberMethods *nb;
189 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000190 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000191
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 if (op && PyFloat_Check(op))
193 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000194
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000195 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197 return -1;
198 }
Tim Petersd2364e82001-11-01 20:09:42 +0000199
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000200 if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) {
201 PyErr_SetString(PyExc_TypeError, "a float is required");
202 return -1;
203 }
204
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206 if (fo == NULL)
207 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 if (!PyFloat_Check(fo)) {
209 PyErr_SetString(PyExc_TypeError,
210 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000211 return -1;
212 }
Tim Petersd2364e82001-11-01 20:09:42 +0000213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 val = PyFloat_AS_DOUBLE(fo);
215 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000216
Guido van Rossumb6775db1994-08-01 11:34:53 +0000217 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
220/* Methods */
221
Tim Peters97019e42001-11-28 22:43:45 +0000222static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000223format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
225 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000226 char format[32];
Neal Norwitz545686b2006-12-28 04:45:06 +0000227 /* Subroutine for float_repr, float_str, float_print and others.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228 We want float numbers to be recognizable as such,
229 i.e., they should contain a decimal point or an exponent.
230 However, %g may print the number as an integer;
231 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000232
Martin v. Löwis737ea822004-06-08 18:52:54 +0000233 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000234 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 cp = buf;
236 if (*cp == '-')
237 cp++;
238 for (; *cp != '\0'; cp++) {
239 /* Any non-digit means it's not an integer;
240 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000241 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242 break;
243 }
244 if (*cp == '\0') {
245 *cp++ = '.';
246 *cp++ = '0';
247 *cp++ = '\0';
248 }
249}
250
Neal Norwitz545686b2006-12-28 04:45:06 +0000251static void
252format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000253{
Neal Norwitz545686b2006-12-28 04:45:06 +0000254 assert(PyFloat_Check(v));
255 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000256}
257
Neil Schemenauer32117e52001-01-04 01:44:34 +0000258/* Macro and helper that convert PyObject obj to a C double and store
259 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000260 slot function. If conversion to double raises an exception, obj is
261 set to NULL, and the function invoking this macro returns NULL. If
262 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
263 stored in obj, and returned from the function invoking this macro.
264*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000265#define CONVERT_TO_DOUBLE(obj, dbl) \
266 if (PyFloat_Check(obj)) \
267 dbl = PyFloat_AS_DOUBLE(obj); \
268 else if (convert_to_double(&(obj), &(dbl)) < 0) \
269 return obj;
270
271static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000272convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000273{
274 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000275
Neil Schemenauer32117e52001-01-04 01:44:34 +0000276 if (PyInt_Check(obj)) {
277 *dbl = (double)PyInt_AS_LONG(obj);
278 }
279 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000280 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000281 if (*dbl == -1.0 && PyErr_Occurred()) {
282 *v = NULL;
283 return -1;
284 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000285 }
286 else {
287 Py_INCREF(Py_NotImplemented);
288 *v = Py_NotImplemented;
289 return -1;
290 }
291 return 0;
292}
293
Guido van Rossum57072eb1999-12-23 19:00:28 +0000294/* Precisions used by repr() and str(), respectively.
295
296 The repr() precision (17 significant decimal digits) is the minimal number
297 that is guaranteed to have enough precision so that if the number is read
298 back in the exact same binary value is recreated. This is true for IEEE
299 floating point by design, and also happens to work for all other modern
300 hardware.
301
302 The str() precision is chosen so that in most cases, the rounding noise
303 created by various operations is suppressed, while giving plenty of
304 precision for practical use.
305
306*/
307
308#define PREC_REPR 17
309#define PREC_STR 12
310
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000311/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000312static int
Fred Drakefd99de62000-07-09 05:02:18 +0000313float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314{
315 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000316 format_float(buf, sizeof(buf), v,
317 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000319 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320}
321
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000323float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324{
325 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000326 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000327 return PyString_FromString(buf);
328}
329
330static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000331float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000332{
333 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000334 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336}
337
Tim Peters307fa782004-09-23 08:06:40 +0000338/* Comparison is pretty much a nightmare. When comparing float to float,
339 * we do it as straightforwardly (and long-windedly) as conceivable, so
340 * that, e.g., Python x == y delivers the same result as the platform
341 * C x == y when x and/or y is a NaN.
342 * When mixing float with an integer type, there's no good *uniform* approach.
343 * Converting the double to an integer obviously doesn't work, since we
344 * may lose info from fractional bits. Converting the integer to a double
345 * also has two failure modes: (1) a long int may trigger overflow (too
346 * large to fit in the dynamic range of a C double); (2) even a C long may have
347 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
348 * 63 bits of precision, but a C double probably has only 53), and then
349 * we can falsely claim equality when low-order integer bits are lost by
350 * coercion to double. So this part is painful too.
351 */
352
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000353static PyObject*
354float_richcompare(PyObject *v, PyObject *w, int op)
355{
356 double i, j;
357 int r = 0;
358
Tim Peters307fa782004-09-23 08:06:40 +0000359 assert(PyFloat_Check(v));
360 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000361
Tim Peters307fa782004-09-23 08:06:40 +0000362 /* Switch on the type of w. Set i and j to doubles to be compared,
363 * and op to the richcomp to use.
364 */
365 if (PyFloat_Check(w))
366 j = PyFloat_AS_DOUBLE(w);
367
Thomas Wouters477c8d52006-05-27 19:21:47 +0000368 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000369 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000370 /* If i is an infinity, its magnitude exceeds any
371 * finite integer, so it doesn't matter which int we
372 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000373 */
374 j = 0.0;
375 else
376 goto Unimplemented;
377 }
378
379 else if (PyInt_Check(w)) {
380 long jj = PyInt_AS_LONG(w);
381 /* In the worst realistic case I can imagine, C double is a
382 * Cray single with 48 bits of precision, and long has 64
383 * bits.
384 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000385#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000386 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
387 if (abs >> 48) {
388 /* Needs more than 48 bits. Make it take the
389 * PyLong path.
390 */
391 PyObject *result;
392 PyObject *ww = PyLong_FromLong(jj);
393
394 if (ww == NULL)
395 return NULL;
396 result = float_richcompare(v, ww, op);
397 Py_DECREF(ww);
398 return result;
399 }
400#endif
401 j = (double)jj;
402 assert((long)j == jj);
403 }
404
405 else if (PyLong_Check(w)) {
406 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
407 int wsign = _PyLong_Sign(w);
408 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000409 int exponent;
410
411 if (vsign != wsign) {
412 /* Magnitudes are irrelevant -- the signs alone
413 * determine the outcome.
414 */
415 i = (double)vsign;
416 j = (double)wsign;
417 goto Compare;
418 }
419 /* The signs are the same. */
420 /* Convert w to a double if it fits. In particular, 0 fits. */
421 nbits = _PyLong_NumBits(w);
422 if (nbits == (size_t)-1 && PyErr_Occurred()) {
423 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000424 * to hold the # of bits. Replace with little doubles
425 * that give the same outcome -- w is so large that
426 * its magnitude must exceed the magnitude of any
427 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000428 */
429 PyErr_Clear();
430 i = (double)vsign;
431 assert(wsign != 0);
432 j = wsign * 2.0;
433 goto Compare;
434 }
435 if (nbits <= 48) {
436 j = PyLong_AsDouble(w);
437 /* It's impossible that <= 48 bits overflowed. */
438 assert(j != -1.0 || ! PyErr_Occurred());
439 goto Compare;
440 }
441 assert(wsign != 0); /* else nbits was 0 */
442 assert(vsign != 0); /* if vsign were 0, then since wsign is
443 * not 0, we would have taken the
444 * vsign != wsign branch at the start */
445 /* We want to work with non-negative numbers. */
446 if (vsign < 0) {
447 /* "Multiply both sides" by -1; this also swaps the
448 * comparator.
449 */
450 i = -i;
451 op = _Py_SwappedOp[op];
452 }
453 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000454 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000455 /* exponent is the # of bits in v before the radix point;
456 * we know that nbits (the # of bits in w) > 48 at this point
457 */
458 if (exponent < 0 || (size_t)exponent < nbits) {
459 i = 1.0;
460 j = 2.0;
461 goto Compare;
462 }
463 if ((size_t)exponent > nbits) {
464 i = 2.0;
465 j = 1.0;
466 goto Compare;
467 }
468 /* v and w have the same number of bits before the radix
469 * point. Construct two longs that have the same comparison
470 * outcome.
471 */
472 {
473 double fracpart;
474 double intpart;
475 PyObject *result = NULL;
476 PyObject *one = NULL;
477 PyObject *vv = NULL;
478 PyObject *ww = w;
479
480 if (wsign < 0) {
481 ww = PyNumber_Negative(w);
482 if (ww == NULL)
483 goto Error;
484 }
485 else
486 Py_INCREF(ww);
487
488 fracpart = modf(i, &intpart);
489 vv = PyLong_FromDouble(intpart);
490 if (vv == NULL)
491 goto Error;
492
493 if (fracpart != 0.0) {
494 /* Shift left, and or a 1 bit into vv
495 * to represent the lost fraction.
496 */
497 PyObject *temp;
498
499 one = PyInt_FromLong(1);
500 if (one == NULL)
501 goto Error;
502
503 temp = PyNumber_Lshift(ww, one);
504 if (temp == NULL)
505 goto Error;
506 Py_DECREF(ww);
507 ww = temp;
508
509 temp = PyNumber_Lshift(vv, one);
510 if (temp == NULL)
511 goto Error;
512 Py_DECREF(vv);
513 vv = temp;
514
515 temp = PyNumber_Or(vv, one);
516 if (temp == NULL)
517 goto Error;
518 Py_DECREF(vv);
519 vv = temp;
520 }
521
522 r = PyObject_RichCompareBool(vv, ww, op);
523 if (r < 0)
524 goto Error;
525 result = PyBool_FromLong(r);
526 Error:
527 Py_XDECREF(vv);
528 Py_XDECREF(ww);
529 Py_XDECREF(one);
530 return result;
531 }
532 } /* else if (PyLong_Check(w)) */
533
534 else /* w isn't float, int, or long */
535 goto Unimplemented;
536
537 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000538 PyFPE_START_PROTECT("richcompare", return NULL)
539 switch (op) {
540 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000541 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000542 break;
543 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000544 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000545 break;
546 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000547 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000548 break;
549 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000550 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000551 break;
552 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000553 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000554 break;
555 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000556 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000557 break;
558 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000559 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000560 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000561
562 Unimplemented:
563 Py_INCREF(Py_NotImplemented);
564 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000565}
566
Guido van Rossum9bfef441993-03-29 10:43:31 +0000567static long
Fred Drakefd99de62000-07-09 05:02:18 +0000568float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000569{
Tim Peters39dce292000-08-15 03:34:48 +0000570 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000571}
572
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000573static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000574float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000576 double a,b;
577 CONVERT_TO_DOUBLE(v, a);
578 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000579 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000580 a = a + b;
581 PyFPE_END_PROTECT(a)
582 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583}
584
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000586float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000588 double a,b;
589 CONVERT_TO_DOUBLE(v, a);
590 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000591 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000592 a = a - b;
593 PyFPE_END_PROTECT(a)
594 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595}
596
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000597static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000598float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000599{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000600 double a,b;
601 CONVERT_TO_DOUBLE(v, a);
602 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000603 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000604 a = a * b;
605 PyFPE_END_PROTECT(a)
606 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000607}
608
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000609static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000610float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000612 double a,b;
613 CONVERT_TO_DOUBLE(v, a);
614 CONVERT_TO_DOUBLE(w, b);
615 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617 return NULL;
618 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000619 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000620 a = a / b;
621 PyFPE_END_PROTECT(a)
622 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623}
624
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000626float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000628 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000629 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000630 CONVERT_TO_DOUBLE(v, vx);
631 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000634 return NULL;
635 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000636 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000637 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000638 /* note: checking mod*wx < 0 is incorrect -- underflows to
639 0 if wx < sqrt(smallest nonzero double) */
640 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000641 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000642 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000643 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645}
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000648float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000649{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000650 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000651 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000652 CONVERT_TO_DOUBLE(v, vx);
653 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000654 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000656 return NULL;
657 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000658 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000659 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000660 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000661 exact multiple of wx. But this is fp arithmetic, and fp
662 vx - mod is an approximation; the result is that div may
663 not be an exact integral value after the division, although
664 it will always be very close to one.
665 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000666 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000667 if (mod) {
668 /* ensure the remainder has the same sign as the denominator */
669 if ((wx < 0) != (mod < 0)) {
670 mod += wx;
671 div -= 1.0;
672 }
673 }
674 else {
675 /* the remainder is zero, and in the presence of signed zeroes
676 fmod returns different results across platforms; ensure
677 it has the same sign as the denominator; we'd like to do
678 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000679 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000680 if (wx < 0.0)
681 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000682 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000683 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000684 if (div) {
685 floordiv = floor(div);
686 if (div - floordiv > 0.5)
687 floordiv += 1.0;
688 }
689 else {
690 /* div is zero - get the same sign as the true quotient */
691 div *= div; /* hide "div = +0" from optimizers */
692 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
693 }
694 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000695 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000696}
697
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000699float_floor_div(PyObject *v, PyObject *w)
700{
701 PyObject *t, *r;
702
703 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000704 if (t == NULL || t == Py_NotImplemented)
705 return t;
706 assert(PyTuple_CheckExact(t));
707 r = PyTuple_GET_ITEM(t, 0);
708 Py_INCREF(r);
709 Py_DECREF(t);
710 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000711}
712
713static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000714float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715{
716 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000717
718 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000719 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000720 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000721 return NULL;
722 }
723
Neil Schemenauer32117e52001-01-04 01:44:34 +0000724 CONVERT_TO_DOUBLE(v, iv);
725 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000726
727 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000728 if (iw == 0) { /* v**0 is 1, even 0**0 */
Tim Petersc54d1902000-10-06 00:36:09 +0000729 PyFPE_START_PROTECT("pow", return NULL)
730 if ((PyObject *)z != Py_None) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000731 double iz;
Neil Schemenauer010b0cc2001-01-08 06:29:50 +0000732 CONVERT_TO_DOUBLE(z, iz);
Tim Peters96685bf2001-08-23 22:31:37 +0000733 ix = fmod(1.0, iz);
734 if (ix != 0 && iz < 0)
735 ix += iz;
Guido van Rossum70d93461991-05-28 21:57:39 +0000736 }
Tim Petersc54d1902000-10-06 00:36:09 +0000737 else
738 ix = 1.0;
739 PyFPE_END_PROTECT(ix)
Tim Petersd2364e82001-11-01 20:09:42 +0000740 return PyFloat_FromDouble(ix);
Tim Petersc54d1902000-10-06 00:36:09 +0000741 }
Tim Peters96685bf2001-08-23 22:31:37 +0000742 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000743 if (iw < 0.0) {
744 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000745 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000746 return NULL;
747 }
748 return PyFloat_FromDouble(0.0);
749 }
Tim Peterse87568d2003-05-24 20:18:24 +0000750 if (iv < 0.0) {
751 /* Whether this is an error is a mess, and bumps into libm
752 * bugs so we have to figure it out ourselves.
753 */
754 if (iw != floor(iw)) {
755 PyErr_SetString(PyExc_ValueError, "negative number "
756 "cannot be raised to a fractional power");
757 return NULL;
758 }
759 /* iw is an exact integer, albeit perhaps a very large one.
760 * -1 raised to an exact integer should never be exceptional.
761 * Alas, some libms (chiefly glibc as of early 2003) return
762 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
763 * happen to be representable in a *C* integer. That's a
764 * bug; we let that slide in math.pow() (which currently
765 * reflects all platform accidents), but not for Python's **.
766 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000768 /* Return 1 if iw is even, -1 if iw is odd; there's
769 * no guarantee that any C integral type is big
770 * enough to hold iw, so we have to check this
771 * indirectly.
772 */
773 ix = floor(iw * 0.5) * 2.0;
774 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
775 }
776 /* Else iv != -1.0, and overflow or underflow are possible.
777 * Unless we're to write pow() ourselves, we have to trust
778 * the platform to do this correctly.
779 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000780 }
Tim Peters96685bf2001-08-23 22:31:37 +0000781 errno = 0;
782 PyFPE_START_PROTECT("pow", return NULL)
783 ix = pow(iv, iw);
784 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000785 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000786 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000787 /* We don't expect any errno value other than ERANGE, but
788 * the range of libm bugs appears unbounded.
789 */
790 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
791 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000793 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000794 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795}
796
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000798float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801}
802
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000804float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805{
Tim Peters0280cf72001-09-11 21:53:35 +0000806 if (PyFloat_CheckExact(v)) {
807 Py_INCREF(v);
808 return (PyObject *)v;
809 }
810 else
811 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000812}
813
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000815float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000816{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000817 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818}
819
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000820static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000821float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000822{
823 return v->ob_fval != 0.0;
824}
825
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000826static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000827float_long(PyObject *v)
828{
829 double x = PyFloat_AsDouble(v);
830 return PyLong_FromDouble(x);
831}
832
833static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000834float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000835{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000837 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000838
839 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000840 /* Try to get out cheap if this fits in a Python int. The attempt
841 * to cast to long must be protected, as C doesn't define what
842 * happens if the double is too big to fit in a long. Some rare
843 * systems raise an exception then (RISCOS was mentioned as one,
844 * and someone using a non-default option on Sun also bumped into
845 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
846 * still be vulnerable: if a long has more bits of precision than
847 * a double, casting MIN/MAX to double may yield an approximation,
848 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
849 * yield true from the C expression wholepart<=LONG_MAX, despite
850 * that wholepart is actually greater than LONG_MAX.
851 */
852 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
853 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000854 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000855 }
856 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000857}
858
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000859static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000860float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000861{
Brett Cannonc3647ac2005-04-26 03:45:26 +0000862 if (PyFloat_CheckExact(v))
863 Py_INCREF(v);
864 else
865 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000866 return v;
867}
868
869
Jeremy Hylton938ace62002-07-17 16:30:39 +0000870static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000871float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
872
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873static PyObject *
874float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
875{
876 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +0000877 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878
Guido van Rossumbef14172001-08-29 15:47:46 +0000879 if (type != &PyFloat_Type)
880 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
882 return NULL;
883 if (PyString_Check(x))
884 return PyFloat_FromString(x, NULL);
885 return PyNumber_Float(x);
886}
887
Guido van Rossumbef14172001-08-29 15:47:46 +0000888/* Wimpy, slow approach to tp_new calls for subtypes of float:
889 first create a regular float from whatever arguments we got,
890 then allocate a subtype instance and initialize its ob_fval
891 from the regular float. The regular float is then thrown away.
892*/
893static PyObject *
894float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
895{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000896 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000897
898 assert(PyType_IsSubtype(type, &PyFloat_Type));
899 tmp = float_new(&PyFloat_Type, args, kwds);
900 if (tmp == NULL)
901 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000902 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000903 newobj = type->tp_alloc(type, 0);
904 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +0000905 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000906 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000907 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000908 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +0000909 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000910 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +0000911}
912
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000913static PyObject *
914float_getnewargs(PyFloatObject *v)
915{
916 return Py_BuildValue("(d)", v->ob_fval);
917}
918
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000919/* this is for the benefit of the pack/unpack routines below */
920
921typedef enum {
922 unknown_format, ieee_big_endian_format, ieee_little_endian_format
923} float_format_type;
924
925static float_format_type double_format, float_format;
926static float_format_type detected_double_format, detected_float_format;
927
928static PyObject *
929float_getformat(PyTypeObject *v, PyObject* arg)
930{
931 char* s;
932 float_format_type r;
933
934 if (!PyString_Check(arg)) {
935 PyErr_Format(PyExc_TypeError,
936 "__getformat__() argument must be string, not %.500s",
937 arg->ob_type->tp_name);
938 return NULL;
939 }
940 s = PyString_AS_STRING(arg);
941 if (strcmp(s, "double") == 0) {
942 r = double_format;
943 }
944 else if (strcmp(s, "float") == 0) {
945 r = float_format;
946 }
947 else {
948 PyErr_SetString(PyExc_ValueError,
949 "__getformat__() argument 1 must be "
950 "'double' or 'float'");
951 return NULL;
952 }
953
954 switch (r) {
955 case unknown_format:
956 return PyString_FromString("unknown");
957 case ieee_little_endian_format:
958 return PyString_FromString("IEEE, little-endian");
959 case ieee_big_endian_format:
960 return PyString_FromString("IEEE, big-endian");
961 default:
962 Py_FatalError("insane float_format or double_format");
963 return NULL;
964 }
965}
966
967PyDoc_STRVAR(float_getformat_doc,
968"float.__getformat__(typestr) -> string\n"
969"\n"
970"You probably don't want to use this function. It exists mainly to be\n"
971"used in Python's test suite.\n"
972"\n"
973"typestr must be 'double' or 'float'. This function returns whichever of\n"
974"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
975"format of floating point numbers used by the C type named by typestr.");
976
977static PyObject *
978float_setformat(PyTypeObject *v, PyObject* args)
979{
980 char* typestr;
981 char* format;
982 float_format_type f;
983 float_format_type detected;
984 float_format_type *p;
985
986 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
987 return NULL;
988
989 if (strcmp(typestr, "double") == 0) {
990 p = &double_format;
991 detected = detected_double_format;
992 }
993 else if (strcmp(typestr, "float") == 0) {
994 p = &float_format;
995 detected = detected_float_format;
996 }
997 else {
998 PyErr_SetString(PyExc_ValueError,
999 "__setformat__() argument 1 must "
1000 "be 'double' or 'float'");
1001 return NULL;
1002 }
1003
1004 if (strcmp(format, "unknown") == 0) {
1005 f = unknown_format;
1006 }
1007 else if (strcmp(format, "IEEE, little-endian") == 0) {
1008 f = ieee_little_endian_format;
1009 }
1010 else if (strcmp(format, "IEEE, big-endian") == 0) {
1011 f = ieee_big_endian_format;
1012 }
1013 else {
1014 PyErr_SetString(PyExc_ValueError,
1015 "__setformat__() argument 2 must be "
1016 "'unknown', 'IEEE, little-endian' or "
1017 "'IEEE, big-endian'");
1018 return NULL;
1019
1020 }
1021
1022 if (f != unknown_format && f != detected) {
1023 PyErr_Format(PyExc_ValueError,
1024 "can only set %s format to 'unknown' or the "
1025 "detected platform value", typestr);
1026 return NULL;
1027 }
1028
1029 *p = f;
1030 Py_RETURN_NONE;
1031}
1032
1033PyDoc_STRVAR(float_setformat_doc,
1034"float.__setformat__(typestr, fmt) -> None\n"
1035"\n"
1036"You probably don't want to use this function. It exists mainly to be\n"
1037"used in Python's test suite.\n"
1038"\n"
1039"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1040"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1041"one of the latter two if it appears to match the underlying C reality.\n"
1042"\n"
1043"Overrides the automatic determination of C-level floating point type.\n"
1044"This affects how floats are converted to and from binary strings.");
1045
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001046static PyMethodDef float_methods[] = {
1047 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001048 {"__getformat__", (PyCFunction)float_getformat,
1049 METH_O|METH_CLASS, float_getformat_doc},
1050 {"__setformat__", (PyCFunction)float_setformat,
1051 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001052 {NULL, NULL} /* sentinel */
1053};
1054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001055PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056"float(x) -> floating point number\n\
1057\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001058Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059
1060
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001061static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001062 float_add, /*nb_add*/
1063 float_sub, /*nb_subtract*/
1064 float_mul, /*nb_multiply*/
1065 float_rem, /*nb_remainder*/
1066 float_divmod, /*nb_divmod*/
1067 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001068 (unaryfunc)float_neg, /*nb_negative*/
1069 (unaryfunc)float_pos, /*nb_positive*/
1070 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001071 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001072 0, /*nb_invert*/
1073 0, /*nb_lshift*/
1074 0, /*nb_rshift*/
1075 0, /*nb_and*/
1076 0, /*nb_xor*/
1077 0, /*nb_or*/
Neal Norwitz4886cc32006-08-21 17:06:07 +00001078 (coercion)0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001079 float_int, /*nb_int*/
1080 float_long, /*nb_long*/
1081 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001082 0, /* nb_oct */
1083 0, /* nb_hex */
1084 0, /* nb_inplace_add */
1085 0, /* nb_inplace_subtract */
1086 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001087 0, /* nb_inplace_remainder */
1088 0, /* nb_inplace_power */
1089 0, /* nb_inplace_lshift */
1090 0, /* nb_inplace_rshift */
1091 0, /* nb_inplace_and */
1092 0, /* nb_inplace_xor */
1093 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001094 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001095 float_div, /* nb_true_divide */
1096 0, /* nb_inplace_floor_divide */
1097 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001098};
1099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001100PyTypeObject PyFloat_Type = {
1101 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001102 0,
1103 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001104 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001105 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106 (destructor)float_dealloc, /* tp_dealloc */
1107 (printfunc)float_print, /* tp_print */
1108 0, /* tp_getattr */
1109 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001110 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111 (reprfunc)float_repr, /* tp_repr */
1112 &float_as_number, /* tp_as_number */
1113 0, /* tp_as_sequence */
1114 0, /* tp_as_mapping */
1115 (hashfunc)float_hash, /* tp_hash */
1116 0, /* tp_call */
1117 (reprfunc)float_str, /* tp_str */
1118 PyObject_GenericGetAttr, /* tp_getattro */
1119 0, /* tp_setattro */
1120 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001121 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 float_doc, /* tp_doc */
1123 0, /* tp_traverse */
1124 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 0, /* tp_weaklistoffset */
1127 0, /* tp_iter */
1128 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001129 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 0, /* tp_members */
1131 0, /* tp_getset */
1132 0, /* tp_base */
1133 0, /* tp_dict */
1134 0, /* tp_descr_get */
1135 0, /* tp_descr_set */
1136 0, /* tp_dictoffset */
1137 0, /* tp_init */
1138 0, /* tp_alloc */
1139 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001140};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001141
1142void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001143_PyFloat_Init(void)
1144{
1145 /* We attempt to determine if this machine is using IEEE
1146 floating point formats by peering at the bits of some
1147 carefully chosen values. If it looks like we are on an
1148 IEEE platform, the float packing/unpacking routines can
1149 just copy bits, if not they resort to arithmetic & shifts
1150 and masks. The shifts & masks approach works on all finite
1151 values, but what happens to infinities, NaNs and signed
1152 zeroes on packing is an accident, and attempting to unpack
1153 a NaN or an infinity will raise an exception.
1154
1155 Note that if we're on some whacked-out platform which uses
1156 IEEE formats but isn't strictly little-endian or big-
1157 endian, we will fall back to the portable shifts & masks
1158 method. */
1159
1160#if SIZEOF_DOUBLE == 8
1161 {
1162 double x = 9006104071832581.0;
1163 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1164 detected_double_format = ieee_big_endian_format;
1165 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1166 detected_double_format = ieee_little_endian_format;
1167 else
1168 detected_double_format = unknown_format;
1169 }
1170#else
1171 detected_double_format = unknown_format;
1172#endif
1173
1174#if SIZEOF_FLOAT == 4
1175 {
1176 float y = 16711938.0;
1177 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1178 detected_float_format = ieee_big_endian_format;
1179 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1180 detected_float_format = ieee_little_endian_format;
1181 else
1182 detected_float_format = unknown_format;
1183 }
1184#else
1185 detected_float_format = unknown_format;
1186#endif
1187
1188 double_format = detected_double_format;
1189 float_format = detected_float_format;
1190}
1191
1192void
Fred Drakefd99de62000-07-09 05:02:18 +00001193PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001194{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001195 PyFloatObject *p;
1196 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001197 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001198 int bc, bf; /* block count, number of freed blocks */
1199 int frem, fsum; /* remaining unfreed floats per block, total */
1200
1201 bc = 0;
1202 bf = 0;
1203 fsum = 0;
1204 list = block_list;
1205 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001206 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001207 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001208 bc++;
1209 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001210 for (i = 0, p = &list->objects[0];
1211 i < N_FLOATOBJECTS;
1212 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001213 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001214 frem++;
1215 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001216 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001217 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001218 list->next = block_list;
1219 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001220 for (i = 0, p = &list->objects[0];
1221 i < N_FLOATOBJECTS;
1222 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001223 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +00001224 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001225 p->ob_type = (struct _typeobject *)
1226 free_list;
1227 free_list = p;
1228 }
1229 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001230 }
1231 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001232 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001233 bf++;
1234 }
1235 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001236 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001237 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001238 if (!Py_VerboseFlag)
1239 return;
1240 fprintf(stderr, "# cleanup floats");
1241 if (!fsum) {
1242 fprintf(stderr, "\n");
1243 }
1244 else {
1245 fprintf(stderr,
1246 ": %d unfreed float%s in %d out of %d block%s\n",
1247 fsum, fsum == 1 ? "" : "s",
1248 bc - bf, bc, bc == 1 ? "" : "s");
1249 }
1250 if (Py_VerboseFlag > 1) {
1251 list = block_list;
1252 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001253 for (i = 0, p = &list->objects[0];
1254 i < N_FLOATOBJECTS;
1255 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001256 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +00001257 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001258 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001259 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001260 /* XXX(twouters) cast refcount to
1261 long until %zd is universally
1262 available
1263 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001264 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001265 "# <float at %p, refcnt=%ld, val=%s>\n",
1266 p, (long)p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001267 }
1268 }
1269 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001270 }
1271 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001272}
Tim Peters9905b942003-03-20 20:53:32 +00001273
1274/*----------------------------------------------------------------------------
1275 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1276 *
1277 * TODO: On platforms that use the standard IEEE-754 single and double
1278 * formats natively, these routines could simply copy the bytes.
1279 */
1280int
1281_PyFloat_Pack4(double x, unsigned char *p, int le)
1282{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001283 if (float_format == unknown_format) {
1284 unsigned char sign;
1285 int e;
1286 double f;
1287 unsigned int fbits;
1288 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001289
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001290 if (le) {
1291 p += 3;
1292 incr = -1;
1293 }
Tim Peters9905b942003-03-20 20:53:32 +00001294
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001295 if (x < 0) {
1296 sign = 1;
1297 x = -x;
1298 }
1299 else
1300 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001301
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001302 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001303
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001304 /* Normalize f to be in the range [1.0, 2.0) */
1305 if (0.5 <= f && f < 1.0) {
1306 f *= 2.0;
1307 e--;
1308 }
1309 else if (f == 0.0)
1310 e = 0;
1311 else {
1312 PyErr_SetString(PyExc_SystemError,
1313 "frexp() result out of range");
1314 return -1;
1315 }
1316
1317 if (e >= 128)
1318 goto Overflow;
1319 else if (e < -126) {
1320 /* Gradual underflow */
1321 f = ldexp(f, 126 + e);
1322 e = 0;
1323 }
1324 else if (!(e == 0 && f == 0.0)) {
1325 e += 127;
1326 f -= 1.0; /* Get rid of leading 1 */
1327 }
1328
1329 f *= 8388608.0; /* 2**23 */
1330 fbits = (unsigned int)(f + 0.5); /* Round */
1331 assert(fbits <= 8388608);
1332 if (fbits >> 23) {
1333 /* The carry propagated out of a string of 23 1 bits. */
1334 fbits = 0;
1335 ++e;
1336 if (e >= 255)
1337 goto Overflow;
1338 }
1339
1340 /* First byte */
1341 *p = (sign << 7) | (e >> 1);
1342 p += incr;
1343
1344 /* Second byte */
1345 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1346 p += incr;
1347
1348 /* Third byte */
1349 *p = (fbits >> 8) & 0xFF;
1350 p += incr;
1351
1352 /* Fourth byte */
1353 *p = fbits & 0xFF;
1354
1355 /* Done */
1356 return 0;
1357
1358 Overflow:
1359 PyErr_SetString(PyExc_OverflowError,
1360 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001361 return -1;
1362 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001363 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001364 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001365 const char *s = (char*)&y;
1366 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001367
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001368 if ((float_format == ieee_little_endian_format && !le)
1369 || (float_format == ieee_big_endian_format && le)) {
1370 p += 3;
1371 incr = -1;
1372 }
1373
1374 for (i = 0; i < 4; i++) {
1375 *p = *s++;
1376 p += incr;
1377 }
1378 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001379 }
Tim Peters9905b942003-03-20 20:53:32 +00001380}
1381
1382int
1383_PyFloat_Pack8(double x, unsigned char *p, int le)
1384{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001385 if (double_format == unknown_format) {
1386 unsigned char sign;
1387 int e;
1388 double f;
1389 unsigned int fhi, flo;
1390 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001391
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001392 if (le) {
1393 p += 7;
1394 incr = -1;
1395 }
Tim Peters9905b942003-03-20 20:53:32 +00001396
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001397 if (x < 0) {
1398 sign = 1;
1399 x = -x;
1400 }
1401 else
1402 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001403
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001404 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001405
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001406 /* Normalize f to be in the range [1.0, 2.0) */
1407 if (0.5 <= f && f < 1.0) {
1408 f *= 2.0;
1409 e--;
1410 }
1411 else if (f == 0.0)
1412 e = 0;
1413 else {
1414 PyErr_SetString(PyExc_SystemError,
1415 "frexp() result out of range");
1416 return -1;
1417 }
1418
1419 if (e >= 1024)
1420 goto Overflow;
1421 else if (e < -1022) {
1422 /* Gradual underflow */
1423 f = ldexp(f, 1022 + e);
1424 e = 0;
1425 }
1426 else if (!(e == 0 && f == 0.0)) {
1427 e += 1023;
1428 f -= 1.0; /* Get rid of leading 1 */
1429 }
1430
1431 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1432 f *= 268435456.0; /* 2**28 */
1433 fhi = (unsigned int)f; /* Truncate */
1434 assert(fhi < 268435456);
1435
1436 f -= (double)fhi;
1437 f *= 16777216.0; /* 2**24 */
1438 flo = (unsigned int)(f + 0.5); /* Round */
1439 assert(flo <= 16777216);
1440 if (flo >> 24) {
1441 /* The carry propagated out of a string of 24 1 bits. */
1442 flo = 0;
1443 ++fhi;
1444 if (fhi >> 28) {
1445 /* And it also progagated out of the next 28 bits. */
1446 fhi = 0;
1447 ++e;
1448 if (e >= 2047)
1449 goto Overflow;
1450 }
1451 }
1452
1453 /* First byte */
1454 *p = (sign << 7) | (e >> 4);
1455 p += incr;
1456
1457 /* Second byte */
1458 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1459 p += incr;
1460
1461 /* Third byte */
1462 *p = (fhi >> 16) & 0xFF;
1463 p += incr;
1464
1465 /* Fourth byte */
1466 *p = (fhi >> 8) & 0xFF;
1467 p += incr;
1468
1469 /* Fifth byte */
1470 *p = fhi & 0xFF;
1471 p += incr;
1472
1473 /* Sixth byte */
1474 *p = (flo >> 16) & 0xFF;
1475 p += incr;
1476
1477 /* Seventh byte */
1478 *p = (flo >> 8) & 0xFF;
1479 p += incr;
1480
1481 /* Eighth byte */
1482 *p = flo & 0xFF;
1483 p += incr;
1484
1485 /* Done */
1486 return 0;
1487
1488 Overflow:
1489 PyErr_SetString(PyExc_OverflowError,
1490 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001491 return -1;
1492 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001493 else {
1494 const char *s = (char*)&x;
1495 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001496
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001497 if ((double_format == ieee_little_endian_format && !le)
1498 || (double_format == ieee_big_endian_format && le)) {
1499 p += 7;
1500 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001501 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001502
1503 for (i = 0; i < 8; i++) {
1504 *p = *s++;
1505 p += incr;
1506 }
1507 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001508 }
Tim Peters9905b942003-03-20 20:53:32 +00001509}
1510
Neal Norwitz545686b2006-12-28 04:45:06 +00001511/* Should only be used by marshal. */
1512int
1513_PyFloat_Repr(double x, char *p, size_t len)
1514{
1515 format_double(p, len, x, PREC_REPR);
1516 return (int)strlen(p);
1517}
1518
Tim Peters9905b942003-03-20 20:53:32 +00001519double
1520_PyFloat_Unpack4(const unsigned char *p, int le)
1521{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001522 if (float_format == unknown_format) {
1523 unsigned char sign;
1524 int e;
1525 unsigned int f;
1526 double x;
1527 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001528
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001529 if (le) {
1530 p += 3;
1531 incr = -1;
1532 }
1533
1534 /* First byte */
1535 sign = (*p >> 7) & 1;
1536 e = (*p & 0x7F) << 1;
1537 p += incr;
1538
1539 /* Second byte */
1540 e |= (*p >> 7) & 1;
1541 f = (*p & 0x7F) << 16;
1542 p += incr;
1543
1544 if (e == 255) {
1545 PyErr_SetString(
1546 PyExc_ValueError,
1547 "can't unpack IEEE 754 special value "
1548 "on non-IEEE platform");
1549 return -1;
1550 }
1551
1552 /* Third byte */
1553 f |= *p << 8;
1554 p += incr;
1555
1556 /* Fourth byte */
1557 f |= *p;
1558
1559 x = (double)f / 8388608.0;
1560
1561 /* XXX This sadly ignores Inf/NaN issues */
1562 if (e == 0)
1563 e = -126;
1564 else {
1565 x += 1.0;
1566 e -= 127;
1567 }
1568 x = ldexp(x, e);
1569
1570 if (sign)
1571 x = -x;
1572
1573 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001574 }
Tim Peters9905b942003-03-20 20:53:32 +00001575 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001576 float x;
1577
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001578 if ((float_format == ieee_little_endian_format && !le)
1579 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001580 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581 char *d = &buf[3];
1582 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001583
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001584 for (i = 0; i < 4; i++) {
1585 *d-- = *p++;
1586 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001587 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001588 }
1589 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001590 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001591 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001592
1593 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001594 }
Tim Peters9905b942003-03-20 20:53:32 +00001595}
1596
1597double
1598_PyFloat_Unpack8(const unsigned char *p, int le)
1599{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001600 if (double_format == unknown_format) {
1601 unsigned char sign;
1602 int e;
1603 unsigned int fhi, flo;
1604 double x;
1605 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001606
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001607 if (le) {
1608 p += 7;
1609 incr = -1;
1610 }
1611
1612 /* First byte */
1613 sign = (*p >> 7) & 1;
1614 e = (*p & 0x7F) << 4;
1615
1616 p += incr;
1617
1618 /* Second byte */
1619 e |= (*p >> 4) & 0xF;
1620 fhi = (*p & 0xF) << 24;
1621 p += incr;
1622
1623 if (e == 2047) {
1624 PyErr_SetString(
1625 PyExc_ValueError,
1626 "can't unpack IEEE 754 special value "
1627 "on non-IEEE platform");
1628 return -1.0;
1629 }
1630
1631 /* Third byte */
1632 fhi |= *p << 16;
1633 p += incr;
1634
1635 /* Fourth byte */
1636 fhi |= *p << 8;
1637 p += incr;
1638
1639 /* Fifth byte */
1640 fhi |= *p;
1641 p += incr;
1642
1643 /* Sixth byte */
1644 flo = *p << 16;
1645 p += incr;
1646
1647 /* Seventh byte */
1648 flo |= *p << 8;
1649 p += incr;
1650
1651 /* Eighth byte */
1652 flo |= *p;
1653
1654 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1655 x /= 268435456.0; /* 2**28 */
1656
1657 if (e == 0)
1658 e = -1022;
1659 else {
1660 x += 1.0;
1661 e -= 1023;
1662 }
1663 x = ldexp(x, e);
1664
1665 if (sign)
1666 x = -x;
1667
1668 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001669 }
Tim Peters9905b942003-03-20 20:53:32 +00001670 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001671 double x;
1672
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673 if ((double_format == ieee_little_endian_format && !le)
1674 || (double_format == ieee_big_endian_format && le)) {
1675 char buf[8];
1676 char *d = &buf[7];
1677 int i;
1678
1679 for (i = 0; i < 8; i++) {
1680 *d-- = *p++;
1681 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001682 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683 }
1684 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001685 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001686 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001687
1688 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001689 }
Tim Peters9905b942003-03-20 20:53:32 +00001690}