blob: 574b96a4e74ae74b54369f2761c1c8c814f4ecd4 [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>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Jack Janseneddc1442003-11-20 01:44:59 +000012#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000013extern double fmod(double, double);
14extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000015#endif
16
Guido van Rossum93ad0df1997-05-13 21:00:42 +000017/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000018#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000019#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000020#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000021
Guido van Rossum3fce8831999-03-12 19:43:17 +000022struct _floatblock {
23 struct _floatblock *next;
24 PyFloatObject objects[N_FLOATOBJECTS];
25};
26
27typedef struct _floatblock PyFloatBlock;
28
29static PyFloatBlock *block_list = NULL;
30static PyFloatObject *free_list = NULL;
31
Guido van Rossum93ad0df1997-05-13 21:00:42 +000032static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000033fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000034{
35 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000036 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
37 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000038 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000039 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000040 ((PyFloatBlock *)p)->next = block_list;
41 block_list = (PyFloatBlock *)p;
42 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043 q = p + N_FLOATOBJECTS;
44 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000045 Py_TYPE(q) = (struct _typeobject *)(q-1);
46 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000047 return p + N_FLOATOBJECTS - 1;
48}
49
Christian Heimesdfdfaab2007-12-01 11:20:10 +000050double
51PyFloat_GetMax(void)
52{
53 return DBL_MAX;
54}
55
56double
57PyFloat_GetMin(void)
58{
59 return DBL_MIN;
60}
61
62PyObject *
63PyFloat_GetInfo(void)
64{
65 PyObject *d, *tmp;
66
67#define SET_FLOAT_CONST(d, key, const) \
68 tmp = PyFloat_FromDouble(const); \
69 if (tmp == NULL) return NULL; \
70 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
71 Py_DECREF(tmp)
72#define SET_INT_CONST(d, key, const) \
73 tmp = PyInt_FromLong(const); \
74 if (tmp == NULL) return NULL; \
75 if (PyDict_SetItemString(d, key, tmp)) return NULL; \
76 Py_DECREF(tmp)
77
78 d = PyDict_New();
79
80 SET_FLOAT_CONST(d, "max", DBL_MAX);
81 SET_INT_CONST(d, "max_exp", DBL_MAX_EXP);
82 SET_INT_CONST(d, "max_10_exp", DBL_MAX_10_EXP);
83 SET_FLOAT_CONST(d, "min", DBL_MIN);
84 SET_INT_CONST(d, "min_exp", DBL_MIN_EXP);
85 SET_INT_CONST(d, "min_10_exp", DBL_MIN_10_EXP);
86 SET_INT_CONST(d, "dig", DBL_DIG);
87 SET_INT_CONST(d, "mant_dig", DBL_MANT_DIG);
88 SET_FLOAT_CONST(d, "epsilon", DBL_EPSILON);
89 SET_INT_CONST(d, "radix", FLT_RADIX);
90 SET_INT_CONST(d, "rounds", FLT_ROUNDS);
91
92 return d;
93}
94
95
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Guido van Rossum93ad0df1997-05-13 21:00:42 +000099 register PyFloatObject *op;
100 if (free_list == NULL) {
101 if ((free_list = fill_free_list()) == NULL)
102 return NULL;
103 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000104 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000105 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000106 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000107 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000108 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110}
111
Tim Petersef14d732000-09-23 03:39:17 +0000112/**************************************************************************
113RED_FLAG 22-Sep-2000 tim
114PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
115
1161. If v was a regular string, *pend was set to point to its terminating
117 null byte. That's useless (the caller can find that without any
118 help from this function!).
119
1202. If v was a Unicode string, or an object convertible to a character
121 buffer, *pend was set to point into stack trash (the auto temp
122 vector holding the character buffer). That was downright dangerous.
123
124Since we can't change the interface of a public API function, pend is
125still supported but now *officially* useless: if pend is not NULL,
126*pend is set to NULL.
127**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000128PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000129PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000130{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000131 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000132 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000133 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000134#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000135 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000136#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000137 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000138
Tim Petersef14d732000-09-23 03:39:17 +0000139 if (pend)
140 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000141 if (PyString_Check(v)) {
142 s = PyString_AS_STRING(v);
143 len = PyString_GET_SIZE(v);
144 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000145#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000146 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000147 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000148 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000149 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000150 return NULL;
151 }
Tim Petersef14d732000-09-23 03:39:17 +0000152 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000153 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000154 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000155 NULL))
156 return NULL;
157 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000158 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000159 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000160#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000161 else if (PyObject_AsCharBuffer(v, &s, &len)) {
162 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000163 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000165 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166
Guido van Rossum4c08d552000-03-10 22:55:18 +0000167 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168 while (*s && isspace(Py_CHARMASK(*s)))
169 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000170 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 PyErr_SetString(PyExc_ValueError, "empty string for float()");
172 return NULL;
173 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000174 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000175 /* We don't care about overflow or underflow. If the platform supports
176 * them, infinities and signed zeroes (on underflow) are fine.
177 * However, strtod can return 0 for denormalized numbers, where atof
178 * does not. So (alas!) we special-case a zero result. Note that
179 * whether strtod sets errno on underflow is not defined, so we can't
180 * key off errno.
181 */
Tim Peters858346e2000-09-25 21:01:28 +0000182 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000183 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000184 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000185 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000186 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000187 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 if (end > last)
189 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000190 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000191 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000192 char *p = (char*)sp;
193 int sign = 1;
194
195 if (*p == '-') {
196 sign = -1;
197 p++;
198 }
199 if (*p == '+') {
200 p++;
201 }
202 if (PyOS_strnicmp(p, "inf", 4) == 0) {
203 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
204 }
205#ifdef Py_NAN
206 if(PyOS_strnicmp(p, "nan", 4) == 0) {
207 return PyFloat_FromDouble(Py_NAN);
208 }
209#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000210 PyOS_snprintf(buffer, sizeof(buffer),
211 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000212 PyErr_SetString(PyExc_ValueError, buffer);
213 return NULL;
214 }
215 /* Since end != s, the platform made *some* kind of sense out
216 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 while (*end && isspace(Py_CHARMASK(*end)))
218 end++;
219 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000220 PyOS_snprintf(buffer, sizeof(buffer),
221 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000222 PyErr_SetString(PyExc_ValueError, buffer);
223 return NULL;
224 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000225 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000226 PyErr_SetString(PyExc_ValueError,
227 "null byte in argument for float()");
228 return NULL;
229 }
Tim Petersef14d732000-09-23 03:39:17 +0000230 if (x == 0.0) {
231 /* See above -- may have been strtod being anal
232 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000233 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000234 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000235 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000236 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000238 return PyFloat_FromDouble(x);
239}
240
Guido van Rossum234f9421993-06-17 12:35:49 +0000241static void
Fred Drakefd99de62000-07-09 05:02:18 +0000242float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000243{
Guido van Rossum9475a232001-10-05 20:51:39 +0000244 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000245 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000246 free_list = op;
247 }
248 else
Christian Heimese93237d2007-12-19 02:37:44 +0000249 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000250}
251
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252double
Fred Drakefd99de62000-07-09 05:02:18 +0000253PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000255 PyNumberMethods *nb;
256 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000258
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000259 if (op && PyFloat_Check(op))
260 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000261
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000262 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264 return -1;
265 }
Tim Petersd2364e82001-11-01 20:09:42 +0000266
Christian Heimese93237d2007-12-19 02:37:44 +0000267 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000268 PyErr_SetString(PyExc_TypeError, "a float is required");
269 return -1;
270 }
271
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273 if (fo == NULL)
274 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275 if (!PyFloat_Check(fo)) {
276 PyErr_SetString(PyExc_TypeError,
277 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000278 return -1;
279 }
Tim Petersd2364e82001-11-01 20:09:42 +0000280
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 val = PyFloat_AS_DOUBLE(fo);
282 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000283
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285}
286
287/* Methods */
288
Tim Peters97019e42001-11-28 22:43:45 +0000289static void
290format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291{
292 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000293 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000294 int i;
295
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 /* Subroutine for float_repr and float_print.
297 We want float numbers to be recognizable as such,
298 i.e., they should contain a decimal point or an exponent.
299 However, %g may print the number as an integer;
300 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000301
302 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000303 PyOS_snprintf(format, 32, "%%.%ig", precision);
304 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305 cp = buf;
306 if (*cp == '-')
307 cp++;
308 for (; *cp != '\0'; cp++) {
309 /* Any non-digit means it's not an integer;
310 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000311 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312 break;
313 }
314 if (*cp == '\0') {
315 *cp++ = '.';
316 *cp++ = '0';
317 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000318 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000320 /* Checking the next three chars should be more than enough to
321 * detect inf or nan, even on Windows. We check for inf or nan
322 * at last because they are rare cases.
323 */
324 for (i=0; *cp != '\0' && i<3; cp++, i++) {
325 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
326 continue;
327 /* found something that is neither a digit nor point
328 * it might be a NaN or INF
329 */
330#ifdef Py_NAN
331 if (Py_IS_NAN(v->ob_fval)) {
332 strcpy(buf, "nan");
333 }
334 else
335#endif
336 if (Py_IS_INFINITY(v->ob_fval)) {
337 cp = buf;
338 if (*cp == '-')
339 cp++;
340 strcpy(cp, "inf");
341 }
342 break;
343 }
344
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345}
346
Tim Peters97019e42001-11-28 22:43:45 +0000347/* XXX PyFloat_AsStringEx should not be a public API function (for one
348 XXX thing, its signature passes a buffer without a length; for another,
349 XXX it isn't useful outside this file).
350*/
351void
352PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
353{
354 format_float(buf, 100, v, precision);
355}
356
Christian Heimesf15c66e2007-12-11 00:54:34 +0000357#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000358/* The following function is based on Tcl_PrintDouble,
359 * from tclUtil.c.
360 */
361
362#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
363#define is_nan(d) ((d) != (d))
364
365static void
366format_double_repr(char *dst, double value)
367{
368 char *p, c;
369 int exp;
370 int signum;
371 char buffer[30];
372
373 /*
374 * Handle NaN.
375 */
376
377 if (is_nan(value)) {
378 strcpy(dst, "nan");
379 return;
380 }
381
382 /*
383 * Handle infinities.
384 */
385
386 if (is_infinite(value)) {
387 if (value < 0) {
388 strcpy(dst, "-inf");
389 } else {
390 strcpy(dst, "inf");
391 }
392 return;
393 }
394
395 /*
396 * Ordinary (normal and denormal) values.
397 */
398
399 exp = _PyFloat_Digits(buffer, value, &signum)+1;
400 if (signum) {
401 *dst++ = '-';
402 }
403 p = buffer;
404 if (exp < -3 || exp > 17) {
405 /*
406 * E format for numbers < 1e-3 or >= 1e17.
407 */
408
409 *dst++ = *p++;
410 c = *p;
411 if (c != '\0') {
412 *dst++ = '.';
413 while (c != '\0') {
414 *dst++ = c;
415 c = *++p;
416 }
417 }
418 sprintf(dst, "e%+d", exp-1);
419 } else {
420 /*
421 * F format for others.
422 */
423
424 if (exp <= 0) {
425 *dst++ = '0';
426 }
427 c = *p;
428 while (exp-- > 0) {
429 if (c != '\0') {
430 *dst++ = c;
431 c = *++p;
432 } else {
433 *dst++ = '0';
434 }
435 }
436 *dst++ = '.';
437 if (c == '\0') {
438 *dst++ = '0';
439 } else {
440 while (++exp < 0) {
441 *dst++ = '0';
442 }
443 while (c != '\0') {
444 *dst++ = c;
445 c = *++p;
446 }
447 }
448 *dst++ = '\0';
449 }
450}
451
452static void
453format_float_repr(char *buf, PyFloatObject *v)
454{
455 assert(PyFloat_Check(v));
456 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
457}
458
Christian Heimesf15c66e2007-12-11 00:54:34 +0000459#endif /* Py_BROKEN_REPR */
460
Neil Schemenauer32117e52001-01-04 01:44:34 +0000461/* Macro and helper that convert PyObject obj to a C double and store
462 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000463 slot function. If conversion to double raises an exception, obj is
464 set to NULL, and the function invoking this macro returns NULL. If
465 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
466 stored in obj, and returned from the function invoking this macro.
467*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000468#define CONVERT_TO_DOUBLE(obj, dbl) \
469 if (PyFloat_Check(obj)) \
470 dbl = PyFloat_AS_DOUBLE(obj); \
471 else if (convert_to_double(&(obj), &(dbl)) < 0) \
472 return obj;
473
474static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000475convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000476{
477 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000478
Neil Schemenauer32117e52001-01-04 01:44:34 +0000479 if (PyInt_Check(obj)) {
480 *dbl = (double)PyInt_AS_LONG(obj);
481 }
482 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000483 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000484 if (*dbl == -1.0 && PyErr_Occurred()) {
485 *v = NULL;
486 return -1;
487 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000488 }
489 else {
490 Py_INCREF(Py_NotImplemented);
491 *v = Py_NotImplemented;
492 return -1;
493 }
494 return 0;
495}
496
Guido van Rossum57072eb1999-12-23 19:00:28 +0000497/* Precisions used by repr() and str(), respectively.
498
499 The repr() precision (17 significant decimal digits) is the minimal number
500 that is guaranteed to have enough precision so that if the number is read
501 back in the exact same binary value is recreated. This is true for IEEE
502 floating point by design, and also happens to work for all other modern
503 hardware.
504
505 The str() precision is chosen so that in most cases, the rounding noise
506 created by various operations is suppressed, while giving plenty of
507 precision for practical use.
508
509*/
510
511#define PREC_REPR 17
512#define PREC_STR 12
513
Tim Peters97019e42001-11-28 22:43:45 +0000514/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
515 XXX they pass a char buffer without passing a length.
516*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000517void
Fred Drakefd99de62000-07-09 05:02:18 +0000518PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000519{
Tim Peters97019e42001-11-28 22:43:45 +0000520 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000521}
522
Tim Peters72f98e92001-05-08 15:19:57 +0000523void
524PyFloat_AsReprString(char *buf, PyFloatObject *v)
525{
Tim Peters97019e42001-11-28 22:43:45 +0000526 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000527}
528
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000529/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000530static int
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532{
533 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000534 format_float(buf, sizeof(buf), v,
535 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000536 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000538 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000539 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000543float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000545#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000546 char buf[30];
547 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000548#else
549 char buf[100];
550 format_float(buf, sizeof(buf), v, PREC_REPR);
551#endif
552
Guido van Rossum57072eb1999-12-23 19:00:28 +0000553 return PyString_FromString(buf);
554}
555
556static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000557float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000558{
559 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000560 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Tim Peters307fa782004-09-23 08:06:40 +0000564/* Comparison is pretty much a nightmare. When comparing float to float,
565 * we do it as straightforwardly (and long-windedly) as conceivable, so
566 * that, e.g., Python x == y delivers the same result as the platform
567 * C x == y when x and/or y is a NaN.
568 * When mixing float with an integer type, there's no good *uniform* approach.
569 * Converting the double to an integer obviously doesn't work, since we
570 * may lose info from fractional bits. Converting the integer to a double
571 * also has two failure modes: (1) a long int may trigger overflow (too
572 * large to fit in the dynamic range of a C double); (2) even a C long may have
573 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
574 * 63 bits of precision, but a C double probably has only 53), and then
575 * we can falsely claim equality when low-order integer bits are lost by
576 * coercion to double. So this part is painful too.
577 */
578
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000579static PyObject*
580float_richcompare(PyObject *v, PyObject *w, int op)
581{
582 double i, j;
583 int r = 0;
584
Tim Peters307fa782004-09-23 08:06:40 +0000585 assert(PyFloat_Check(v));
586 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000587
Tim Peters307fa782004-09-23 08:06:40 +0000588 /* Switch on the type of w. Set i and j to doubles to be compared,
589 * and op to the richcomp to use.
590 */
591 if (PyFloat_Check(w))
592 j = PyFloat_AS_DOUBLE(w);
593
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000594 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000595 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000596 /* If i is an infinity, its magnitude exceeds any
597 * finite integer, so it doesn't matter which int we
598 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000599 */
600 j = 0.0;
601 else
602 goto Unimplemented;
603 }
604
605 else if (PyInt_Check(w)) {
606 long jj = PyInt_AS_LONG(w);
607 /* In the worst realistic case I can imagine, C double is a
608 * Cray single with 48 bits of precision, and long has 64
609 * bits.
610 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000611#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000612 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
613 if (abs >> 48) {
614 /* Needs more than 48 bits. Make it take the
615 * PyLong path.
616 */
617 PyObject *result;
618 PyObject *ww = PyLong_FromLong(jj);
619
620 if (ww == NULL)
621 return NULL;
622 result = float_richcompare(v, ww, op);
623 Py_DECREF(ww);
624 return result;
625 }
626#endif
627 j = (double)jj;
628 assert((long)j == jj);
629 }
630
631 else if (PyLong_Check(w)) {
632 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
633 int wsign = _PyLong_Sign(w);
634 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000635 int exponent;
636
637 if (vsign != wsign) {
638 /* Magnitudes are irrelevant -- the signs alone
639 * determine the outcome.
640 */
641 i = (double)vsign;
642 j = (double)wsign;
643 goto Compare;
644 }
645 /* The signs are the same. */
646 /* Convert w to a double if it fits. In particular, 0 fits. */
647 nbits = _PyLong_NumBits(w);
648 if (nbits == (size_t)-1 && PyErr_Occurred()) {
649 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000650 * to hold the # of bits. Replace with little doubles
651 * that give the same outcome -- w is so large that
652 * its magnitude must exceed the magnitude of any
653 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000654 */
655 PyErr_Clear();
656 i = (double)vsign;
657 assert(wsign != 0);
658 j = wsign * 2.0;
659 goto Compare;
660 }
661 if (nbits <= 48) {
662 j = PyLong_AsDouble(w);
663 /* It's impossible that <= 48 bits overflowed. */
664 assert(j != -1.0 || ! PyErr_Occurred());
665 goto Compare;
666 }
667 assert(wsign != 0); /* else nbits was 0 */
668 assert(vsign != 0); /* if vsign were 0, then since wsign is
669 * not 0, we would have taken the
670 * vsign != wsign branch at the start */
671 /* We want to work with non-negative numbers. */
672 if (vsign < 0) {
673 /* "Multiply both sides" by -1; this also swaps the
674 * comparator.
675 */
676 i = -i;
677 op = _Py_SwappedOp[op];
678 }
679 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000680 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000681 /* exponent is the # of bits in v before the radix point;
682 * we know that nbits (the # of bits in w) > 48 at this point
683 */
684 if (exponent < 0 || (size_t)exponent < nbits) {
685 i = 1.0;
686 j = 2.0;
687 goto Compare;
688 }
689 if ((size_t)exponent > nbits) {
690 i = 2.0;
691 j = 1.0;
692 goto Compare;
693 }
694 /* v and w have the same number of bits before the radix
695 * point. Construct two longs that have the same comparison
696 * outcome.
697 */
698 {
699 double fracpart;
700 double intpart;
701 PyObject *result = NULL;
702 PyObject *one = NULL;
703 PyObject *vv = NULL;
704 PyObject *ww = w;
705
706 if (wsign < 0) {
707 ww = PyNumber_Negative(w);
708 if (ww == NULL)
709 goto Error;
710 }
711 else
712 Py_INCREF(ww);
713
714 fracpart = modf(i, &intpart);
715 vv = PyLong_FromDouble(intpart);
716 if (vv == NULL)
717 goto Error;
718
719 if (fracpart != 0.0) {
720 /* Shift left, and or a 1 bit into vv
721 * to represent the lost fraction.
722 */
723 PyObject *temp;
724
725 one = PyInt_FromLong(1);
726 if (one == NULL)
727 goto Error;
728
729 temp = PyNumber_Lshift(ww, one);
730 if (temp == NULL)
731 goto Error;
732 Py_DECREF(ww);
733 ww = temp;
734
735 temp = PyNumber_Lshift(vv, one);
736 if (temp == NULL)
737 goto Error;
738 Py_DECREF(vv);
739 vv = temp;
740
741 temp = PyNumber_Or(vv, one);
742 if (temp == NULL)
743 goto Error;
744 Py_DECREF(vv);
745 vv = temp;
746 }
747
748 r = PyObject_RichCompareBool(vv, ww, op);
749 if (r < 0)
750 goto Error;
751 result = PyBool_FromLong(r);
752 Error:
753 Py_XDECREF(vv);
754 Py_XDECREF(ww);
755 Py_XDECREF(one);
756 return result;
757 }
758 } /* else if (PyLong_Check(w)) */
759
760 else /* w isn't float, int, or long */
761 goto Unimplemented;
762
763 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000764 PyFPE_START_PROTECT("richcompare", return NULL)
765 switch (op) {
766 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000767 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000768 break;
769 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000770 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000771 break;
772 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000773 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000774 break;
775 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000776 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000777 break;
778 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000779 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000780 break;
781 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000782 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000783 break;
784 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000785 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000786 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000787
788 Unimplemented:
789 Py_INCREF(Py_NotImplemented);
790 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000791}
792
Guido van Rossum9bfef441993-03-29 10:43:31 +0000793static long
Fred Drakefd99de62000-07-09 05:02:18 +0000794float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000795{
Tim Peters39dce292000-08-15 03:34:48 +0000796 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000797}
798
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000799static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000800float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000802 double a,b;
803 CONVERT_TO_DOUBLE(v, a);
804 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000805 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000806 a = a + b;
807 PyFPE_END_PROTECT(a)
808 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809}
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000812float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000814 double a,b;
815 CONVERT_TO_DOUBLE(v, a);
816 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000817 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000818 a = a - b;
819 PyFPE_END_PROTECT(a)
820 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821}
822
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000823static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000824float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000826 double a,b;
827 CONVERT_TO_DOUBLE(v, a);
828 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000829 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000830 a = a * b;
831 PyFPE_END_PROTECT(a)
832 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000836float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000838 double a,b;
839 CONVERT_TO_DOUBLE(v, a);
840 CONVERT_TO_DOUBLE(w, b);
841 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000842 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000843 return NULL;
844 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000845 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000846 a = a / b;
847 PyFPE_END_PROTECT(a)
848 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000849}
850
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000851static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000852float_classic_div(PyObject *v, PyObject *w)
853{
854 double a,b;
855 CONVERT_TO_DOUBLE(v, a);
856 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000857 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000858 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
859 return NULL;
860 if (b == 0.0) {
861 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
862 return NULL;
863 }
864 PyFPE_START_PROTECT("divide", return 0)
865 a = a / b;
866 PyFPE_END_PROTECT(a)
867 return PyFloat_FromDouble(a);
868}
869
870static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000871float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000873 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000874 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000875 CONVERT_TO_DOUBLE(v, vx);
876 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000878 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879 return NULL;
880 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000881 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000882 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000883 /* note: checking mod*wx < 0 is incorrect -- underflows to
884 0 if wx < sqrt(smallest nonzero double) */
885 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000886 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000887 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000888 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000890}
891
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000892static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000893float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000894{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000895 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000896 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000897 CONVERT_TO_DOUBLE(v, vx);
898 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000899 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000900 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000901 return NULL;
902 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000903 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000904 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000905 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000906 exact multiple of wx. But this is fp arithmetic, and fp
907 vx - mod is an approximation; the result is that div may
908 not be an exact integral value after the division, although
909 it will always be very close to one.
910 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000911 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000912 if (mod) {
913 /* ensure the remainder has the same sign as the denominator */
914 if ((wx < 0) != (mod < 0)) {
915 mod += wx;
916 div -= 1.0;
917 }
918 }
919 else {
920 /* the remainder is zero, and in the presence of signed zeroes
921 fmod returns different results across platforms; ensure
922 it has the same sign as the denominator; we'd like to do
923 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000924 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000925 if (wx < 0.0)
926 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000927 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000928 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000929 if (div) {
930 floordiv = floor(div);
931 if (div - floordiv > 0.5)
932 floordiv += 1.0;
933 }
934 else {
935 /* div is zero - get the same sign as the true quotient */
936 div *= div; /* hide "div = +0" from optimizers */
937 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
938 }
939 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000940 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000941}
942
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000944float_floor_div(PyObject *v, PyObject *w)
945{
946 PyObject *t, *r;
947
948 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000949 if (t == NULL || t == Py_NotImplemented)
950 return t;
951 assert(PyTuple_CheckExact(t));
952 r = PyTuple_GET_ITEM(t, 0);
953 Py_INCREF(r);
954 Py_DECREF(t);
955 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000956}
957
958static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000959float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000960{
961 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000962
963 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000964 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000965 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000966 return NULL;
967 }
968
Neil Schemenauer32117e52001-01-04 01:44:34 +0000969 CONVERT_TO_DOUBLE(v, iv);
970 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000971
972 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000973 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000974 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000975 }
Tim Peters96685bf2001-08-23 22:31:37 +0000976 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000977 if (iw < 0.0) {
978 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000979 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000980 return NULL;
981 }
982 return PyFloat_FromDouble(0.0);
983 }
Tim Peterse87568d2003-05-24 20:18:24 +0000984 if (iv < 0.0) {
985 /* Whether this is an error is a mess, and bumps into libm
986 * bugs so we have to figure it out ourselves.
987 */
988 if (iw != floor(iw)) {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000989 /* Negative numbers raised to fractional powers
990 * become complex.
991 */
992 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000993 }
994 /* iw is an exact integer, albeit perhaps a very large one.
995 * -1 raised to an exact integer should never be exceptional.
996 * Alas, some libms (chiefly glibc as of early 2003) return
997 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
998 * happen to be representable in a *C* integer. That's a
999 * bug; we let that slide in math.pow() (which currently
1000 * reflects all platform accidents), but not for Python's **.
1001 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001002 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001003 /* Return 1 if iw is even, -1 if iw is odd; there's
1004 * no guarantee that any C integral type is big
1005 * enough to hold iw, so we have to check this
1006 * indirectly.
1007 */
1008 ix = floor(iw * 0.5) * 2.0;
1009 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1010 }
1011 /* Else iv != -1.0, and overflow or underflow are possible.
1012 * Unless we're to write pow() ourselves, we have to trust
1013 * the platform to do this correctly.
1014 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001015 }
Tim Peters96685bf2001-08-23 22:31:37 +00001016 errno = 0;
1017 PyFPE_START_PROTECT("pow", return NULL)
1018 ix = pow(iv, iw);
1019 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001020 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001021 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001022 /* We don't expect any errno value other than ERANGE, but
1023 * the range of libm bugs appears unbounded.
1024 */
Alex Martelli348dc882006-08-23 22:17:59 +00001025 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1026 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001027 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001028 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001029 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001030}
1031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001032static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001033float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001034{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001035 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001036}
1037
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001039float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001040{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001041 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001042}
1043
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001044static int
Fred Drakefd99de62000-07-09 05:02:18 +00001045float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001046{
1047 return v->ob_fval != 0.0;
1048}
1049
Guido van Rossum234f9421993-06-17 12:35:49 +00001050static int
Fred Drakefd99de62000-07-09 05:02:18 +00001051float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001052{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053 if (PyInt_Check(*pw)) {
1054 long x = PyInt_AsLong(*pw);
1055 *pw = PyFloat_FromDouble((double)x);
1056 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001057 return 0;
1058 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001059 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001060 double x = PyLong_AsDouble(*pw);
1061 if (x == -1.0 && PyErr_Occurred())
1062 return -1;
1063 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001064 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001065 return 0;
1066 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001067 else if (PyFloat_Check(*pw)) {
1068 Py_INCREF(*pv);
1069 Py_INCREF(*pw);
1070 return 0;
1071 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001072 return 1; /* Can't do it */
1073}
1074
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001075static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001076float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001077{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001078 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001079 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001080
1081 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001082 /* Try to get out cheap if this fits in a Python int. The attempt
1083 * to cast to long must be protected, as C doesn't define what
1084 * happens if the double is too big to fit in a long. Some rare
1085 * systems raise an exception then (RISCOS was mentioned as one,
1086 * and someone using a non-default option on Sun also bumped into
1087 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1088 * still be vulnerable: if a long has more bits of precision than
1089 * a double, casting MIN/MAX to double may yield an approximation,
1090 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1091 * yield true from the C expression wholepart<=LONG_MAX, despite
1092 * that wholepart is actually greater than LONG_MAX.
1093 */
1094 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1095 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001096 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001097 }
1098 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001099}
1100
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001101static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001102float_round(PyObject *v, PyObject *args)
1103{
1104#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1105 double x;
1106 double f;
1107 double flr, cil;
1108 double rounded;
1109 int i;
1110 int ndigits = UNDEF_NDIGITS;
1111
1112 if (!PyArg_ParseTuple(args, "|i", &ndigits))
1113 return NULL;
1114
1115 x = PyFloat_AsDouble(v);
1116
1117 if (ndigits != UNDEF_NDIGITS) {
1118 f = 1.0;
1119 i = abs(ndigits);
1120 while (--i >= 0)
1121 f = f*10.0;
1122 if (ndigits < 0)
1123 x /= f;
1124 else
1125 x *= f;
1126 }
1127
1128 flr = floor(x);
1129 cil = ceil(x);
1130
1131 if (x-flr > 0.5)
1132 rounded = cil;
1133 else if (x-flr == 0.5)
1134 rounded = fmod(flr, 2) == 0 ? flr : cil;
1135 else
1136 rounded = flr;
1137
1138 if (ndigits != UNDEF_NDIGITS) {
1139 if (ndigits < 0)
1140 rounded *= f;
1141 else
1142 rounded /= f;
1143 }
1144
1145 return PyFloat_FromDouble(rounded);
1146#undef UNDEF_NDIGITS
1147}
1148
1149static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001150float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001151{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001152 if (PyFloat_CheckExact(v))
1153 Py_INCREF(v);
1154 else
1155 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001156 return v;
1157}
1158
1159
Jeremy Hylton938ace62002-07-17 16:30:39 +00001160static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001161float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1162
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163static PyObject *
1164float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1165{
1166 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001167 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
Guido van Rossumbef14172001-08-29 15:47:46 +00001169 if (type != &PyFloat_Type)
1170 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1172 return NULL;
1173 if (PyString_Check(x))
1174 return PyFloat_FromString(x, NULL);
1175 return PyNumber_Float(x);
1176}
1177
Guido van Rossumbef14172001-08-29 15:47:46 +00001178/* Wimpy, slow approach to tp_new calls for subtypes of float:
1179 first create a regular float from whatever arguments we got,
1180 then allocate a subtype instance and initialize its ob_fval
1181 from the regular float. The regular float is then thrown away.
1182*/
1183static PyObject *
1184float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1185{
Anthony Baxter377be112006-04-11 06:54:30 +00001186 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001187
1188 assert(PyType_IsSubtype(type, &PyFloat_Type));
1189 tmp = float_new(&PyFloat_Type, args, kwds);
1190 if (tmp == NULL)
1191 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001192 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001193 newobj = type->tp_alloc(type, 0);
1194 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001195 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001196 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001197 }
Anthony Baxter377be112006-04-11 06:54:30 +00001198 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001199 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001200 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001201}
1202
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001203static PyObject *
1204float_getnewargs(PyFloatObject *v)
1205{
1206 return Py_BuildValue("(d)", v->ob_fval);
1207}
1208
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001209/* this is for the benefit of the pack/unpack routines below */
1210
1211typedef enum {
1212 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1213} float_format_type;
1214
1215static float_format_type double_format, float_format;
1216static float_format_type detected_double_format, detected_float_format;
1217
1218static PyObject *
1219float_getformat(PyTypeObject *v, PyObject* arg)
1220{
1221 char* s;
1222 float_format_type r;
1223
1224 if (!PyString_Check(arg)) {
1225 PyErr_Format(PyExc_TypeError,
1226 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001227 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001228 return NULL;
1229 }
1230 s = PyString_AS_STRING(arg);
1231 if (strcmp(s, "double") == 0) {
1232 r = double_format;
1233 }
1234 else if (strcmp(s, "float") == 0) {
1235 r = float_format;
1236 }
1237 else {
1238 PyErr_SetString(PyExc_ValueError,
1239 "__getformat__() argument 1 must be "
1240 "'double' or 'float'");
1241 return NULL;
1242 }
1243
1244 switch (r) {
1245 case unknown_format:
1246 return PyString_FromString("unknown");
1247 case ieee_little_endian_format:
1248 return PyString_FromString("IEEE, little-endian");
1249 case ieee_big_endian_format:
1250 return PyString_FromString("IEEE, big-endian");
1251 default:
1252 Py_FatalError("insane float_format or double_format");
1253 return NULL;
1254 }
1255}
1256
1257PyDoc_STRVAR(float_getformat_doc,
1258"float.__getformat__(typestr) -> string\n"
1259"\n"
1260"You probably don't want to use this function. It exists mainly to be\n"
1261"used in Python's test suite.\n"
1262"\n"
1263"typestr must be 'double' or 'float'. This function returns whichever of\n"
1264"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1265"format of floating point numbers used by the C type named by typestr.");
1266
1267static PyObject *
1268float_setformat(PyTypeObject *v, PyObject* args)
1269{
1270 char* typestr;
1271 char* format;
1272 float_format_type f;
1273 float_format_type detected;
1274 float_format_type *p;
1275
1276 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1277 return NULL;
1278
1279 if (strcmp(typestr, "double") == 0) {
1280 p = &double_format;
1281 detected = detected_double_format;
1282 }
1283 else if (strcmp(typestr, "float") == 0) {
1284 p = &float_format;
1285 detected = detected_float_format;
1286 }
1287 else {
1288 PyErr_SetString(PyExc_ValueError,
1289 "__setformat__() argument 1 must "
1290 "be 'double' or 'float'");
1291 return NULL;
1292 }
1293
1294 if (strcmp(format, "unknown") == 0) {
1295 f = unknown_format;
1296 }
1297 else if (strcmp(format, "IEEE, little-endian") == 0) {
1298 f = ieee_little_endian_format;
1299 }
1300 else if (strcmp(format, "IEEE, big-endian") == 0) {
1301 f = ieee_big_endian_format;
1302 }
1303 else {
1304 PyErr_SetString(PyExc_ValueError,
1305 "__setformat__() argument 2 must be "
1306 "'unknown', 'IEEE, little-endian' or "
1307 "'IEEE, big-endian'");
1308 return NULL;
1309
1310 }
1311
1312 if (f != unknown_format && f != detected) {
1313 PyErr_Format(PyExc_ValueError,
1314 "can only set %s format to 'unknown' or the "
1315 "detected platform value", typestr);
1316 return NULL;
1317 }
1318
1319 *p = f;
1320 Py_RETURN_NONE;
1321}
1322
1323PyDoc_STRVAR(float_setformat_doc,
1324"float.__setformat__(typestr, fmt) -> None\n"
1325"\n"
1326"You probably don't want to use this function. It exists mainly to be\n"
1327"used in Python's test suite.\n"
1328"\n"
1329"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1330"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1331"one of the latter two if it appears to match the underlying C reality.\n"
1332"\n"
1333"Overrides the automatic determination of C-level floating point type.\n"
1334"This affects how floats are converted to and from binary strings.");
1335
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001336static PyObject *
1337float_getzero(PyObject *v, void *closure)
1338{
1339 return PyFloat_FromDouble(0.0);
1340}
1341
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001342static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001343 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1344 "Returns self, the complex conjugate of any float."},
1345 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1346 "Returns the Integral closest to x between 0 and x."},
1347 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1348 "Returns the Integral closest to x, rounding half toward even.\n"
1349 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001350 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001351 {"__getformat__", (PyCFunction)float_getformat,
1352 METH_O|METH_CLASS, float_getformat_doc},
1353 {"__setformat__", (PyCFunction)float_setformat,
1354 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001355 {NULL, NULL} /* sentinel */
1356};
1357
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001358static PyGetSetDef float_getset[] = {
1359 {"real",
1360 (getter)float_float, (setter)NULL,
1361 "the real part of a complex number",
1362 NULL},
1363 {"imag",
1364 (getter)float_getzero, (setter)NULL,
1365 "the imaginary part of a complex number",
1366 NULL},
1367 {NULL} /* Sentinel */
1368};
1369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001370PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371"float(x) -> floating point number\n\
1372\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001373Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374
1375
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001377 float_add, /*nb_add*/
1378 float_sub, /*nb_subtract*/
1379 float_mul, /*nb_multiply*/
1380 float_classic_div, /*nb_divide*/
1381 float_rem, /*nb_remainder*/
1382 float_divmod, /*nb_divmod*/
1383 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001384 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001385 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001386 (unaryfunc)float_abs, /*nb_absolute*/
1387 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001388 0, /*nb_invert*/
1389 0, /*nb_lshift*/
1390 0, /*nb_rshift*/
1391 0, /*nb_and*/
1392 0, /*nb_xor*/
1393 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001394 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001395 float_trunc, /*nb_int*/
1396 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001397 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001398 0, /* nb_oct */
1399 0, /* nb_hex */
1400 0, /* nb_inplace_add */
1401 0, /* nb_inplace_subtract */
1402 0, /* nb_inplace_multiply */
1403 0, /* nb_inplace_divide */
1404 0, /* nb_inplace_remainder */
1405 0, /* nb_inplace_power */
1406 0, /* nb_inplace_lshift */
1407 0, /* nb_inplace_rshift */
1408 0, /* nb_inplace_and */
1409 0, /* nb_inplace_xor */
1410 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001411 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001412 float_div, /* nb_true_divide */
1413 0, /* nb_inplace_floor_divide */
1414 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001415};
1416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001418 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001419 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001420 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001421 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 (destructor)float_dealloc, /* tp_dealloc */
1423 (printfunc)float_print, /* tp_print */
1424 0, /* tp_getattr */
1425 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001426 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427 (reprfunc)float_repr, /* tp_repr */
1428 &float_as_number, /* tp_as_number */
1429 0, /* tp_as_sequence */
1430 0, /* tp_as_mapping */
1431 (hashfunc)float_hash, /* tp_hash */
1432 0, /* tp_call */
1433 (reprfunc)float_str, /* tp_str */
1434 PyObject_GenericGetAttr, /* tp_getattro */
1435 0, /* tp_setattro */
1436 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1438 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439 float_doc, /* tp_doc */
1440 0, /* tp_traverse */
1441 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001442 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443 0, /* tp_weaklistoffset */
1444 0, /* tp_iter */
1445 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001446 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001448 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 0, /* tp_base */
1450 0, /* tp_dict */
1451 0, /* tp_descr_get */
1452 0, /* tp_descr_set */
1453 0, /* tp_dictoffset */
1454 0, /* tp_init */
1455 0, /* tp_alloc */
1456 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001457};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001458
1459void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001460_PyFloat_Init(void)
1461{
1462 /* We attempt to determine if this machine is using IEEE
1463 floating point formats by peering at the bits of some
1464 carefully chosen values. If it looks like we are on an
1465 IEEE platform, the float packing/unpacking routines can
1466 just copy bits, if not they resort to arithmetic & shifts
1467 and masks. The shifts & masks approach works on all finite
1468 values, but what happens to infinities, NaNs and signed
1469 zeroes on packing is an accident, and attempting to unpack
1470 a NaN or an infinity will raise an exception.
1471
1472 Note that if we're on some whacked-out platform which uses
1473 IEEE formats but isn't strictly little-endian or big-
1474 endian, we will fall back to the portable shifts & masks
1475 method. */
1476
1477#if SIZEOF_DOUBLE == 8
1478 {
1479 double x = 9006104071832581.0;
1480 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1481 detected_double_format = ieee_big_endian_format;
1482 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1483 detected_double_format = ieee_little_endian_format;
1484 else
1485 detected_double_format = unknown_format;
1486 }
1487#else
1488 detected_double_format = unknown_format;
1489#endif
1490
1491#if SIZEOF_FLOAT == 4
1492 {
1493 float y = 16711938.0;
1494 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1495 detected_float_format = ieee_big_endian_format;
1496 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1497 detected_float_format = ieee_little_endian_format;
1498 else
1499 detected_float_format = unknown_format;
1500 }
1501#else
1502 detected_float_format = unknown_format;
1503#endif
1504
1505 double_format = detected_double_format;
1506 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001507
1508#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001509 /* Initialize floating point repr */
1510 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001511#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001512}
1513
1514void
Fred Drakefd99de62000-07-09 05:02:18 +00001515PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001516{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001517 PyFloatObject *p;
1518 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001519 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001520 int bc, bf; /* block count, number of freed blocks */
1521 int frem, fsum; /* remaining unfreed floats per block, total */
1522
1523 bc = 0;
1524 bf = 0;
1525 fsum = 0;
1526 list = block_list;
1527 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001528 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001529 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001530 bc++;
1531 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001532 for (i = 0, p = &list->objects[0];
1533 i < N_FLOATOBJECTS;
1534 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001535 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001536 frem++;
1537 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001538 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001539 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001540 list->next = block_list;
1541 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001542 for (i = 0, p = &list->objects[0];
1543 i < N_FLOATOBJECTS;
1544 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001545 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001546 Py_REFCNT(p) == 0) {
1547 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001548 free_list;
1549 free_list = p;
1550 }
1551 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001552 }
1553 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001554 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001555 bf++;
1556 }
1557 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001558 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001559 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001560 if (!Py_VerboseFlag)
1561 return;
1562 fprintf(stderr, "# cleanup floats");
1563 if (!fsum) {
1564 fprintf(stderr, "\n");
1565 }
1566 else {
1567 fprintf(stderr,
1568 ": %d unfreed float%s in %d out of %d block%s\n",
1569 fsum, fsum == 1 ? "" : "s",
1570 bc - bf, bc, bc == 1 ? "" : "s");
1571 }
1572 if (Py_VerboseFlag > 1) {
1573 list = block_list;
1574 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001575 for (i = 0, p = &list->objects[0];
1576 i < N_FLOATOBJECTS;
1577 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001578 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001579 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001580 char buf[100];
1581 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001582 /* XXX(twouters) cast refcount to
1583 long until %zd is universally
1584 available
1585 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001586 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001587 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001588 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001589 }
1590 }
1591 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001592 }
1593 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001594}
Tim Peters9905b942003-03-20 20:53:32 +00001595
1596/*----------------------------------------------------------------------------
1597 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1598 *
1599 * TODO: On platforms that use the standard IEEE-754 single and double
1600 * formats natively, these routines could simply copy the bytes.
1601 */
1602int
1603_PyFloat_Pack4(double x, unsigned char *p, int le)
1604{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001605 if (float_format == unknown_format) {
1606 unsigned char sign;
1607 int e;
1608 double f;
1609 unsigned int fbits;
1610 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001611
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001612 if (le) {
1613 p += 3;
1614 incr = -1;
1615 }
Tim Peters9905b942003-03-20 20:53:32 +00001616
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617 if (x < 0) {
1618 sign = 1;
1619 x = -x;
1620 }
1621 else
1622 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001623
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001625
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001626 /* Normalize f to be in the range [1.0, 2.0) */
1627 if (0.5 <= f && f < 1.0) {
1628 f *= 2.0;
1629 e--;
1630 }
1631 else if (f == 0.0)
1632 e = 0;
1633 else {
1634 PyErr_SetString(PyExc_SystemError,
1635 "frexp() result out of range");
1636 return -1;
1637 }
1638
1639 if (e >= 128)
1640 goto Overflow;
1641 else if (e < -126) {
1642 /* Gradual underflow */
1643 f = ldexp(f, 126 + e);
1644 e = 0;
1645 }
1646 else if (!(e == 0 && f == 0.0)) {
1647 e += 127;
1648 f -= 1.0; /* Get rid of leading 1 */
1649 }
1650
1651 f *= 8388608.0; /* 2**23 */
1652 fbits = (unsigned int)(f + 0.5); /* Round */
1653 assert(fbits <= 8388608);
1654 if (fbits >> 23) {
1655 /* The carry propagated out of a string of 23 1 bits. */
1656 fbits = 0;
1657 ++e;
1658 if (e >= 255)
1659 goto Overflow;
1660 }
1661
1662 /* First byte */
1663 *p = (sign << 7) | (e >> 1);
1664 p += incr;
1665
1666 /* Second byte */
1667 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1668 p += incr;
1669
1670 /* Third byte */
1671 *p = (fbits >> 8) & 0xFF;
1672 p += incr;
1673
1674 /* Fourth byte */
1675 *p = fbits & 0xFF;
1676
1677 /* Done */
1678 return 0;
1679
1680 Overflow:
1681 PyErr_SetString(PyExc_OverflowError,
1682 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001683 return -1;
1684 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001685 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001686 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687 const char *s = (char*)&y;
1688 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001689
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690 if ((float_format == ieee_little_endian_format && !le)
1691 || (float_format == ieee_big_endian_format && le)) {
1692 p += 3;
1693 incr = -1;
1694 }
1695
1696 for (i = 0; i < 4; i++) {
1697 *p = *s++;
1698 p += incr;
1699 }
1700 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001701 }
Tim Peters9905b942003-03-20 20:53:32 +00001702}
1703
1704int
1705_PyFloat_Pack8(double x, unsigned char *p, int le)
1706{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001707 if (double_format == unknown_format) {
1708 unsigned char sign;
1709 int e;
1710 double f;
1711 unsigned int fhi, flo;
1712 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001713
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001714 if (le) {
1715 p += 7;
1716 incr = -1;
1717 }
Tim Peters9905b942003-03-20 20:53:32 +00001718
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001719 if (x < 0) {
1720 sign = 1;
1721 x = -x;
1722 }
1723 else
1724 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001725
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001726 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001727
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001728 /* Normalize f to be in the range [1.0, 2.0) */
1729 if (0.5 <= f && f < 1.0) {
1730 f *= 2.0;
1731 e--;
1732 }
1733 else if (f == 0.0)
1734 e = 0;
1735 else {
1736 PyErr_SetString(PyExc_SystemError,
1737 "frexp() result out of range");
1738 return -1;
1739 }
1740
1741 if (e >= 1024)
1742 goto Overflow;
1743 else if (e < -1022) {
1744 /* Gradual underflow */
1745 f = ldexp(f, 1022 + e);
1746 e = 0;
1747 }
1748 else if (!(e == 0 && f == 0.0)) {
1749 e += 1023;
1750 f -= 1.0; /* Get rid of leading 1 */
1751 }
1752
1753 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1754 f *= 268435456.0; /* 2**28 */
1755 fhi = (unsigned int)f; /* Truncate */
1756 assert(fhi < 268435456);
1757
1758 f -= (double)fhi;
1759 f *= 16777216.0; /* 2**24 */
1760 flo = (unsigned int)(f + 0.5); /* Round */
1761 assert(flo <= 16777216);
1762 if (flo >> 24) {
1763 /* The carry propagated out of a string of 24 1 bits. */
1764 flo = 0;
1765 ++fhi;
1766 if (fhi >> 28) {
1767 /* And it also progagated out of the next 28 bits. */
1768 fhi = 0;
1769 ++e;
1770 if (e >= 2047)
1771 goto Overflow;
1772 }
1773 }
1774
1775 /* First byte */
1776 *p = (sign << 7) | (e >> 4);
1777 p += incr;
1778
1779 /* Second byte */
1780 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1781 p += incr;
1782
1783 /* Third byte */
1784 *p = (fhi >> 16) & 0xFF;
1785 p += incr;
1786
1787 /* Fourth byte */
1788 *p = (fhi >> 8) & 0xFF;
1789 p += incr;
1790
1791 /* Fifth byte */
1792 *p = fhi & 0xFF;
1793 p += incr;
1794
1795 /* Sixth byte */
1796 *p = (flo >> 16) & 0xFF;
1797 p += incr;
1798
1799 /* Seventh byte */
1800 *p = (flo >> 8) & 0xFF;
1801 p += incr;
1802
1803 /* Eighth byte */
1804 *p = flo & 0xFF;
1805 p += incr;
1806
1807 /* Done */
1808 return 0;
1809
1810 Overflow:
1811 PyErr_SetString(PyExc_OverflowError,
1812 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001813 return -1;
1814 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001815 else {
1816 const char *s = (char*)&x;
1817 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001818
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001819 if ((double_format == ieee_little_endian_format && !le)
1820 || (double_format == ieee_big_endian_format && le)) {
1821 p += 7;
1822 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001823 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001824
1825 for (i = 0; i < 8; i++) {
1826 *p = *s++;
1827 p += incr;
1828 }
1829 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001830 }
Tim Peters9905b942003-03-20 20:53:32 +00001831}
1832
1833double
1834_PyFloat_Unpack4(const unsigned char *p, int le)
1835{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001836 if (float_format == unknown_format) {
1837 unsigned char sign;
1838 int e;
1839 unsigned int f;
1840 double x;
1841 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001842
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001843 if (le) {
1844 p += 3;
1845 incr = -1;
1846 }
1847
1848 /* First byte */
1849 sign = (*p >> 7) & 1;
1850 e = (*p & 0x7F) << 1;
1851 p += incr;
1852
1853 /* Second byte */
1854 e |= (*p >> 7) & 1;
1855 f = (*p & 0x7F) << 16;
1856 p += incr;
1857
1858 if (e == 255) {
1859 PyErr_SetString(
1860 PyExc_ValueError,
1861 "can't unpack IEEE 754 special value "
1862 "on non-IEEE platform");
1863 return -1;
1864 }
1865
1866 /* Third byte */
1867 f |= *p << 8;
1868 p += incr;
1869
1870 /* Fourth byte */
1871 f |= *p;
1872
1873 x = (double)f / 8388608.0;
1874
1875 /* XXX This sadly ignores Inf/NaN issues */
1876 if (e == 0)
1877 e = -126;
1878 else {
1879 x += 1.0;
1880 e -= 127;
1881 }
1882 x = ldexp(x, e);
1883
1884 if (sign)
1885 x = -x;
1886
1887 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001888 }
Tim Peters9905b942003-03-20 20:53:32 +00001889 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001890 float x;
1891
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892 if ((float_format == ieee_little_endian_format && !le)
1893 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001894 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001895 char *d = &buf[3];
1896 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001897
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001898 for (i = 0; i < 4; i++) {
1899 *d-- = *p++;
1900 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001901 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001902 }
1903 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001904 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001905 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001906
1907 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001908 }
Tim Peters9905b942003-03-20 20:53:32 +00001909}
1910
1911double
1912_PyFloat_Unpack8(const unsigned char *p, int le)
1913{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001914 if (double_format == unknown_format) {
1915 unsigned char sign;
1916 int e;
1917 unsigned int fhi, flo;
1918 double x;
1919 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001920
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001921 if (le) {
1922 p += 7;
1923 incr = -1;
1924 }
1925
1926 /* First byte */
1927 sign = (*p >> 7) & 1;
1928 e = (*p & 0x7F) << 4;
1929
1930 p += incr;
1931
1932 /* Second byte */
1933 e |= (*p >> 4) & 0xF;
1934 fhi = (*p & 0xF) << 24;
1935 p += incr;
1936
1937 if (e == 2047) {
1938 PyErr_SetString(
1939 PyExc_ValueError,
1940 "can't unpack IEEE 754 special value "
1941 "on non-IEEE platform");
1942 return -1.0;
1943 }
1944
1945 /* Third byte */
1946 fhi |= *p << 16;
1947 p += incr;
1948
1949 /* Fourth byte */
1950 fhi |= *p << 8;
1951 p += incr;
1952
1953 /* Fifth byte */
1954 fhi |= *p;
1955 p += incr;
1956
1957 /* Sixth byte */
1958 flo = *p << 16;
1959 p += incr;
1960
1961 /* Seventh byte */
1962 flo |= *p << 8;
1963 p += incr;
1964
1965 /* Eighth byte */
1966 flo |= *p;
1967
1968 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1969 x /= 268435456.0; /* 2**28 */
1970
1971 if (e == 0)
1972 e = -1022;
1973 else {
1974 x += 1.0;
1975 e -= 1023;
1976 }
1977 x = ldexp(x, e);
1978
1979 if (sign)
1980 x = -x;
1981
1982 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001983 }
Tim Peters9905b942003-03-20 20:53:32 +00001984 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001985 double x;
1986
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001987 if ((double_format == ieee_little_endian_format && !le)
1988 || (double_format == ieee_big_endian_format && le)) {
1989 char buf[8];
1990 char *d = &buf[7];
1991 int i;
1992
1993 for (i = 0; i < 8; i++) {
1994 *d-- = *p++;
1995 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001996 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997 }
1998 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001999 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002000 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002001
2002 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002003 }
Tim Peters9905b942003-03-20 20:53:32 +00002004}