blob: 340b0e7a2d98131ac75c85ae4728e56964208cfa [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
Guido van Rossum93ad0df1997-05-13 21:00:42 +000019/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000020#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000021#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000022#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000023
Guido van Rossum3fce8831999-03-12 19:43:17 +000024struct _floatblock {
25 struct _floatblock *next;
26 PyFloatObject objects[N_FLOATOBJECTS];
27};
28
29typedef struct _floatblock PyFloatBlock;
30
31static PyFloatBlock *block_list = NULL;
32static PyFloatObject *free_list = NULL;
33
Guido van Rossum93ad0df1997-05-13 21:00:42 +000034static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000035fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000036{
37 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000038 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
39 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000041 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000042 ((PyFloatBlock *)p)->next = block_list;
43 block_list = (PyFloatBlock *)p;
44 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 q = p + N_FLOATOBJECTS;
46 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000047 Py_TYPE(q) = (struct _typeobject *)(q-1);
48 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 return p + N_FLOATOBJECTS - 1;
50}
51
Christian Heimesdfdfaab2007-12-01 11:20:10 +000052double
53PyFloat_GetMax(void)
54{
55 return DBL_MAX;
56}
57
58double
59PyFloat_GetMin(void)
60{
61 return DBL_MIN;
62}
63
Christian Heimesc94e2b52008-01-14 04:13:37 +000064static PyTypeObject FloatInfoType = {0};
65
66PyDoc_STRVAR(floatinfo__doc__,
67"sys.floatinfo\n\
68\n\
69A structseq holding information about the float type. It contains low level\n\
70information about the precision and internal representation. Please study\n\
71your system's :file:`float.h` for more information.");
72
73static PyStructSequence_Field floatinfo_fields[] = {
74 {"max", "DBL_MAX -- maximum representable finite float"},
75 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
76 "is representable"},
77 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
78 "is representable"},
79 {"min", "DBL_MIN -- Minimum positive normalizer float"},
80 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
81 "is a normalized float"},
82 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
83 "a normalized"},
84 {"dig", "DBL_DIG -- digits"},
85 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
86 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
87 "representable float"},
88 {"radix", "FLT_RADIX -- radix of exponent"},
89 {"rounds", "FLT_ROUNDS -- addition rounds"},
90 {0}
91};
92
93static PyStructSequence_Desc floatinfo_desc = {
94 "sys.floatinfo", /* name */
95 floatinfo__doc__, /* doc */
96 floatinfo_fields, /* fields */
97 11
98};
99
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000100PyObject *
101PyFloat_GetInfo(void)
102{
Christian Heimesc94e2b52008-01-14 04:13:37 +0000103 static PyObject* floatinfo;
104 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000105
Christian Heimesc94e2b52008-01-14 04:13:37 +0000106 if (floatinfo != NULL) {
107 Py_INCREF(floatinfo);
108 return floatinfo;
109 }
110 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
111
112 floatinfo = PyStructSequence_New(&FloatInfoType);
113 if (floatinfo == NULL) {
114 return NULL;
115 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000116
Christian Heimesc94e2b52008-01-14 04:13:37 +0000117#define SetIntFlag(flag) \
118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
119#define SetDblFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000121
Christian Heimesc94e2b52008-01-14 04:13:37 +0000122 SetDblFlag(DBL_MAX);
123 SetIntFlag(DBL_MAX_EXP);
124 SetIntFlag(DBL_MAX_10_EXP);
125 SetDblFlag(DBL_MIN);
126 SetIntFlag(DBL_MIN_EXP);
127 SetIntFlag(DBL_MIN_10_EXP);
128 SetIntFlag(DBL_DIG);
129 SetIntFlag(DBL_MANT_DIG);
130 SetDblFlag(DBL_EPSILON);
131 SetIntFlag(FLT_RADIX);
132 SetIntFlag(FLT_ROUNDS);
133#undef SetIntFlag
134#undef SetDblFlag
135
136 if (PyErr_Occurred()) {
137 Py_CLEAR(floatinfo);
138 return NULL;
139 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000140
Christian Heimesc94e2b52008-01-14 04:13:37 +0000141 Py_INCREF(floatinfo);
142 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
152 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000153 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000155 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Tim Petersef14d732000-09-23 03:39:17 +0000161/**************************************************************************
162RED_FLAG 22-Sep-2000 tim
163PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
164
1651. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
168
1692. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
172
173Since we can't change the interface of a public API function, pend is
174still supported but now *officially* useless: if pend is not NULL,
175*pend is set to NULL.
176**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000178PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000180 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000182 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000184 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000185#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187
Tim Petersef14d732000-09-23 03:39:17 +0000188 if (pend)
189 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000190 if (PyString_Check(v)) {
191 s = PyString_AS_STRING(v);
192 len = PyString_GET_SIZE(v);
193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000194#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000195 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000196 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000198 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 return NULL;
200 }
Tim Petersef14d732000-09-23 03:39:17 +0000201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000203 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 NULL))
205 return NULL;
206 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000207 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000208 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000210 else if (PyObject_AsCharBuffer(v, &s, &len)) {
211 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000212 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215
Guido van Rossum4c08d552000-03-10 22:55:18 +0000216 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 while (*s && isspace(Py_CHARMASK(*s)))
218 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000219 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000220 PyErr_SetString(PyExc_ValueError, "empty string for float()");
221 return NULL;
222 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000223 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000224 /* We don't care about overflow or underflow. If the platform supports
225 * them, infinities and signed zeroes (on underflow) are fine.
226 * However, strtod can return 0 for denormalized numbers, where atof
227 * does not. So (alas!) we special-case a zero result. Note that
228 * whether strtod sets errno on underflow is not defined, so we can't
229 * key off errno.
230 */
Tim Peters858346e2000-09-25 21:01:28 +0000231 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000232 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000233 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000234 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000235 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000236 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237 if (end > last)
238 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000239 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000240 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000241 char *p = (char*)sp;
242 int sign = 1;
243
244 if (*p == '-') {
245 sign = -1;
246 p++;
247 }
248 if (*p == '+') {
249 p++;
250 }
251 if (PyOS_strnicmp(p, "inf", 4) == 0) {
252 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
253 }
254#ifdef Py_NAN
255 if(PyOS_strnicmp(p, "nan", 4) == 0) {
256 return PyFloat_FromDouble(Py_NAN);
257 }
258#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000259 PyOS_snprintf(buffer, sizeof(buffer),
260 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000261 PyErr_SetString(PyExc_ValueError, buffer);
262 return NULL;
263 }
264 /* Since end != s, the platform made *some* kind of sense out
265 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266 while (*end && isspace(Py_CHARMASK(*end)))
267 end++;
268 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000269 PyOS_snprintf(buffer, sizeof(buffer),
270 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000271 PyErr_SetString(PyExc_ValueError, buffer);
272 return NULL;
273 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000274 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000275 PyErr_SetString(PyExc_ValueError,
276 "null byte in argument for float()");
277 return NULL;
278 }
Tim Petersef14d732000-09-23 03:39:17 +0000279 if (x == 0.0) {
280 /* See above -- may have been strtod being anal
281 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000282 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000283 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000284 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000285 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000286 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000287 return PyFloat_FromDouble(x);
288}
289
Guido van Rossum234f9421993-06-17 12:35:49 +0000290static void
Fred Drakefd99de62000-07-09 05:02:18 +0000291float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000292{
Guido van Rossum9475a232001-10-05 20:51:39 +0000293 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000294 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000295 free_list = op;
296 }
297 else
Christian Heimese93237d2007-12-19 02:37:44 +0000298 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000299}
300
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301double
Fred Drakefd99de62000-07-09 05:02:18 +0000302PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 PyNumberMethods *nb;
305 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000306 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 if (op && PyFloat_Check(op))
309 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000311 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313 return -1;
314 }
Tim Petersd2364e82001-11-01 20:09:42 +0000315
Christian Heimese93237d2007-12-19 02:37:44 +0000316 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000317 PyErr_SetString(PyExc_TypeError, "a float is required");
318 return -1;
319 }
320
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000322 if (fo == NULL)
323 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 if (!PyFloat_Check(fo)) {
325 PyErr_SetString(PyExc_TypeError,
326 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000327 return -1;
328 }
Tim Petersd2364e82001-11-01 20:09:42 +0000329
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 val = PyFloat_AS_DOUBLE(fo);
331 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000332
Guido van Rossumb6775db1994-08-01 11:34:53 +0000333 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000334}
335
336/* Methods */
337
Tim Peters97019e42001-11-28 22:43:45 +0000338static void
339format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340{
341 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000342 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000343 int i;
344
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345 /* Subroutine for float_repr and float_print.
346 We want float numbers to be recognizable as such,
347 i.e., they should contain a decimal point or an exponent.
348 However, %g may print the number as an integer;
349 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000350
351 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000352 PyOS_snprintf(format, 32, "%%.%ig", precision);
353 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000354 cp = buf;
355 if (*cp == '-')
356 cp++;
357 for (; *cp != '\0'; cp++) {
358 /* Any non-digit means it's not an integer;
359 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000360 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000361 break;
362 }
363 if (*cp == '\0') {
364 *cp++ = '.';
365 *cp++ = '0';
366 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000367 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000369 /* Checking the next three chars should be more than enough to
370 * detect inf or nan, even on Windows. We check for inf or nan
371 * at last because they are rare cases.
372 */
373 for (i=0; *cp != '\0' && i<3; cp++, i++) {
374 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
375 continue;
376 /* found something that is neither a digit nor point
377 * it might be a NaN or INF
378 */
379#ifdef Py_NAN
380 if (Py_IS_NAN(v->ob_fval)) {
381 strcpy(buf, "nan");
382 }
383 else
384#endif
385 if (Py_IS_INFINITY(v->ob_fval)) {
386 cp = buf;
387 if (*cp == '-')
388 cp++;
389 strcpy(cp, "inf");
390 }
391 break;
392 }
393
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394}
395
Tim Peters97019e42001-11-28 22:43:45 +0000396/* XXX PyFloat_AsStringEx should not be a public API function (for one
397 XXX thing, its signature passes a buffer without a length; for another,
398 XXX it isn't useful outside this file).
399*/
400void
401PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
402{
403 format_float(buf, 100, v, precision);
404}
405
Christian Heimesf15c66e2007-12-11 00:54:34 +0000406#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000407/* The following function is based on Tcl_PrintDouble,
408 * from tclUtil.c.
409 */
410
411#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
412#define is_nan(d) ((d) != (d))
413
414static void
415format_double_repr(char *dst, double value)
416{
417 char *p, c;
418 int exp;
419 int signum;
420 char buffer[30];
421
422 /*
423 * Handle NaN.
424 */
425
426 if (is_nan(value)) {
427 strcpy(dst, "nan");
428 return;
429 }
430
431 /*
432 * Handle infinities.
433 */
434
435 if (is_infinite(value)) {
436 if (value < 0) {
437 strcpy(dst, "-inf");
438 } else {
439 strcpy(dst, "inf");
440 }
441 return;
442 }
443
444 /*
445 * Ordinary (normal and denormal) values.
446 */
447
448 exp = _PyFloat_Digits(buffer, value, &signum)+1;
449 if (signum) {
450 *dst++ = '-';
451 }
452 p = buffer;
453 if (exp < -3 || exp > 17) {
454 /*
455 * E format for numbers < 1e-3 or >= 1e17.
456 */
457
458 *dst++ = *p++;
459 c = *p;
460 if (c != '\0') {
461 *dst++ = '.';
462 while (c != '\0') {
463 *dst++ = c;
464 c = *++p;
465 }
466 }
467 sprintf(dst, "e%+d", exp-1);
468 } else {
469 /*
470 * F format for others.
471 */
472
473 if (exp <= 0) {
474 *dst++ = '0';
475 }
476 c = *p;
477 while (exp-- > 0) {
478 if (c != '\0') {
479 *dst++ = c;
480 c = *++p;
481 } else {
482 *dst++ = '0';
483 }
484 }
485 *dst++ = '.';
486 if (c == '\0') {
487 *dst++ = '0';
488 } else {
489 while (++exp < 0) {
490 *dst++ = '0';
491 }
492 while (c != '\0') {
493 *dst++ = c;
494 c = *++p;
495 }
496 }
497 *dst++ = '\0';
498 }
499}
500
501static void
502format_float_repr(char *buf, PyFloatObject *v)
503{
504 assert(PyFloat_Check(v));
505 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
506}
507
Christian Heimesf15c66e2007-12-11 00:54:34 +0000508#endif /* Py_BROKEN_REPR */
509
Neil Schemenauer32117e52001-01-04 01:44:34 +0000510/* Macro and helper that convert PyObject obj to a C double and store
511 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000512 slot function. If conversion to double raises an exception, obj is
513 set to NULL, and the function invoking this macro returns NULL. If
514 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
515 stored in obj, and returned from the function invoking this macro.
516*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000517#define CONVERT_TO_DOUBLE(obj, dbl) \
518 if (PyFloat_Check(obj)) \
519 dbl = PyFloat_AS_DOUBLE(obj); \
520 else if (convert_to_double(&(obj), &(dbl)) < 0) \
521 return obj;
522
523static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000524convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000525{
526 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000527
Neil Schemenauer32117e52001-01-04 01:44:34 +0000528 if (PyInt_Check(obj)) {
529 *dbl = (double)PyInt_AS_LONG(obj);
530 }
531 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000532 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000533 if (*dbl == -1.0 && PyErr_Occurred()) {
534 *v = NULL;
535 return -1;
536 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000537 }
538 else {
539 Py_INCREF(Py_NotImplemented);
540 *v = Py_NotImplemented;
541 return -1;
542 }
543 return 0;
544}
545
Guido van Rossum57072eb1999-12-23 19:00:28 +0000546/* Precisions used by repr() and str(), respectively.
547
548 The repr() precision (17 significant decimal digits) is the minimal number
549 that is guaranteed to have enough precision so that if the number is read
550 back in the exact same binary value is recreated. This is true for IEEE
551 floating point by design, and also happens to work for all other modern
552 hardware.
553
554 The str() precision is chosen so that in most cases, the rounding noise
555 created by various operations is suppressed, while giving plenty of
556 precision for practical use.
557
558*/
559
560#define PREC_REPR 17
561#define PREC_STR 12
562
Tim Peters97019e42001-11-28 22:43:45 +0000563/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
564 XXX they pass a char buffer without passing a length.
565*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000566void
Fred Drakefd99de62000-07-09 05:02:18 +0000567PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000568{
Tim Peters97019e42001-11-28 22:43:45 +0000569 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000570}
571
Tim Peters72f98e92001-05-08 15:19:57 +0000572void
573PyFloat_AsReprString(char *buf, PyFloatObject *v)
574{
Tim Peters97019e42001-11-28 22:43:45 +0000575 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000576}
577
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000578/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000579static int
Fred Drakefd99de62000-07-09 05:02:18 +0000580float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581{
582 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000583 format_float(buf, sizeof(buf), v,
584 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000585 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000587 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000588 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000589}
590
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000592float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000594#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000595 char buf[30];
596 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000597#else
598 char buf[100];
599 format_float(buf, sizeof(buf), v, PREC_REPR);
600#endif
601
Guido van Rossum57072eb1999-12-23 19:00:28 +0000602 return PyString_FromString(buf);
603}
604
605static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000606float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000607{
608 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000609 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611}
612
Tim Peters307fa782004-09-23 08:06:40 +0000613/* Comparison is pretty much a nightmare. When comparing float to float,
614 * we do it as straightforwardly (and long-windedly) as conceivable, so
615 * that, e.g., Python x == y delivers the same result as the platform
616 * C x == y when x and/or y is a NaN.
617 * When mixing float with an integer type, there's no good *uniform* approach.
618 * Converting the double to an integer obviously doesn't work, since we
619 * may lose info from fractional bits. Converting the integer to a double
620 * also has two failure modes: (1) a long int may trigger overflow (too
621 * large to fit in the dynamic range of a C double); (2) even a C long may have
622 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
623 * 63 bits of precision, but a C double probably has only 53), and then
624 * we can falsely claim equality when low-order integer bits are lost by
625 * coercion to double. So this part is painful too.
626 */
627
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000628static PyObject*
629float_richcompare(PyObject *v, PyObject *w, int op)
630{
631 double i, j;
632 int r = 0;
633
Tim Peters307fa782004-09-23 08:06:40 +0000634 assert(PyFloat_Check(v));
635 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000636
Tim Peters307fa782004-09-23 08:06:40 +0000637 /* Switch on the type of w. Set i and j to doubles to be compared,
638 * and op to the richcomp to use.
639 */
640 if (PyFloat_Check(w))
641 j = PyFloat_AS_DOUBLE(w);
642
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000643 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000644 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000645 /* If i is an infinity, its magnitude exceeds any
646 * finite integer, so it doesn't matter which int we
647 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000648 */
649 j = 0.0;
650 else
651 goto Unimplemented;
652 }
653
654 else if (PyInt_Check(w)) {
655 long jj = PyInt_AS_LONG(w);
656 /* In the worst realistic case I can imagine, C double is a
657 * Cray single with 48 bits of precision, and long has 64
658 * bits.
659 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000660#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000661 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
662 if (abs >> 48) {
663 /* Needs more than 48 bits. Make it take the
664 * PyLong path.
665 */
666 PyObject *result;
667 PyObject *ww = PyLong_FromLong(jj);
668
669 if (ww == NULL)
670 return NULL;
671 result = float_richcompare(v, ww, op);
672 Py_DECREF(ww);
673 return result;
674 }
675#endif
676 j = (double)jj;
677 assert((long)j == jj);
678 }
679
680 else if (PyLong_Check(w)) {
681 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
682 int wsign = _PyLong_Sign(w);
683 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000684 int exponent;
685
686 if (vsign != wsign) {
687 /* Magnitudes are irrelevant -- the signs alone
688 * determine the outcome.
689 */
690 i = (double)vsign;
691 j = (double)wsign;
692 goto Compare;
693 }
694 /* The signs are the same. */
695 /* Convert w to a double if it fits. In particular, 0 fits. */
696 nbits = _PyLong_NumBits(w);
697 if (nbits == (size_t)-1 && PyErr_Occurred()) {
698 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000699 * to hold the # of bits. Replace with little doubles
700 * that give the same outcome -- w is so large that
701 * its magnitude must exceed the magnitude of any
702 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000703 */
704 PyErr_Clear();
705 i = (double)vsign;
706 assert(wsign != 0);
707 j = wsign * 2.0;
708 goto Compare;
709 }
710 if (nbits <= 48) {
711 j = PyLong_AsDouble(w);
712 /* It's impossible that <= 48 bits overflowed. */
713 assert(j != -1.0 || ! PyErr_Occurred());
714 goto Compare;
715 }
716 assert(wsign != 0); /* else nbits was 0 */
717 assert(vsign != 0); /* if vsign were 0, then since wsign is
718 * not 0, we would have taken the
719 * vsign != wsign branch at the start */
720 /* We want to work with non-negative numbers. */
721 if (vsign < 0) {
722 /* "Multiply both sides" by -1; this also swaps the
723 * comparator.
724 */
725 i = -i;
726 op = _Py_SwappedOp[op];
727 }
728 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000729 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000730 /* exponent is the # of bits in v before the radix point;
731 * we know that nbits (the # of bits in w) > 48 at this point
732 */
733 if (exponent < 0 || (size_t)exponent < nbits) {
734 i = 1.0;
735 j = 2.0;
736 goto Compare;
737 }
738 if ((size_t)exponent > nbits) {
739 i = 2.0;
740 j = 1.0;
741 goto Compare;
742 }
743 /* v and w have the same number of bits before the radix
744 * point. Construct two longs that have the same comparison
745 * outcome.
746 */
747 {
748 double fracpart;
749 double intpart;
750 PyObject *result = NULL;
751 PyObject *one = NULL;
752 PyObject *vv = NULL;
753 PyObject *ww = w;
754
755 if (wsign < 0) {
756 ww = PyNumber_Negative(w);
757 if (ww == NULL)
758 goto Error;
759 }
760 else
761 Py_INCREF(ww);
762
763 fracpart = modf(i, &intpart);
764 vv = PyLong_FromDouble(intpart);
765 if (vv == NULL)
766 goto Error;
767
768 if (fracpart != 0.0) {
769 /* Shift left, and or a 1 bit into vv
770 * to represent the lost fraction.
771 */
772 PyObject *temp;
773
774 one = PyInt_FromLong(1);
775 if (one == NULL)
776 goto Error;
777
778 temp = PyNumber_Lshift(ww, one);
779 if (temp == NULL)
780 goto Error;
781 Py_DECREF(ww);
782 ww = temp;
783
784 temp = PyNumber_Lshift(vv, one);
785 if (temp == NULL)
786 goto Error;
787 Py_DECREF(vv);
788 vv = temp;
789
790 temp = PyNumber_Or(vv, one);
791 if (temp == NULL)
792 goto Error;
793 Py_DECREF(vv);
794 vv = temp;
795 }
796
797 r = PyObject_RichCompareBool(vv, ww, op);
798 if (r < 0)
799 goto Error;
800 result = PyBool_FromLong(r);
801 Error:
802 Py_XDECREF(vv);
803 Py_XDECREF(ww);
804 Py_XDECREF(one);
805 return result;
806 }
807 } /* else if (PyLong_Check(w)) */
808
809 else /* w isn't float, int, or long */
810 goto Unimplemented;
811
812 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000813 PyFPE_START_PROTECT("richcompare", return NULL)
814 switch (op) {
815 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000816 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000817 break;
818 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000819 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000820 break;
821 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000822 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000823 break;
824 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000825 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000826 break;
827 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000828 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000829 break;
830 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000831 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000832 break;
833 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000834 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000835 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000836
837 Unimplemented:
838 Py_INCREF(Py_NotImplemented);
839 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000840}
841
Guido van Rossum9bfef441993-03-29 10:43:31 +0000842static long
Fred Drakefd99de62000-07-09 05:02:18 +0000843float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000844{
Tim Peters39dce292000-08-15 03:34:48 +0000845 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000846}
847
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000848static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000849float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000851 double a,b;
852 CONVERT_TO_DOUBLE(v, a);
853 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000854 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000855 a = a + b;
856 PyFPE_END_PROTECT(a)
857 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000858}
859
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000860static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000861float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000862{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000863 double a,b;
864 CONVERT_TO_DOUBLE(v, a);
865 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000866 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000867 a = a - b;
868 PyFPE_END_PROTECT(a)
869 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000870}
871
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000873float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000874{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000875 double a,b;
876 CONVERT_TO_DOUBLE(v, a);
877 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000878 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000879 a = a * b;
880 PyFPE_END_PROTECT(a)
881 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000882}
883
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000884static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000885float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000886{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000887 double a,b;
888 CONVERT_TO_DOUBLE(v, a);
889 CONVERT_TO_DOUBLE(w, b);
890 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000891 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000892 return NULL;
893 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000894 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000895 a = a / b;
896 PyFPE_END_PROTECT(a)
897 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000898}
899
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000900static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000901float_classic_div(PyObject *v, PyObject *w)
902{
903 double a,b;
904 CONVERT_TO_DOUBLE(v, a);
905 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000906 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000907 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
908 return NULL;
909 if (b == 0.0) {
910 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
911 return NULL;
912 }
913 PyFPE_START_PROTECT("divide", return 0)
914 a = a / b;
915 PyFPE_END_PROTECT(a)
916 return PyFloat_FromDouble(a);
917}
918
919static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000920float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000921{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000922 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000923 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000924 CONVERT_TO_DOUBLE(v, vx);
925 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000926 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000927 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000928 return NULL;
929 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000930 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000931 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000932 /* note: checking mod*wx < 0 is incorrect -- underflows to
933 0 if wx < sqrt(smallest nonzero double) */
934 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000935 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000936 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000937 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000938 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000939}
940
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000942float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000943{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000944 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000945 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000946 CONVERT_TO_DOUBLE(v, vx);
947 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000948 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000949 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000950 return NULL;
951 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000952 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000953 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000954 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000955 exact multiple of wx. But this is fp arithmetic, and fp
956 vx - mod is an approximation; the result is that div may
957 not be an exact integral value after the division, although
958 it will always be very close to one.
959 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000960 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000961 if (mod) {
962 /* ensure the remainder has the same sign as the denominator */
963 if ((wx < 0) != (mod < 0)) {
964 mod += wx;
965 div -= 1.0;
966 }
967 }
968 else {
969 /* the remainder is zero, and in the presence of signed zeroes
970 fmod returns different results across platforms; ensure
971 it has the same sign as the denominator; we'd like to do
972 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000973 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000974 if (wx < 0.0)
975 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000976 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000977 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000978 if (div) {
979 floordiv = floor(div);
980 if (div - floordiv > 0.5)
981 floordiv += 1.0;
982 }
983 else {
984 /* div is zero - get the same sign as the true quotient */
985 div *= div; /* hide "div = +0" from optimizers */
986 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
987 }
988 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000989 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000990}
991
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000993float_floor_div(PyObject *v, PyObject *w)
994{
995 PyObject *t, *r;
996
997 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000998 if (t == NULL || t == Py_NotImplemented)
999 return t;
1000 assert(PyTuple_CheckExact(t));
1001 r = PyTuple_GET_ITEM(t, 0);
1002 Py_INCREF(r);
1003 Py_DECREF(t);
1004 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001005}
1006
1007static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001008float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001009{
1010 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001011
1012 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001013 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001014 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001015 return NULL;
1016 }
1017
Neil Schemenauer32117e52001-01-04 01:44:34 +00001018 CONVERT_TO_DOUBLE(v, iv);
1019 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001020
1021 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001022 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001023 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001024 }
Tim Peters96685bf2001-08-23 22:31:37 +00001025 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001026 if (iw < 0.0) {
1027 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001028 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001029 return NULL;
1030 }
1031 return PyFloat_FromDouble(0.0);
1032 }
Tim Peterse87568d2003-05-24 20:18:24 +00001033 if (iv < 0.0) {
1034 /* Whether this is an error is a mess, and bumps into libm
1035 * bugs so we have to figure it out ourselves.
1036 */
1037 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001038 PyErr_SetString(PyExc_ValueError, "negative number "
1039 "cannot be raised to a fractional power");
1040 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001041 }
1042 /* iw is an exact integer, albeit perhaps a very large one.
1043 * -1 raised to an exact integer should never be exceptional.
1044 * Alas, some libms (chiefly glibc as of early 2003) return
1045 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1046 * happen to be representable in a *C* integer. That's a
1047 * bug; we let that slide in math.pow() (which currently
1048 * reflects all platform accidents), but not for Python's **.
1049 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001050 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001051 /* Return 1 if iw is even, -1 if iw is odd; there's
1052 * no guarantee that any C integral type is big
1053 * enough to hold iw, so we have to check this
1054 * indirectly.
1055 */
1056 ix = floor(iw * 0.5) * 2.0;
1057 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1058 }
1059 /* Else iv != -1.0, and overflow or underflow are possible.
1060 * Unless we're to write pow() ourselves, we have to trust
1061 * the platform to do this correctly.
1062 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001063 }
Tim Peters96685bf2001-08-23 22:31:37 +00001064 errno = 0;
1065 PyFPE_START_PROTECT("pow", return NULL)
1066 ix = pow(iv, iw);
1067 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001068 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001069 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001070 /* We don't expect any errno value other than ERANGE, but
1071 * the range of libm bugs appears unbounded.
1072 */
Alex Martelli348dc882006-08-23 22:17:59 +00001073 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1074 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001075 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001076 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001077 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001078}
1079
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001080static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001081float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001082{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001083 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001084}
1085
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001086static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001087float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001088{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001089 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001090}
1091
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001092static int
Fred Drakefd99de62000-07-09 05:02:18 +00001093float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001094{
1095 return v->ob_fval != 0.0;
1096}
1097
Guido van Rossum234f9421993-06-17 12:35:49 +00001098static int
Fred Drakefd99de62000-07-09 05:02:18 +00001099float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001100{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001101 if (PyInt_Check(*pw)) {
1102 long x = PyInt_AsLong(*pw);
1103 *pw = PyFloat_FromDouble((double)x);
1104 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001105 return 0;
1106 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001107 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001108 double x = PyLong_AsDouble(*pw);
1109 if (x == -1.0 && PyErr_Occurred())
1110 return -1;
1111 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001113 return 0;
1114 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001115 else if (PyFloat_Check(*pw)) {
1116 Py_INCREF(*pv);
1117 Py_INCREF(*pw);
1118 return 0;
1119 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001120 return 1; /* Can't do it */
1121}
1122
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001123static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001124float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001125{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001126 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001127 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001128
1129 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001130 /* Try to get out cheap if this fits in a Python int. The attempt
1131 * to cast to long must be protected, as C doesn't define what
1132 * happens if the double is too big to fit in a long. Some rare
1133 * systems raise an exception then (RISCOS was mentioned as one,
1134 * and someone using a non-default option on Sun also bumped into
1135 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1136 * still be vulnerable: if a long has more bits of precision than
1137 * a double, casting MIN/MAX to double may yield an approximation,
1138 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1139 * yield true from the C expression wholepart<=LONG_MAX, despite
1140 * that wholepart is actually greater than LONG_MAX.
1141 */
1142 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1143 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001144 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001145 }
1146 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001147}
1148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001149static 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."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001347 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001348 {"__getformat__", (PyCFunction)float_getformat,
1349 METH_O|METH_CLASS, float_getformat_doc},
1350 {"__setformat__", (PyCFunction)float_setformat,
1351 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001352 {NULL, NULL} /* sentinel */
1353};
1354
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001355static PyGetSetDef float_getset[] = {
1356 {"real",
1357 (getter)float_float, (setter)NULL,
1358 "the real part of a complex number",
1359 NULL},
1360 {"imag",
1361 (getter)float_getzero, (setter)NULL,
1362 "the imaginary part of a complex number",
1363 NULL},
1364 {NULL} /* Sentinel */
1365};
1366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001367PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368"float(x) -> floating point number\n\
1369\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001370Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
1372
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001374 float_add, /*nb_add*/
1375 float_sub, /*nb_subtract*/
1376 float_mul, /*nb_multiply*/
1377 float_classic_div, /*nb_divide*/
1378 float_rem, /*nb_remainder*/
1379 float_divmod, /*nb_divmod*/
1380 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001381 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001382 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001383 (unaryfunc)float_abs, /*nb_absolute*/
1384 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001385 0, /*nb_invert*/
1386 0, /*nb_lshift*/
1387 0, /*nb_rshift*/
1388 0, /*nb_and*/
1389 0, /*nb_xor*/
1390 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001391 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001392 float_trunc, /*nb_int*/
1393 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001394 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001395 0, /* nb_oct */
1396 0, /* nb_hex */
1397 0, /* nb_inplace_add */
1398 0, /* nb_inplace_subtract */
1399 0, /* nb_inplace_multiply */
1400 0, /* nb_inplace_divide */
1401 0, /* nb_inplace_remainder */
1402 0, /* nb_inplace_power */
1403 0, /* nb_inplace_lshift */
1404 0, /* nb_inplace_rshift */
1405 0, /* nb_inplace_and */
1406 0, /* nb_inplace_xor */
1407 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001408 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001409 float_div, /* nb_true_divide */
1410 0, /* nb_inplace_floor_divide */
1411 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412};
1413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001415 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001416 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001418 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 (destructor)float_dealloc, /* tp_dealloc */
1420 (printfunc)float_print, /* tp_print */
1421 0, /* tp_getattr */
1422 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001423 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 (reprfunc)float_repr, /* tp_repr */
1425 &float_as_number, /* tp_as_number */
1426 0, /* tp_as_sequence */
1427 0, /* tp_as_mapping */
1428 (hashfunc)float_hash, /* tp_hash */
1429 0, /* tp_call */
1430 (reprfunc)float_str, /* tp_str */
1431 PyObject_GenericGetAttr, /* tp_getattro */
1432 0, /* tp_setattro */
1433 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1435 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436 float_doc, /* tp_doc */
1437 0, /* tp_traverse */
1438 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001439 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 0, /* tp_weaklistoffset */
1441 0, /* tp_iter */
1442 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001443 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001445 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446 0, /* tp_base */
1447 0, /* tp_dict */
1448 0, /* tp_descr_get */
1449 0, /* tp_descr_set */
1450 0, /* tp_dictoffset */
1451 0, /* tp_init */
1452 0, /* tp_alloc */
1453 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001454};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001455
1456void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001457_PyFloat_Init(void)
1458{
1459 /* We attempt to determine if this machine is using IEEE
1460 floating point formats by peering at the bits of some
1461 carefully chosen values. If it looks like we are on an
1462 IEEE platform, the float packing/unpacking routines can
1463 just copy bits, if not they resort to arithmetic & shifts
1464 and masks. The shifts & masks approach works on all finite
1465 values, but what happens to infinities, NaNs and signed
1466 zeroes on packing is an accident, and attempting to unpack
1467 a NaN or an infinity will raise an exception.
1468
1469 Note that if we're on some whacked-out platform which uses
1470 IEEE formats but isn't strictly little-endian or big-
1471 endian, we will fall back to the portable shifts & masks
1472 method. */
1473
1474#if SIZEOF_DOUBLE == 8
1475 {
1476 double x = 9006104071832581.0;
1477 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1478 detected_double_format = ieee_big_endian_format;
1479 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1480 detected_double_format = ieee_little_endian_format;
1481 else
1482 detected_double_format = unknown_format;
1483 }
1484#else
1485 detected_double_format = unknown_format;
1486#endif
1487
1488#if SIZEOF_FLOAT == 4
1489 {
1490 float y = 16711938.0;
1491 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1492 detected_float_format = ieee_big_endian_format;
1493 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1494 detected_float_format = ieee_little_endian_format;
1495 else
1496 detected_float_format = unknown_format;
1497 }
1498#else
1499 detected_float_format = unknown_format;
1500#endif
1501
1502 double_format = detected_double_format;
1503 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001504
1505#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001506 /* Initialize floating point repr */
1507 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001508#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001509}
1510
1511void
Fred Drakefd99de62000-07-09 05:02:18 +00001512PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001513{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001514 PyFloatObject *p;
1515 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001516 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001517 int bc, bf; /* block count, number of freed blocks */
1518 int frem, fsum; /* remaining unfreed floats per block, total */
1519
1520 bc = 0;
1521 bf = 0;
1522 fsum = 0;
1523 list = block_list;
1524 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001525 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001526 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001527 bc++;
1528 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001529 for (i = 0, p = &list->objects[0];
1530 i < N_FLOATOBJECTS;
1531 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001532 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001533 frem++;
1534 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001535 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001536 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001537 list->next = block_list;
1538 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001539 for (i = 0, p = &list->objects[0];
1540 i < N_FLOATOBJECTS;
1541 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001542 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001543 Py_REFCNT(p) == 0) {
1544 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001545 free_list;
1546 free_list = p;
1547 }
1548 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001549 }
1550 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001551 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001552 bf++;
1553 }
1554 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001555 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001556 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001557 if (!Py_VerboseFlag)
1558 return;
1559 fprintf(stderr, "# cleanup floats");
1560 if (!fsum) {
1561 fprintf(stderr, "\n");
1562 }
1563 else {
1564 fprintf(stderr,
1565 ": %d unfreed float%s in %d out of %d block%s\n",
1566 fsum, fsum == 1 ? "" : "s",
1567 bc - bf, bc, bc == 1 ? "" : "s");
1568 }
1569 if (Py_VerboseFlag > 1) {
1570 list = block_list;
1571 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001572 for (i = 0, p = &list->objects[0];
1573 i < N_FLOATOBJECTS;
1574 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001575 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001576 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001577 char buf[100];
1578 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001579 /* XXX(twouters) cast refcount to
1580 long until %zd is universally
1581 available
1582 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001583 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001584 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001585 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001586 }
1587 }
1588 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001589 }
1590 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001591}
Tim Peters9905b942003-03-20 20:53:32 +00001592
1593/*----------------------------------------------------------------------------
1594 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1595 *
1596 * TODO: On platforms that use the standard IEEE-754 single and double
1597 * formats natively, these routines could simply copy the bytes.
1598 */
1599int
1600_PyFloat_Pack4(double x, unsigned char *p, int le)
1601{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001602 if (float_format == unknown_format) {
1603 unsigned char sign;
1604 int e;
1605 double f;
1606 unsigned int fbits;
1607 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001608
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001609 if (le) {
1610 p += 3;
1611 incr = -1;
1612 }
Tim Peters9905b942003-03-20 20:53:32 +00001613
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001614 if (x < 0) {
1615 sign = 1;
1616 x = -x;
1617 }
1618 else
1619 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001620
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001621 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001622
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001623 /* Normalize f to be in the range [1.0, 2.0) */
1624 if (0.5 <= f && f < 1.0) {
1625 f *= 2.0;
1626 e--;
1627 }
1628 else if (f == 0.0)
1629 e = 0;
1630 else {
1631 PyErr_SetString(PyExc_SystemError,
1632 "frexp() result out of range");
1633 return -1;
1634 }
1635
1636 if (e >= 128)
1637 goto Overflow;
1638 else if (e < -126) {
1639 /* Gradual underflow */
1640 f = ldexp(f, 126 + e);
1641 e = 0;
1642 }
1643 else if (!(e == 0 && f == 0.0)) {
1644 e += 127;
1645 f -= 1.0; /* Get rid of leading 1 */
1646 }
1647
1648 f *= 8388608.0; /* 2**23 */
1649 fbits = (unsigned int)(f + 0.5); /* Round */
1650 assert(fbits <= 8388608);
1651 if (fbits >> 23) {
1652 /* The carry propagated out of a string of 23 1 bits. */
1653 fbits = 0;
1654 ++e;
1655 if (e >= 255)
1656 goto Overflow;
1657 }
1658
1659 /* First byte */
1660 *p = (sign << 7) | (e >> 1);
1661 p += incr;
1662
1663 /* Second byte */
1664 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1665 p += incr;
1666
1667 /* Third byte */
1668 *p = (fbits >> 8) & 0xFF;
1669 p += incr;
1670
1671 /* Fourth byte */
1672 *p = fbits & 0xFF;
1673
1674 /* Done */
1675 return 0;
1676
1677 Overflow:
1678 PyErr_SetString(PyExc_OverflowError,
1679 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001680 return -1;
1681 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001682 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001683 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001684 const char *s = (char*)&y;
1685 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001686
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687 if ((float_format == ieee_little_endian_format && !le)
1688 || (float_format == ieee_big_endian_format && le)) {
1689 p += 3;
1690 incr = -1;
1691 }
1692
1693 for (i = 0; i < 4; i++) {
1694 *p = *s++;
1695 p += incr;
1696 }
1697 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001698 }
Tim Peters9905b942003-03-20 20:53:32 +00001699}
1700
1701int
1702_PyFloat_Pack8(double x, unsigned char *p, int le)
1703{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001704 if (double_format == unknown_format) {
1705 unsigned char sign;
1706 int e;
1707 double f;
1708 unsigned int fhi, flo;
1709 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001710
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711 if (le) {
1712 p += 7;
1713 incr = -1;
1714 }
Tim Peters9905b942003-03-20 20:53:32 +00001715
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716 if (x < 0) {
1717 sign = 1;
1718 x = -x;
1719 }
1720 else
1721 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001722
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001723 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001724
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001725 /* Normalize f to be in the range [1.0, 2.0) */
1726 if (0.5 <= f && f < 1.0) {
1727 f *= 2.0;
1728 e--;
1729 }
1730 else if (f == 0.0)
1731 e = 0;
1732 else {
1733 PyErr_SetString(PyExc_SystemError,
1734 "frexp() result out of range");
1735 return -1;
1736 }
1737
1738 if (e >= 1024)
1739 goto Overflow;
1740 else if (e < -1022) {
1741 /* Gradual underflow */
1742 f = ldexp(f, 1022 + e);
1743 e = 0;
1744 }
1745 else if (!(e == 0 && f == 0.0)) {
1746 e += 1023;
1747 f -= 1.0; /* Get rid of leading 1 */
1748 }
1749
1750 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1751 f *= 268435456.0; /* 2**28 */
1752 fhi = (unsigned int)f; /* Truncate */
1753 assert(fhi < 268435456);
1754
1755 f -= (double)fhi;
1756 f *= 16777216.0; /* 2**24 */
1757 flo = (unsigned int)(f + 0.5); /* Round */
1758 assert(flo <= 16777216);
1759 if (flo >> 24) {
1760 /* The carry propagated out of a string of 24 1 bits. */
1761 flo = 0;
1762 ++fhi;
1763 if (fhi >> 28) {
1764 /* And it also progagated out of the next 28 bits. */
1765 fhi = 0;
1766 ++e;
1767 if (e >= 2047)
1768 goto Overflow;
1769 }
1770 }
1771
1772 /* First byte */
1773 *p = (sign << 7) | (e >> 4);
1774 p += incr;
1775
1776 /* Second byte */
1777 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1778 p += incr;
1779
1780 /* Third byte */
1781 *p = (fhi >> 16) & 0xFF;
1782 p += incr;
1783
1784 /* Fourth byte */
1785 *p = (fhi >> 8) & 0xFF;
1786 p += incr;
1787
1788 /* Fifth byte */
1789 *p = fhi & 0xFF;
1790 p += incr;
1791
1792 /* Sixth byte */
1793 *p = (flo >> 16) & 0xFF;
1794 p += incr;
1795
1796 /* Seventh byte */
1797 *p = (flo >> 8) & 0xFF;
1798 p += incr;
1799
1800 /* Eighth byte */
1801 *p = flo & 0xFF;
1802 p += incr;
1803
1804 /* Done */
1805 return 0;
1806
1807 Overflow:
1808 PyErr_SetString(PyExc_OverflowError,
1809 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001810 return -1;
1811 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001812 else {
1813 const char *s = (char*)&x;
1814 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001815
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001816 if ((double_format == ieee_little_endian_format && !le)
1817 || (double_format == ieee_big_endian_format && le)) {
1818 p += 7;
1819 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001820 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001821
1822 for (i = 0; i < 8; i++) {
1823 *p = *s++;
1824 p += incr;
1825 }
1826 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001827 }
Tim Peters9905b942003-03-20 20:53:32 +00001828}
1829
1830double
1831_PyFloat_Unpack4(const unsigned char *p, int le)
1832{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001833 if (float_format == unknown_format) {
1834 unsigned char sign;
1835 int e;
1836 unsigned int f;
1837 double x;
1838 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001839
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001840 if (le) {
1841 p += 3;
1842 incr = -1;
1843 }
1844
1845 /* First byte */
1846 sign = (*p >> 7) & 1;
1847 e = (*p & 0x7F) << 1;
1848 p += incr;
1849
1850 /* Second byte */
1851 e |= (*p >> 7) & 1;
1852 f = (*p & 0x7F) << 16;
1853 p += incr;
1854
1855 if (e == 255) {
1856 PyErr_SetString(
1857 PyExc_ValueError,
1858 "can't unpack IEEE 754 special value "
1859 "on non-IEEE platform");
1860 return -1;
1861 }
1862
1863 /* Third byte */
1864 f |= *p << 8;
1865 p += incr;
1866
1867 /* Fourth byte */
1868 f |= *p;
1869
1870 x = (double)f / 8388608.0;
1871
1872 /* XXX This sadly ignores Inf/NaN issues */
1873 if (e == 0)
1874 e = -126;
1875 else {
1876 x += 1.0;
1877 e -= 127;
1878 }
1879 x = ldexp(x, e);
1880
1881 if (sign)
1882 x = -x;
1883
1884 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001885 }
Tim Peters9905b942003-03-20 20:53:32 +00001886 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001887 float x;
1888
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001889 if ((float_format == ieee_little_endian_format && !le)
1890 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001891 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892 char *d = &buf[3];
1893 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001894
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001895 for (i = 0; i < 4; i++) {
1896 *d-- = *p++;
1897 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001898 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001899 }
1900 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001901 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001902 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001903
1904 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001905 }
Tim Peters9905b942003-03-20 20:53:32 +00001906}
1907
1908double
1909_PyFloat_Unpack8(const unsigned char *p, int le)
1910{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001911 if (double_format == unknown_format) {
1912 unsigned char sign;
1913 int e;
1914 unsigned int fhi, flo;
1915 double x;
1916 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001917
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001918 if (le) {
1919 p += 7;
1920 incr = -1;
1921 }
1922
1923 /* First byte */
1924 sign = (*p >> 7) & 1;
1925 e = (*p & 0x7F) << 4;
1926
1927 p += incr;
1928
1929 /* Second byte */
1930 e |= (*p >> 4) & 0xF;
1931 fhi = (*p & 0xF) << 24;
1932 p += incr;
1933
1934 if (e == 2047) {
1935 PyErr_SetString(
1936 PyExc_ValueError,
1937 "can't unpack IEEE 754 special value "
1938 "on non-IEEE platform");
1939 return -1.0;
1940 }
1941
1942 /* Third byte */
1943 fhi |= *p << 16;
1944 p += incr;
1945
1946 /* Fourth byte */
1947 fhi |= *p << 8;
1948 p += incr;
1949
1950 /* Fifth byte */
1951 fhi |= *p;
1952 p += incr;
1953
1954 /* Sixth byte */
1955 flo = *p << 16;
1956 p += incr;
1957
1958 /* Seventh byte */
1959 flo |= *p << 8;
1960 p += incr;
1961
1962 /* Eighth byte */
1963 flo |= *p;
1964
1965 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1966 x /= 268435456.0; /* 2**28 */
1967
1968 if (e == 0)
1969 e = -1022;
1970 else {
1971 x += 1.0;
1972 e -= 1023;
1973 }
1974 x = ldexp(x, e);
1975
1976 if (sign)
1977 x = -x;
1978
1979 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001980 }
Tim Peters9905b942003-03-20 20:53:32 +00001981 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001982 double x;
1983
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001984 if ((double_format == ieee_little_endian_format && !le)
1985 || (double_format == ieee_big_endian_format && le)) {
1986 char buf[8];
1987 char *d = &buf[7];
1988 int i;
1989
1990 for (i = 0; i < 8; i++) {
1991 *d-- = *p++;
1992 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001993 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001994 }
1995 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001996 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001998
1999 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002000 }
Tim Peters9905b942003-03-20 20:53:32 +00002001}