blob: fc4dd218361f898ff52b09e10887cf36db7a7029 [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"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Christian Heimesc94e2b52008-01-14 04:13:37 +000013
Jack Janseneddc1442003-11-20 01:44:59 +000014#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000015extern double fmod(double, double);
16extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000017#endif
18
Neal Norwitz5f95a792008-01-25 08:04:16 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000026#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000027#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
30 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
32};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
42 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000043 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000047 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 q = p + N_FLOATOBJECTS;
51 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000052 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 return p + N_FLOATOBJECTS - 1;
55}
56
Christian Heimesdfdfaab2007-12-01 11:20:10 +000057double
58PyFloat_GetMax(void)
59{
60 return DBL_MAX;
61}
62
63double
64PyFloat_GetMin(void)
65{
66 return DBL_MIN;
67}
68
Christian Heimesc94e2b52008-01-14 04:13:37 +000069static PyTypeObject FloatInfoType = {0};
70
71PyDoc_STRVAR(floatinfo__doc__,
72"sys.floatinfo\n\
73\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
79 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
96};
97
98static PyStructSequence_Desc floatinfo_desc = {
99 "sys.floatinfo", /* name */
100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
103};
104
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Christian Heimesc94e2b52008-01-14 04:13:37 +0000108 static PyObject* floatinfo;
109 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000110
Christian Heimesc94e2b52008-01-14 04:13:37 +0000111 if (floatinfo != NULL) {
112 Py_INCREF(floatinfo);
113 return floatinfo;
114 }
115 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
116
117 floatinfo = PyStructSequence_New(&FloatInfoType);
118 if (floatinfo == NULL) {
119 return NULL;
120 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000121
Christian Heimesc94e2b52008-01-14 04:13:37 +0000122#define SetIntFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
124#define SetDblFlag(flag) \
125 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000126
Christian Heimesc94e2b52008-01-14 04:13:37 +0000127 SetDblFlag(DBL_MAX);
128 SetIntFlag(DBL_MAX_EXP);
129 SetIntFlag(DBL_MAX_10_EXP);
130 SetDblFlag(DBL_MIN);
131 SetIntFlag(DBL_MIN_EXP);
132 SetIntFlag(DBL_MIN_10_EXP);
133 SetIntFlag(DBL_DIG);
134 SetIntFlag(DBL_MANT_DIG);
135 SetDblFlag(DBL_EPSILON);
136 SetIntFlag(FLT_RADIX);
137 SetIntFlag(FLT_ROUNDS);
138#undef SetIntFlag
139#undef SetDblFlag
140
141 if (PyErr_Occurred()) {
142 Py_CLEAR(floatinfo);
143 return NULL;
144 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000145
Christian Heimesc94e2b52008-01-14 04:13:37 +0000146 Py_INCREF(floatinfo);
147 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000148}
149
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000153 register PyFloatObject *op;
154 if (free_list == NULL) {
155 if ((free_list = fill_free_list()) == NULL)
156 return NULL;
157 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000158 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000159 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000160 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000161 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000162 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Petersef14d732000-09-23 03:39:17 +0000166/**************************************************************************
167RED_FLAG 22-Sep-2000 tim
168PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
169
1701. If v was a regular string, *pend was set to point to its terminating
171 null byte. That's useless (the caller can find that without any
172 help from this function!).
173
1742. If v was a Unicode string, or an object convertible to a character
175 buffer, *pend was set to point into stack trash (the auto temp
176 vector holding the character buffer). That was downright dangerous.
177
178Since we can't change the interface of a public API function, pend is
179still supported but now *officially* useless: if pend is not NULL,
180*pend is set to NULL.
181**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000183PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000185 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000186 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000187 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000188#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000189 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000190#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000191 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192
Tim Petersef14d732000-09-23 03:39:17 +0000193 if (pend)
194 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000195 if (PyString_Check(v)) {
196 s = PyString_AS_STRING(v);
197 len = PyString_GET_SIZE(v);
198 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000199#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000200 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000201 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000203 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 return NULL;
205 }
Tim Petersef14d732000-09-23 03:39:17 +0000206 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000207 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000208 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000209 NULL))
210 return NULL;
211 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000212 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000213 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000214#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000215 else if (PyObject_AsCharBuffer(v, &s, &len)) {
216 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000217 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000219 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000220
Guido van Rossum4c08d552000-03-10 22:55:18 +0000221 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000222 while (*s && isspace(Py_CHARMASK(*s)))
223 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000224 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000225 PyErr_SetString(PyExc_ValueError, "empty string for float()");
226 return NULL;
227 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000228 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000229 /* We don't care about overflow or underflow. If the platform supports
230 * them, infinities and signed zeroes (on underflow) are fine.
231 * However, strtod can return 0 for denormalized numbers, where atof
232 * does not. So (alas!) we special-case a zero result. Note that
233 * whether strtod sets errno on underflow is not defined, so we can't
234 * key off errno.
235 */
Tim Peters858346e2000-09-25 21:01:28 +0000236 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000237 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000238 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000239 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000240 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000241 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000242 if (end > last)
243 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000244 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000245 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000246 char *p = (char*)sp;
247 int sign = 1;
248
249 if (*p == '-') {
250 sign = -1;
251 p++;
252 }
253 if (*p == '+') {
254 p++;
255 }
256 if (PyOS_strnicmp(p, "inf", 4) == 0) {
257 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
258 }
259#ifdef Py_NAN
260 if(PyOS_strnicmp(p, "nan", 4) == 0) {
261 return PyFloat_FromDouble(Py_NAN);
262 }
263#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000264 PyOS_snprintf(buffer, sizeof(buffer),
265 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000266 PyErr_SetString(PyExc_ValueError, buffer);
267 return NULL;
268 }
269 /* Since end != s, the platform made *some* kind of sense out
270 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000271 while (*end && isspace(Py_CHARMASK(*end)))
272 end++;
273 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000274 PyOS_snprintf(buffer, sizeof(buffer),
275 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000276 PyErr_SetString(PyExc_ValueError, buffer);
277 return NULL;
278 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000279 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000280 PyErr_SetString(PyExc_ValueError,
281 "null byte in argument for float()");
282 return NULL;
283 }
Tim Petersef14d732000-09-23 03:39:17 +0000284 if (x == 0.0) {
285 /* See above -- may have been strtod being anal
286 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000287 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000288 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000289 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000290 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000291 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000292 return PyFloat_FromDouble(x);
293}
294
Guido van Rossum234f9421993-06-17 12:35:49 +0000295static void
Fred Drakefd99de62000-07-09 05:02:18 +0000296float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000297{
Guido van Rossum9475a232001-10-05 20:51:39 +0000298 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000299 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000300 free_list = op;
301 }
302 else
Christian Heimese93237d2007-12-19 02:37:44 +0000303 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000304}
305
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306double
Fred Drakefd99de62000-07-09 05:02:18 +0000307PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 PyNumberMethods *nb;
310 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313 if (op && PyFloat_Check(op))
314 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000315
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000316 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000317 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318 return -1;
319 }
Tim Petersd2364e82001-11-01 20:09:42 +0000320
Christian Heimese93237d2007-12-19 02:37:44 +0000321 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000322 PyErr_SetString(PyExc_TypeError, "a float is required");
323 return -1;
324 }
325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000327 if (fo == NULL)
328 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 if (!PyFloat_Check(fo)) {
330 PyErr_SetString(PyExc_TypeError,
331 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000332 return -1;
333 }
Tim Petersd2364e82001-11-01 20:09:42 +0000334
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 val = PyFloat_AS_DOUBLE(fo);
336 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000337
Guido van Rossumb6775db1994-08-01 11:34:53 +0000338 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339}
340
341/* Methods */
342
Tim Peters97019e42001-11-28 22:43:45 +0000343static void
344format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
346 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000347 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000348 int i;
349
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350 /* Subroutine for float_repr and float_print.
351 We want float numbers to be recognizable as such,
352 i.e., they should contain a decimal point or an exponent.
353 However, %g may print the number as an integer;
354 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000355
356 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000357 PyOS_snprintf(format, 32, "%%.%ig", precision);
358 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359 cp = buf;
360 if (*cp == '-')
361 cp++;
362 for (; *cp != '\0'; cp++) {
363 /* Any non-digit means it's not an integer;
364 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000365 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 break;
367 }
368 if (*cp == '\0') {
369 *cp++ = '.';
370 *cp++ = '0';
371 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000372 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000374 /* Checking the next three chars should be more than enough to
375 * detect inf or nan, even on Windows. We check for inf or nan
376 * at last because they are rare cases.
377 */
378 for (i=0; *cp != '\0' && i<3; cp++, i++) {
379 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
380 continue;
381 /* found something that is neither a digit nor point
382 * it might be a NaN or INF
383 */
384#ifdef Py_NAN
385 if (Py_IS_NAN(v->ob_fval)) {
386 strcpy(buf, "nan");
387 }
388 else
389#endif
390 if (Py_IS_INFINITY(v->ob_fval)) {
391 cp = buf;
392 if (*cp == '-')
393 cp++;
394 strcpy(cp, "inf");
395 }
396 break;
397 }
398
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Tim Peters97019e42001-11-28 22:43:45 +0000401/* XXX PyFloat_AsStringEx should not be a public API function (for one
402 XXX thing, its signature passes a buffer without a length; for another,
403 XXX it isn't useful outside this file).
404*/
405void
406PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
407{
408 format_float(buf, 100, v, precision);
409}
410
Christian Heimesf15c66e2007-12-11 00:54:34 +0000411#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000412/* The following function is based on Tcl_PrintDouble,
413 * from tclUtil.c.
414 */
415
416#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
417#define is_nan(d) ((d) != (d))
418
419static void
420format_double_repr(char *dst, double value)
421{
422 char *p, c;
423 int exp;
424 int signum;
425 char buffer[30];
426
427 /*
428 * Handle NaN.
429 */
430
431 if (is_nan(value)) {
432 strcpy(dst, "nan");
433 return;
434 }
435
436 /*
437 * Handle infinities.
438 */
439
440 if (is_infinite(value)) {
441 if (value < 0) {
442 strcpy(dst, "-inf");
443 } else {
444 strcpy(dst, "inf");
445 }
446 return;
447 }
448
449 /*
450 * Ordinary (normal and denormal) values.
451 */
452
453 exp = _PyFloat_Digits(buffer, value, &signum)+1;
454 if (signum) {
455 *dst++ = '-';
456 }
457 p = buffer;
458 if (exp < -3 || exp > 17) {
459 /*
460 * E format for numbers < 1e-3 or >= 1e17.
461 */
462
463 *dst++ = *p++;
464 c = *p;
465 if (c != '\0') {
466 *dst++ = '.';
467 while (c != '\0') {
468 *dst++ = c;
469 c = *++p;
470 }
471 }
472 sprintf(dst, "e%+d", exp-1);
473 } else {
474 /*
475 * F format for others.
476 */
477
478 if (exp <= 0) {
479 *dst++ = '0';
480 }
481 c = *p;
482 while (exp-- > 0) {
483 if (c != '\0') {
484 *dst++ = c;
485 c = *++p;
486 } else {
487 *dst++ = '0';
488 }
489 }
490 *dst++ = '.';
491 if (c == '\0') {
492 *dst++ = '0';
493 } else {
494 while (++exp < 0) {
495 *dst++ = '0';
496 }
497 while (c != '\0') {
498 *dst++ = c;
499 c = *++p;
500 }
501 }
502 *dst++ = '\0';
503 }
504}
505
506static void
507format_float_repr(char *buf, PyFloatObject *v)
508{
509 assert(PyFloat_Check(v));
510 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
511}
512
Christian Heimesf15c66e2007-12-11 00:54:34 +0000513#endif /* Py_BROKEN_REPR */
514
Neil Schemenauer32117e52001-01-04 01:44:34 +0000515/* Macro and helper that convert PyObject obj to a C double and store
516 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000517 slot function. If conversion to double raises an exception, obj is
518 set to NULL, and the function invoking this macro returns NULL. If
519 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
520 stored in obj, and returned from the function invoking this macro.
521*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000522#define CONVERT_TO_DOUBLE(obj, dbl) \
523 if (PyFloat_Check(obj)) \
524 dbl = PyFloat_AS_DOUBLE(obj); \
525 else if (convert_to_double(&(obj), &(dbl)) < 0) \
526 return obj;
527
528static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000529convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000530{
531 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000532
Neil Schemenauer32117e52001-01-04 01:44:34 +0000533 if (PyInt_Check(obj)) {
534 *dbl = (double)PyInt_AS_LONG(obj);
535 }
536 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000538 if (*dbl == -1.0 && PyErr_Occurred()) {
539 *v = NULL;
540 return -1;
541 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000542 }
543 else {
544 Py_INCREF(Py_NotImplemented);
545 *v = Py_NotImplemented;
546 return -1;
547 }
548 return 0;
549}
550
Guido van Rossum57072eb1999-12-23 19:00:28 +0000551/* Precisions used by repr() and str(), respectively.
552
553 The repr() precision (17 significant decimal digits) is the minimal number
554 that is guaranteed to have enough precision so that if the number is read
555 back in the exact same binary value is recreated. This is true for IEEE
556 floating point by design, and also happens to work for all other modern
557 hardware.
558
559 The str() precision is chosen so that in most cases, the rounding noise
560 created by various operations is suppressed, while giving plenty of
561 precision for practical use.
562
563*/
564
565#define PREC_REPR 17
566#define PREC_STR 12
567
Tim Peters97019e42001-11-28 22:43:45 +0000568/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
569 XXX they pass a char buffer without passing a length.
570*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000571void
Fred Drakefd99de62000-07-09 05:02:18 +0000572PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000573{
Tim Peters97019e42001-11-28 22:43:45 +0000574 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000575}
576
Tim Peters72f98e92001-05-08 15:19:57 +0000577void
578PyFloat_AsReprString(char *buf, PyFloatObject *v)
579{
Tim Peters97019e42001-11-28 22:43:45 +0000580 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000581}
582
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000583/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000584static int
Fred Drakefd99de62000-07-09 05:02:18 +0000585float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586{
587 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000588 format_float(buf, sizeof(buf), v,
589 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000590 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000592 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000593 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594}
595
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000597float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000599#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000600 char buf[30];
601 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000602#else
603 char buf[100];
604 format_float(buf, sizeof(buf), v, PREC_REPR);
605#endif
606
Guido van Rossum57072eb1999-12-23 19:00:28 +0000607 return PyString_FromString(buf);
608}
609
610static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000611float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000612{
613 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000614 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616}
617
Tim Peters307fa782004-09-23 08:06:40 +0000618/* Comparison is pretty much a nightmare. When comparing float to float,
619 * we do it as straightforwardly (and long-windedly) as conceivable, so
620 * that, e.g., Python x == y delivers the same result as the platform
621 * C x == y when x and/or y is a NaN.
622 * When mixing float with an integer type, there's no good *uniform* approach.
623 * Converting the double to an integer obviously doesn't work, since we
624 * may lose info from fractional bits. Converting the integer to a double
625 * also has two failure modes: (1) a long int may trigger overflow (too
626 * large to fit in the dynamic range of a C double); (2) even a C long may have
627 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
628 * 63 bits of precision, but a C double probably has only 53), and then
629 * we can falsely claim equality when low-order integer bits are lost by
630 * coercion to double. So this part is painful too.
631 */
632
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633static PyObject*
634float_richcompare(PyObject *v, PyObject *w, int op)
635{
636 double i, j;
637 int r = 0;
638
Tim Peters307fa782004-09-23 08:06:40 +0000639 assert(PyFloat_Check(v));
640 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000641
Tim Peters307fa782004-09-23 08:06:40 +0000642 /* Switch on the type of w. Set i and j to doubles to be compared,
643 * and op to the richcomp to use.
644 */
645 if (PyFloat_Check(w))
646 j = PyFloat_AS_DOUBLE(w);
647
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000648 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000649 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000650 /* If i is an infinity, its magnitude exceeds any
651 * finite integer, so it doesn't matter which int we
652 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000653 */
654 j = 0.0;
655 else
656 goto Unimplemented;
657 }
658
659 else if (PyInt_Check(w)) {
660 long jj = PyInt_AS_LONG(w);
661 /* In the worst realistic case I can imagine, C double is a
662 * Cray single with 48 bits of precision, and long has 64
663 * bits.
664 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000665#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000666 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
667 if (abs >> 48) {
668 /* Needs more than 48 bits. Make it take the
669 * PyLong path.
670 */
671 PyObject *result;
672 PyObject *ww = PyLong_FromLong(jj);
673
674 if (ww == NULL)
675 return NULL;
676 result = float_richcompare(v, ww, op);
677 Py_DECREF(ww);
678 return result;
679 }
680#endif
681 j = (double)jj;
682 assert((long)j == jj);
683 }
684
685 else if (PyLong_Check(w)) {
686 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
687 int wsign = _PyLong_Sign(w);
688 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000689 int exponent;
690
691 if (vsign != wsign) {
692 /* Magnitudes are irrelevant -- the signs alone
693 * determine the outcome.
694 */
695 i = (double)vsign;
696 j = (double)wsign;
697 goto Compare;
698 }
699 /* The signs are the same. */
700 /* Convert w to a double if it fits. In particular, 0 fits. */
701 nbits = _PyLong_NumBits(w);
702 if (nbits == (size_t)-1 && PyErr_Occurred()) {
703 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000704 * to hold the # of bits. Replace with little doubles
705 * that give the same outcome -- w is so large that
706 * its magnitude must exceed the magnitude of any
707 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000708 */
709 PyErr_Clear();
710 i = (double)vsign;
711 assert(wsign != 0);
712 j = wsign * 2.0;
713 goto Compare;
714 }
715 if (nbits <= 48) {
716 j = PyLong_AsDouble(w);
717 /* It's impossible that <= 48 bits overflowed. */
718 assert(j != -1.0 || ! PyErr_Occurred());
719 goto Compare;
720 }
721 assert(wsign != 0); /* else nbits was 0 */
722 assert(vsign != 0); /* if vsign were 0, then since wsign is
723 * not 0, we would have taken the
724 * vsign != wsign branch at the start */
725 /* We want to work with non-negative numbers. */
726 if (vsign < 0) {
727 /* "Multiply both sides" by -1; this also swaps the
728 * comparator.
729 */
730 i = -i;
731 op = _Py_SwappedOp[op];
732 }
733 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000734 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000735 /* exponent is the # of bits in v before the radix point;
736 * we know that nbits (the # of bits in w) > 48 at this point
737 */
738 if (exponent < 0 || (size_t)exponent < nbits) {
739 i = 1.0;
740 j = 2.0;
741 goto Compare;
742 }
743 if ((size_t)exponent > nbits) {
744 i = 2.0;
745 j = 1.0;
746 goto Compare;
747 }
748 /* v and w have the same number of bits before the radix
749 * point. Construct two longs that have the same comparison
750 * outcome.
751 */
752 {
753 double fracpart;
754 double intpart;
755 PyObject *result = NULL;
756 PyObject *one = NULL;
757 PyObject *vv = NULL;
758 PyObject *ww = w;
759
760 if (wsign < 0) {
761 ww = PyNumber_Negative(w);
762 if (ww == NULL)
763 goto Error;
764 }
765 else
766 Py_INCREF(ww);
767
768 fracpart = modf(i, &intpart);
769 vv = PyLong_FromDouble(intpart);
770 if (vv == NULL)
771 goto Error;
772
773 if (fracpart != 0.0) {
774 /* Shift left, and or a 1 bit into vv
775 * to represent the lost fraction.
776 */
777 PyObject *temp;
778
779 one = PyInt_FromLong(1);
780 if (one == NULL)
781 goto Error;
782
783 temp = PyNumber_Lshift(ww, one);
784 if (temp == NULL)
785 goto Error;
786 Py_DECREF(ww);
787 ww = temp;
788
789 temp = PyNumber_Lshift(vv, one);
790 if (temp == NULL)
791 goto Error;
792 Py_DECREF(vv);
793 vv = temp;
794
795 temp = PyNumber_Or(vv, one);
796 if (temp == NULL)
797 goto Error;
798 Py_DECREF(vv);
799 vv = temp;
800 }
801
802 r = PyObject_RichCompareBool(vv, ww, op);
803 if (r < 0)
804 goto Error;
805 result = PyBool_FromLong(r);
806 Error:
807 Py_XDECREF(vv);
808 Py_XDECREF(ww);
809 Py_XDECREF(one);
810 return result;
811 }
812 } /* else if (PyLong_Check(w)) */
813
814 else /* w isn't float, int, or long */
815 goto Unimplemented;
816
817 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000818 PyFPE_START_PROTECT("richcompare", return NULL)
819 switch (op) {
820 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000821 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000822 break;
823 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000824 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000825 break;
826 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000827 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000828 break;
829 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000830 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000831 break;
832 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000833 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000834 break;
835 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000836 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000837 break;
838 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000839 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000840 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000841
842 Unimplemented:
843 Py_INCREF(Py_NotImplemented);
844 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000845}
846
Guido van Rossum9bfef441993-03-29 10:43:31 +0000847static long
Fred Drakefd99de62000-07-09 05:02:18 +0000848float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000849{
Tim Peters39dce292000-08-15 03:34:48 +0000850 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000851}
852
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000853static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000854float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000855{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000856 double a,b;
857 CONVERT_TO_DOUBLE(v, a);
858 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000859 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000860 a = a + b;
861 PyFPE_END_PROTECT(a)
862 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000863}
864
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000865static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000866float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000867{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000868 double a,b;
869 CONVERT_TO_DOUBLE(v, a);
870 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000871 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000872 a = a - b;
873 PyFPE_END_PROTECT(a)
874 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875}
876
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000878float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000880 double a,b;
881 CONVERT_TO_DOUBLE(v, a);
882 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000883 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000884 a = a * b;
885 PyFPE_END_PROTECT(a)
886 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000887}
888
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000890float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000891{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000892 double a,b;
893 CONVERT_TO_DOUBLE(v, a);
894 CONVERT_TO_DOUBLE(w, b);
895 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000896 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000897 return NULL;
898 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000899 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000900 a = a / b;
901 PyFPE_END_PROTECT(a)
902 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000903}
904
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000905static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000906float_classic_div(PyObject *v, PyObject *w)
907{
908 double a,b;
909 CONVERT_TO_DOUBLE(v, a);
910 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000911 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000912 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
913 return NULL;
914 if (b == 0.0) {
915 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
916 return NULL;
917 }
918 PyFPE_START_PROTECT("divide", return 0)
919 a = a / b;
920 PyFPE_END_PROTECT(a)
921 return PyFloat_FromDouble(a);
922}
923
924static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000925float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000926{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000927 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000928 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000929 CONVERT_TO_DOUBLE(v, vx);
930 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000931 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000933 return NULL;
934 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000935 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000936 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000937 /* note: checking mod*wx < 0 is incorrect -- underflows to
938 0 if wx < sqrt(smallest nonzero double) */
939 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000940 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000941 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000942 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000944}
945
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000947float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000948{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000949 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000950 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000951 CONVERT_TO_DOUBLE(v, vx);
952 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000953 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000955 return NULL;
956 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000957 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000958 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000959 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000960 exact multiple of wx. But this is fp arithmetic, and fp
961 vx - mod is an approximation; the result is that div may
962 not be an exact integral value after the division, although
963 it will always be very close to one.
964 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000965 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000966 if (mod) {
967 /* ensure the remainder has the same sign as the denominator */
968 if ((wx < 0) != (mod < 0)) {
969 mod += wx;
970 div -= 1.0;
971 }
972 }
973 else {
974 /* the remainder is zero, and in the presence of signed zeroes
975 fmod returns different results across platforms; ensure
976 it has the same sign as the denominator; we'd like to do
977 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000978 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000979 if (wx < 0.0)
980 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000981 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000982 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000983 if (div) {
984 floordiv = floor(div);
985 if (div - floordiv > 0.5)
986 floordiv += 1.0;
987 }
988 else {
989 /* div is zero - get the same sign as the true quotient */
990 div *= div; /* hide "div = +0" from optimizers */
991 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
992 }
993 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000994 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000995}
996
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000998float_floor_div(PyObject *v, PyObject *w)
999{
1000 PyObject *t, *r;
1001
1002 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +00001003 if (t == NULL || t == Py_NotImplemented)
1004 return t;
1005 assert(PyTuple_CheckExact(t));
1006 r = PyTuple_GET_ITEM(t, 0);
1007 Py_INCREF(r);
1008 Py_DECREF(t);
1009 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001010}
1011
1012static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001013float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001014{
1015 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001016
1017 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001018 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001019 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001020 return NULL;
1021 }
1022
Neil Schemenauer32117e52001-01-04 01:44:34 +00001023 CONVERT_TO_DOUBLE(v, iv);
1024 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001025
1026 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001027 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001028 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001029 }
Tim Peters96685bf2001-08-23 22:31:37 +00001030 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001031 if (iw < 0.0) {
1032 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001033 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001034 return NULL;
1035 }
1036 return PyFloat_FromDouble(0.0);
1037 }
Tim Peterse87568d2003-05-24 20:18:24 +00001038 if (iv < 0.0) {
1039 /* Whether this is an error is a mess, and bumps into libm
1040 * bugs so we have to figure it out ourselves.
1041 */
1042 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001043 PyErr_SetString(PyExc_ValueError, "negative number "
1044 "cannot be raised to a fractional power");
1045 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001046 }
1047 /* iw is an exact integer, albeit perhaps a very large one.
1048 * -1 raised to an exact integer should never be exceptional.
1049 * Alas, some libms (chiefly glibc as of early 2003) return
1050 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1051 * happen to be representable in a *C* integer. That's a
1052 * bug; we let that slide in math.pow() (which currently
1053 * reflects all platform accidents), but not for Python's **.
1054 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001055 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001056 /* Return 1 if iw is even, -1 if iw is odd; there's
1057 * no guarantee that any C integral type is big
1058 * enough to hold iw, so we have to check this
1059 * indirectly.
1060 */
1061 ix = floor(iw * 0.5) * 2.0;
1062 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1063 }
1064 /* Else iv != -1.0, and overflow or underflow are possible.
1065 * Unless we're to write pow() ourselves, we have to trust
1066 * the platform to do this correctly.
1067 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001068 }
Tim Peters96685bf2001-08-23 22:31:37 +00001069 errno = 0;
1070 PyFPE_START_PROTECT("pow", return NULL)
1071 ix = pow(iv, iw);
1072 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001073 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001074 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001075 /* We don't expect any errno value other than ERANGE, but
1076 * the range of libm bugs appears unbounded.
1077 */
Alex Martelli348dc882006-08-23 22:17:59 +00001078 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1079 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001080 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001081 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001082 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001083}
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001086float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001087{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001088 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001089}
1090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001091static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001092float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001093{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001094 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001095}
1096
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001097static int
Fred Drakefd99de62000-07-09 05:02:18 +00001098float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001099{
1100 return v->ob_fval != 0.0;
1101}
1102
Guido van Rossum234f9421993-06-17 12:35:49 +00001103static int
Fred Drakefd99de62000-07-09 05:02:18 +00001104float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001105{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001106 if (PyInt_Check(*pw)) {
1107 long x = PyInt_AsLong(*pw);
1108 *pw = PyFloat_FromDouble((double)x);
1109 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001110 return 0;
1111 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001113 double x = PyLong_AsDouble(*pw);
1114 if (x == -1.0 && PyErr_Occurred())
1115 return -1;
1116 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001117 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001118 return 0;
1119 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001120 else if (PyFloat_Check(*pw)) {
1121 Py_INCREF(*pv);
1122 Py_INCREF(*pw);
1123 return 0;
1124 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001125 return 1; /* Can't do it */
1126}
1127
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001128static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001129float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001130{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001132 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001133
1134 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001135 /* Try to get out cheap if this fits in a Python int. The attempt
1136 * to cast to long must be protected, as C doesn't define what
1137 * happens if the double is too big to fit in a long. Some rare
1138 * systems raise an exception then (RISCOS was mentioned as one,
1139 * and someone using a non-default option on Sun also bumped into
1140 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1141 * still be vulnerable: if a long has more bits of precision than
1142 * a double, casting MIN/MAX to double may yield an approximation,
1143 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1144 * yield true from the C expression wholepart<=LONG_MAX, despite
1145 * that wholepart is actually greater than LONG_MAX.
1146 */
1147 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1148 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001149 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001150 }
1151 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001152}
1153
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001154static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001155float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001156{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001157 if (PyFloat_CheckExact(v))
1158 Py_INCREF(v);
1159 else
1160 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001161 return v;
1162}
1163
1164
Jeremy Hylton938ace62002-07-17 16:30:39 +00001165static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001166float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1167
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168static PyObject *
1169float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1170{
1171 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001172 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173
Guido van Rossumbef14172001-08-29 15:47:46 +00001174 if (type != &PyFloat_Type)
1175 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1177 return NULL;
1178 if (PyString_Check(x))
1179 return PyFloat_FromString(x, NULL);
1180 return PyNumber_Float(x);
1181}
1182
Guido van Rossumbef14172001-08-29 15:47:46 +00001183/* Wimpy, slow approach to tp_new calls for subtypes of float:
1184 first create a regular float from whatever arguments we got,
1185 then allocate a subtype instance and initialize its ob_fval
1186 from the regular float. The regular float is then thrown away.
1187*/
1188static PyObject *
1189float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1190{
Anthony Baxter377be112006-04-11 06:54:30 +00001191 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001192
1193 assert(PyType_IsSubtype(type, &PyFloat_Type));
1194 tmp = float_new(&PyFloat_Type, args, kwds);
1195 if (tmp == NULL)
1196 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001197 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001198 newobj = type->tp_alloc(type, 0);
1199 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001200 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001201 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001202 }
Anthony Baxter377be112006-04-11 06:54:30 +00001203 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001204 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001205 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001206}
1207
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001208static PyObject *
1209float_getnewargs(PyFloatObject *v)
1210{
1211 return Py_BuildValue("(d)", v->ob_fval);
1212}
1213
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001214/* this is for the benefit of the pack/unpack routines below */
1215
1216typedef enum {
1217 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1218} float_format_type;
1219
1220static float_format_type double_format, float_format;
1221static float_format_type detected_double_format, detected_float_format;
1222
1223static PyObject *
1224float_getformat(PyTypeObject *v, PyObject* arg)
1225{
1226 char* s;
1227 float_format_type r;
1228
1229 if (!PyString_Check(arg)) {
1230 PyErr_Format(PyExc_TypeError,
1231 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001232 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001233 return NULL;
1234 }
1235 s = PyString_AS_STRING(arg);
1236 if (strcmp(s, "double") == 0) {
1237 r = double_format;
1238 }
1239 else if (strcmp(s, "float") == 0) {
1240 r = float_format;
1241 }
1242 else {
1243 PyErr_SetString(PyExc_ValueError,
1244 "__getformat__() argument 1 must be "
1245 "'double' or 'float'");
1246 return NULL;
1247 }
1248
1249 switch (r) {
1250 case unknown_format:
1251 return PyString_FromString("unknown");
1252 case ieee_little_endian_format:
1253 return PyString_FromString("IEEE, little-endian");
1254 case ieee_big_endian_format:
1255 return PyString_FromString("IEEE, big-endian");
1256 default:
1257 Py_FatalError("insane float_format or double_format");
1258 return NULL;
1259 }
1260}
1261
1262PyDoc_STRVAR(float_getformat_doc,
1263"float.__getformat__(typestr) -> string\n"
1264"\n"
1265"You probably don't want to use this function. It exists mainly to be\n"
1266"used in Python's test suite.\n"
1267"\n"
1268"typestr must be 'double' or 'float'. This function returns whichever of\n"
1269"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1270"format of floating point numbers used by the C type named by typestr.");
1271
1272static PyObject *
1273float_setformat(PyTypeObject *v, PyObject* args)
1274{
1275 char* typestr;
1276 char* format;
1277 float_format_type f;
1278 float_format_type detected;
1279 float_format_type *p;
1280
1281 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1282 return NULL;
1283
1284 if (strcmp(typestr, "double") == 0) {
1285 p = &double_format;
1286 detected = detected_double_format;
1287 }
1288 else if (strcmp(typestr, "float") == 0) {
1289 p = &float_format;
1290 detected = detected_float_format;
1291 }
1292 else {
1293 PyErr_SetString(PyExc_ValueError,
1294 "__setformat__() argument 1 must "
1295 "be 'double' or 'float'");
1296 return NULL;
1297 }
1298
1299 if (strcmp(format, "unknown") == 0) {
1300 f = unknown_format;
1301 }
1302 else if (strcmp(format, "IEEE, little-endian") == 0) {
1303 f = ieee_little_endian_format;
1304 }
1305 else if (strcmp(format, "IEEE, big-endian") == 0) {
1306 f = ieee_big_endian_format;
1307 }
1308 else {
1309 PyErr_SetString(PyExc_ValueError,
1310 "__setformat__() argument 2 must be "
1311 "'unknown', 'IEEE, little-endian' or "
1312 "'IEEE, big-endian'");
1313 return NULL;
1314
1315 }
1316
1317 if (f != unknown_format && f != detected) {
1318 PyErr_Format(PyExc_ValueError,
1319 "can only set %s format to 'unknown' or the "
1320 "detected platform value", typestr);
1321 return NULL;
1322 }
1323
1324 *p = f;
1325 Py_RETURN_NONE;
1326}
1327
1328PyDoc_STRVAR(float_setformat_doc,
1329"float.__setformat__(typestr, fmt) -> None\n"
1330"\n"
1331"You probably don't want to use this function. It exists mainly to be\n"
1332"used in Python's test suite.\n"
1333"\n"
1334"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1335"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1336"one of the latter two if it appears to match the underlying C reality.\n"
1337"\n"
1338"Overrides the automatic determination of C-level floating point type.\n"
1339"This affects how floats are converted to and from binary strings.");
1340
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001341static PyObject *
1342float_getzero(PyObject *v, void *closure)
1343{
1344 return PyFloat_FromDouble(0.0);
1345}
1346
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001347static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001348 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1349 "Returns self, the complex conjugate of any float."},
1350 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1351 "Returns the Integral closest to x between 0 and x."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001352 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001353 {"__getformat__", (PyCFunction)float_getformat,
1354 METH_O|METH_CLASS, float_getformat_doc},
1355 {"__setformat__", (PyCFunction)float_setformat,
1356 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001357 {NULL, NULL} /* sentinel */
1358};
1359
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001360static PyGetSetDef float_getset[] = {
1361 {"real",
1362 (getter)float_float, (setter)NULL,
1363 "the real part of a complex number",
1364 NULL},
1365 {"imag",
1366 (getter)float_getzero, (setter)NULL,
1367 "the imaginary part of a complex number",
1368 NULL},
1369 {NULL} /* Sentinel */
1370};
1371
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001372PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373"float(x) -> floating point number\n\
1374\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001375Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376
1377
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001378static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001379 float_add, /*nb_add*/
1380 float_sub, /*nb_subtract*/
1381 float_mul, /*nb_multiply*/
1382 float_classic_div, /*nb_divide*/
1383 float_rem, /*nb_remainder*/
1384 float_divmod, /*nb_divmod*/
1385 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001386 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001387 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001388 (unaryfunc)float_abs, /*nb_absolute*/
1389 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001390 0, /*nb_invert*/
1391 0, /*nb_lshift*/
1392 0, /*nb_rshift*/
1393 0, /*nb_and*/
1394 0, /*nb_xor*/
1395 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001396 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001397 float_trunc, /*nb_int*/
1398 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001399 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001400 0, /* nb_oct */
1401 0, /* nb_hex */
1402 0, /* nb_inplace_add */
1403 0, /* nb_inplace_subtract */
1404 0, /* nb_inplace_multiply */
1405 0, /* nb_inplace_divide */
1406 0, /* nb_inplace_remainder */
1407 0, /* nb_inplace_power */
1408 0, /* nb_inplace_lshift */
1409 0, /* nb_inplace_rshift */
1410 0, /* nb_inplace_and */
1411 0, /* nb_inplace_xor */
1412 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001413 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001414 float_div, /* nb_true_divide */
1415 0, /* nb_inplace_floor_divide */
1416 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001417};
1418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001420 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001421 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001422 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001423 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 (destructor)float_dealloc, /* tp_dealloc */
1425 (printfunc)float_print, /* tp_print */
1426 0, /* tp_getattr */
1427 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001428 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429 (reprfunc)float_repr, /* tp_repr */
1430 &float_as_number, /* tp_as_number */
1431 0, /* tp_as_sequence */
1432 0, /* tp_as_mapping */
1433 (hashfunc)float_hash, /* tp_hash */
1434 0, /* tp_call */
1435 (reprfunc)float_str, /* tp_str */
1436 PyObject_GenericGetAttr, /* tp_getattro */
1437 0, /* tp_setattro */
1438 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001439 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1440 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441 float_doc, /* tp_doc */
1442 0, /* tp_traverse */
1443 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001444 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 0, /* tp_weaklistoffset */
1446 0, /* tp_iter */
1447 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001448 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001450 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451 0, /* tp_base */
1452 0, /* tp_dict */
1453 0, /* tp_descr_get */
1454 0, /* tp_descr_set */
1455 0, /* tp_dictoffset */
1456 0, /* tp_init */
1457 0, /* tp_alloc */
1458 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001459};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001460
1461void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001462_PyFloat_Init(void)
1463{
1464 /* We attempt to determine if this machine is using IEEE
1465 floating point formats by peering at the bits of some
1466 carefully chosen values. If it looks like we are on an
1467 IEEE platform, the float packing/unpacking routines can
1468 just copy bits, if not they resort to arithmetic & shifts
1469 and masks. The shifts & masks approach works on all finite
1470 values, but what happens to infinities, NaNs and signed
1471 zeroes on packing is an accident, and attempting to unpack
1472 a NaN or an infinity will raise an exception.
1473
1474 Note that if we're on some whacked-out platform which uses
1475 IEEE formats but isn't strictly little-endian or big-
1476 endian, we will fall back to the portable shifts & masks
1477 method. */
1478
1479#if SIZEOF_DOUBLE == 8
1480 {
1481 double x = 9006104071832581.0;
1482 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1483 detected_double_format = ieee_big_endian_format;
1484 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1485 detected_double_format = ieee_little_endian_format;
1486 else
1487 detected_double_format = unknown_format;
1488 }
1489#else
1490 detected_double_format = unknown_format;
1491#endif
1492
1493#if SIZEOF_FLOAT == 4
1494 {
1495 float y = 16711938.0;
1496 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1497 detected_float_format = ieee_big_endian_format;
1498 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1499 detected_float_format = ieee_little_endian_format;
1500 else
1501 detected_float_format = unknown_format;
1502 }
1503#else
1504 detected_float_format = unknown_format;
1505#endif
1506
1507 double_format = detected_double_format;
1508 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001509
1510#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001511 /* Initialize floating point repr */
1512 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001513#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001514}
1515
1516void
Fred Drakefd99de62000-07-09 05:02:18 +00001517PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001518{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001519 PyFloatObject *p;
1520 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001521 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001522 int bc, bf; /* block count, number of freed blocks */
1523 int frem, fsum; /* remaining unfreed floats per block, total */
1524
1525 bc = 0;
1526 bf = 0;
1527 fsum = 0;
1528 list = block_list;
1529 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001530 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001531 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001532 bc++;
1533 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001534 for (i = 0, p = &list->objects[0];
1535 i < N_FLOATOBJECTS;
1536 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001537 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001538 frem++;
1539 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001540 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001541 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001542 list->next = block_list;
1543 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001544 for (i = 0, p = &list->objects[0];
1545 i < N_FLOATOBJECTS;
1546 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001547 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001548 Py_REFCNT(p) == 0) {
1549 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001550 free_list;
1551 free_list = p;
1552 }
1553 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001554 }
1555 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001556 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001557 bf++;
1558 }
1559 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001560 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001561 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001562 if (!Py_VerboseFlag)
1563 return;
1564 fprintf(stderr, "# cleanup floats");
1565 if (!fsum) {
1566 fprintf(stderr, "\n");
1567 }
1568 else {
1569 fprintf(stderr,
1570 ": %d unfreed float%s in %d out of %d block%s\n",
1571 fsum, fsum == 1 ? "" : "s",
1572 bc - bf, bc, bc == 1 ? "" : "s");
1573 }
1574 if (Py_VerboseFlag > 1) {
1575 list = block_list;
1576 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001577 for (i = 0, p = &list->objects[0];
1578 i < N_FLOATOBJECTS;
1579 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001580 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001581 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001582 char buf[100];
1583 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001584 /* XXX(twouters) cast refcount to
1585 long until %zd is universally
1586 available
1587 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001588 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001589 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001590 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001591 }
1592 }
1593 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001594 }
1595 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001596}
Tim Peters9905b942003-03-20 20:53:32 +00001597
1598/*----------------------------------------------------------------------------
1599 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1600 *
1601 * TODO: On platforms that use the standard IEEE-754 single and double
1602 * formats natively, these routines could simply copy the bytes.
1603 */
1604int
1605_PyFloat_Pack4(double x, unsigned char *p, int le)
1606{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001607 if (float_format == unknown_format) {
1608 unsigned char sign;
1609 int e;
1610 double f;
1611 unsigned int fbits;
1612 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001613
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614 if (le) {
1615 p += 3;
1616 incr = -1;
1617 }
Tim Peters9905b942003-03-20 20:53:32 +00001618
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001619 if (x < 0) {
1620 sign = 1;
1621 x = -x;
1622 }
1623 else
1624 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001625
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001626 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001627
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001628 /* Normalize f to be in the range [1.0, 2.0) */
1629 if (0.5 <= f && f < 1.0) {
1630 f *= 2.0;
1631 e--;
1632 }
1633 else if (f == 0.0)
1634 e = 0;
1635 else {
1636 PyErr_SetString(PyExc_SystemError,
1637 "frexp() result out of range");
1638 return -1;
1639 }
1640
1641 if (e >= 128)
1642 goto Overflow;
1643 else if (e < -126) {
1644 /* Gradual underflow */
1645 f = ldexp(f, 126 + e);
1646 e = 0;
1647 }
1648 else if (!(e == 0 && f == 0.0)) {
1649 e += 127;
1650 f -= 1.0; /* Get rid of leading 1 */
1651 }
1652
1653 f *= 8388608.0; /* 2**23 */
1654 fbits = (unsigned int)(f + 0.5); /* Round */
1655 assert(fbits <= 8388608);
1656 if (fbits >> 23) {
1657 /* The carry propagated out of a string of 23 1 bits. */
1658 fbits = 0;
1659 ++e;
1660 if (e >= 255)
1661 goto Overflow;
1662 }
1663
1664 /* First byte */
1665 *p = (sign << 7) | (e >> 1);
1666 p += incr;
1667
1668 /* Second byte */
1669 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1670 p += incr;
1671
1672 /* Third byte */
1673 *p = (fbits >> 8) & 0xFF;
1674 p += incr;
1675
1676 /* Fourth byte */
1677 *p = fbits & 0xFF;
1678
1679 /* Done */
1680 return 0;
1681
1682 Overflow:
1683 PyErr_SetString(PyExc_OverflowError,
1684 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001685 return -1;
1686 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001688 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001689 const char *s = (char*)&y;
1690 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001691
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001692 if ((float_format == ieee_little_endian_format && !le)
1693 || (float_format == ieee_big_endian_format && le)) {
1694 p += 3;
1695 incr = -1;
1696 }
1697
1698 for (i = 0; i < 4; i++) {
1699 *p = *s++;
1700 p += incr;
1701 }
1702 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001703 }
Tim Peters9905b942003-03-20 20:53:32 +00001704}
1705
1706int
1707_PyFloat_Pack8(double x, unsigned char *p, int le)
1708{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001709 if (double_format == unknown_format) {
1710 unsigned char sign;
1711 int e;
1712 double f;
1713 unsigned int fhi, flo;
1714 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001715
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716 if (le) {
1717 p += 7;
1718 incr = -1;
1719 }
Tim Peters9905b942003-03-20 20:53:32 +00001720
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001721 if (x < 0) {
1722 sign = 1;
1723 x = -x;
1724 }
1725 else
1726 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001727
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001728 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001729
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001730 /* Normalize f to be in the range [1.0, 2.0) */
1731 if (0.5 <= f && f < 1.0) {
1732 f *= 2.0;
1733 e--;
1734 }
1735 else if (f == 0.0)
1736 e = 0;
1737 else {
1738 PyErr_SetString(PyExc_SystemError,
1739 "frexp() result out of range");
1740 return -1;
1741 }
1742
1743 if (e >= 1024)
1744 goto Overflow;
1745 else if (e < -1022) {
1746 /* Gradual underflow */
1747 f = ldexp(f, 1022 + e);
1748 e = 0;
1749 }
1750 else if (!(e == 0 && f == 0.0)) {
1751 e += 1023;
1752 f -= 1.0; /* Get rid of leading 1 */
1753 }
1754
1755 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1756 f *= 268435456.0; /* 2**28 */
1757 fhi = (unsigned int)f; /* Truncate */
1758 assert(fhi < 268435456);
1759
1760 f -= (double)fhi;
1761 f *= 16777216.0; /* 2**24 */
1762 flo = (unsigned int)(f + 0.5); /* Round */
1763 assert(flo <= 16777216);
1764 if (flo >> 24) {
1765 /* The carry propagated out of a string of 24 1 bits. */
1766 flo = 0;
1767 ++fhi;
1768 if (fhi >> 28) {
1769 /* And it also progagated out of the next 28 bits. */
1770 fhi = 0;
1771 ++e;
1772 if (e >= 2047)
1773 goto Overflow;
1774 }
1775 }
1776
1777 /* First byte */
1778 *p = (sign << 7) | (e >> 4);
1779 p += incr;
1780
1781 /* Second byte */
1782 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1783 p += incr;
1784
1785 /* Third byte */
1786 *p = (fhi >> 16) & 0xFF;
1787 p += incr;
1788
1789 /* Fourth byte */
1790 *p = (fhi >> 8) & 0xFF;
1791 p += incr;
1792
1793 /* Fifth byte */
1794 *p = fhi & 0xFF;
1795 p += incr;
1796
1797 /* Sixth byte */
1798 *p = (flo >> 16) & 0xFF;
1799 p += incr;
1800
1801 /* Seventh byte */
1802 *p = (flo >> 8) & 0xFF;
1803 p += incr;
1804
1805 /* Eighth byte */
1806 *p = flo & 0xFF;
1807 p += incr;
1808
1809 /* Done */
1810 return 0;
1811
1812 Overflow:
1813 PyErr_SetString(PyExc_OverflowError,
1814 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001815 return -1;
1816 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001817 else {
1818 const char *s = (char*)&x;
1819 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001820
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001821 if ((double_format == ieee_little_endian_format && !le)
1822 || (double_format == ieee_big_endian_format && le)) {
1823 p += 7;
1824 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001825 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001826
1827 for (i = 0; i < 8; i++) {
1828 *p = *s++;
1829 p += incr;
1830 }
1831 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001832 }
Tim Peters9905b942003-03-20 20:53:32 +00001833}
1834
1835double
1836_PyFloat_Unpack4(const unsigned char *p, int le)
1837{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001838 if (float_format == unknown_format) {
1839 unsigned char sign;
1840 int e;
1841 unsigned int f;
1842 double x;
1843 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001844
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001845 if (le) {
1846 p += 3;
1847 incr = -1;
1848 }
1849
1850 /* First byte */
1851 sign = (*p >> 7) & 1;
1852 e = (*p & 0x7F) << 1;
1853 p += incr;
1854
1855 /* Second byte */
1856 e |= (*p >> 7) & 1;
1857 f = (*p & 0x7F) << 16;
1858 p += incr;
1859
1860 if (e == 255) {
1861 PyErr_SetString(
1862 PyExc_ValueError,
1863 "can't unpack IEEE 754 special value "
1864 "on non-IEEE platform");
1865 return -1;
1866 }
1867
1868 /* Third byte */
1869 f |= *p << 8;
1870 p += incr;
1871
1872 /* Fourth byte */
1873 f |= *p;
1874
1875 x = (double)f / 8388608.0;
1876
1877 /* XXX This sadly ignores Inf/NaN issues */
1878 if (e == 0)
1879 e = -126;
1880 else {
1881 x += 1.0;
1882 e -= 127;
1883 }
1884 x = ldexp(x, e);
1885
1886 if (sign)
1887 x = -x;
1888
1889 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001890 }
Tim Peters9905b942003-03-20 20:53:32 +00001891 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001892 float x;
1893
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001894 if ((float_format == ieee_little_endian_format && !le)
1895 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001896 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001897 char *d = &buf[3];
1898 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001899
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001900 for (i = 0; i < 4; i++) {
1901 *d-- = *p++;
1902 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001903 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001904 }
1905 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001906 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001908
1909 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001910 }
Tim Peters9905b942003-03-20 20:53:32 +00001911}
1912
1913double
1914_PyFloat_Unpack8(const unsigned char *p, int le)
1915{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001916 if (double_format == unknown_format) {
1917 unsigned char sign;
1918 int e;
1919 unsigned int fhi, flo;
1920 double x;
1921 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001922
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001923 if (le) {
1924 p += 7;
1925 incr = -1;
1926 }
1927
1928 /* First byte */
1929 sign = (*p >> 7) & 1;
1930 e = (*p & 0x7F) << 4;
1931
1932 p += incr;
1933
1934 /* Second byte */
1935 e |= (*p >> 4) & 0xF;
1936 fhi = (*p & 0xF) << 24;
1937 p += incr;
1938
1939 if (e == 2047) {
1940 PyErr_SetString(
1941 PyExc_ValueError,
1942 "can't unpack IEEE 754 special value "
1943 "on non-IEEE platform");
1944 return -1.0;
1945 }
1946
1947 /* Third byte */
1948 fhi |= *p << 16;
1949 p += incr;
1950
1951 /* Fourth byte */
1952 fhi |= *p << 8;
1953 p += incr;
1954
1955 /* Fifth byte */
1956 fhi |= *p;
1957 p += incr;
1958
1959 /* Sixth byte */
1960 flo = *p << 16;
1961 p += incr;
1962
1963 /* Seventh byte */
1964 flo |= *p << 8;
1965 p += incr;
1966
1967 /* Eighth byte */
1968 flo |= *p;
1969
1970 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1971 x /= 268435456.0; /* 2**28 */
1972
1973 if (e == 0)
1974 e = -1022;
1975 else {
1976 x += 1.0;
1977 e -= 1023;
1978 }
1979 x = ldexp(x, e);
1980
1981 if (sign)
1982 x = -x;
1983
1984 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001985 }
Tim Peters9905b942003-03-20 20:53:32 +00001986 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001987 double x;
1988
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001989 if ((double_format == ieee_little_endian_format && !le)
1990 || (double_format == ieee_big_endian_format && le)) {
1991 char buf[8];
1992 char *d = &buf[7];
1993 int i;
1994
1995 for (i = 0; i < 8; i++) {
1996 *d-- = *p++;
1997 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001998 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999 }
2000 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002001 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002002 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002003
2004 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002005 }
Tim Peters9905b942003-03-20 20:53:32 +00002006}