blob: a832c5d05ec8ac772435cf2d9ffbf8af07869226 [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 Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Eric Smith8c663262007-08-25 02:26:07 +000010#include "formatter_unicode.h"
11
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000013#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Jack Janseneddc1442003-11-20 01:44:59 +000015#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000016extern double fmod(double, double);
17extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000018#endif
19
Guido van Rossum93ad0df1997-05-13 21:00:42 +000020/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000021#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000022#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000023#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000024
Guido van Rossum3fce8831999-03-12 19:43:17 +000025struct _floatblock {
26 struct _floatblock *next;
27 PyFloatObject objects[N_FLOATOBJECTS];
28};
29
30typedef struct _floatblock PyFloatBlock;
31
32static PyFloatBlock *block_list = NULL;
33static PyFloatObject *free_list = NULL;
34
Guido van Rossum93ad0df1997-05-13 21:00:42 +000035static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000036fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000037{
38 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000039 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
40 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000042 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000043 ((PyFloatBlock *)p)->next = block_list;
44 block_list = (PyFloatBlock *)p;
45 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046 q = p + N_FLOATOBJECTS;
47 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000048 Py_TYPE(q) = (struct _typeobject *)(q-1);
49 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 return p + N_FLOATOBJECTS - 1;
51}
52
Christian Heimes93852662007-12-01 12:22:32 +000053double
54PyFloat_GetMax(void)
55{
56 return DBL_MAX;
57}
58
59double
60PyFloat_GetMin(void)
61{
62 return DBL_MIN;
63}
64
Christian Heimesd32ed6f2008-01-14 18:49:24 +000065static PyTypeObject FloatInfoType;
66
67PyDoc_STRVAR(floatinfo__doc__,
68"sys.floatinfo\n\
69\n\
70A structseq holding information about the float type. It contains low level\n\
71information about the precision and internal representation. Please study\n\
72your system's :file:`float.h` for more information.");
73
74static PyStructSequence_Field floatinfo_fields[] = {
75 {"max", "DBL_MAX -- maximum representable finite float"},
76 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
77 "is representable"},
78 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
79 "is representable"},
80 {"min", "DBL_MIN -- Minimum positive normalizer float"},
81 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
82 "is a normalized float"},
83 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
84 "a normalized"},
85 {"dig", "DBL_DIG -- digits"},
86 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
87 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
88 "representable float"},
89 {"radix", "FLT_RADIX -- radix of exponent"},
90 {"rounds", "FLT_ROUNDS -- addition rounds"},
91 {0}
92};
93
94static PyStructSequence_Desc floatinfo_desc = {
95 "sys.floatinfo", /* name */
96 floatinfo__doc__, /* doc */
97 floatinfo_fields, /* fields */
98 11
99};
100
Christian Heimes93852662007-12-01 12:22:32 +0000101PyObject *
102PyFloat_GetInfo(void)
103{
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000104 static PyObject* floatinfo;
105 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000106
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000107 if (floatinfo != NULL) {
108 Py_INCREF(floatinfo);
109 return floatinfo;
110 }
111 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
112
113 floatinfo = PyStructSequence_New(&FloatInfoType);
114 if (floatinfo == NULL) {
115 return NULL;
116 }
Christian Heimes93852662007-12-01 12:22:32 +0000117
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000118#define SetIntFlag(flag) \
119 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
120#define SetDblFlag(flag) \
121 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000122
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000123 SetDblFlag(DBL_MAX);
124 SetIntFlag(DBL_MAX_EXP);
125 SetIntFlag(DBL_MAX_10_EXP);
126 SetDblFlag(DBL_MIN);
127 SetIntFlag(DBL_MIN_EXP);
128 SetIntFlag(DBL_MIN_10_EXP);
129 SetIntFlag(DBL_DIG);
130 SetIntFlag(DBL_MANT_DIG);
131 SetDblFlag(DBL_EPSILON);
132 SetIntFlag(FLT_RADIX);
133 SetIntFlag(FLT_ROUNDS);
134#undef SetIntFlag
135#undef SetDblFlag
136
137 if (PyErr_Occurred()) {
138 Py_CLEAR(floatinfo);
139 return NULL;
140 }
Christian Heimes93852662007-12-01 12:22:32 +0000141
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000142 Py_INCREF(floatinfo);
143 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000144}
145
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 register PyFloatObject *op;
150 if (free_list == NULL) {
151 if ((free_list = fill_free_list()) == NULL)
152 return NULL;
153 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000154 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000155 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000163PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164{
Christian Heimes99170a52007-12-19 02:07:34 +0000165 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000167 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000172 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
174 if (s_buffer == NULL)
175 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000176 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000177 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000178 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000179 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000180 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000181 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000183 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000184 else if (PyObject_AsCharBuffer(v, &s, &len)) {
185 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000186 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000189
Guido van Rossum4c08d552000-03-10 22:55:18 +0000190 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191 while (*s && isspace(Py_CHARMASK(*s)))
192 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000193 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000194 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000195 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 }
Christian Heimes99170a52007-12-19 02:07:34 +0000197 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000198 /* We don't care about overflow or underflow. If the platform supports
199 * them, infinities and signed zeroes (on underflow) are fine.
200 * However, strtod can return 0 for denormalized numbers, where atof
201 * does not. So (alas!) we special-case a zero result. Note that
202 * whether strtod sets errno on underflow is not defined, so we can't
203 * key off errno.
204 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000205 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000206 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000207 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000209 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000210 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000211 if (end > last)
212 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000213 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000214 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000215 char *p = (char*)sp;
216 int sign = 1;
217
218 if (*p == '-') {
219 sign = -1;
220 p++;
221 }
222 if (*p == '+') {
223 p++;
224 }
225 if (PyOS_strnicmp(p, "inf", 4) == 0) {
226 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
227 }
228#ifdef Py_NAN
229 if(PyOS_strnicmp(p, "nan", 4) == 0) {
230 return PyFloat_FromDouble(Py_NAN);
231 }
232#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000233 PyOS_snprintf(buffer, sizeof(buffer),
234 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000235 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000236 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000237 }
238 /* Since end != s, the platform made *some* kind of sense out
239 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000240 while (*end && isspace(Py_CHARMASK(*end)))
241 end++;
242 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000243 PyOS_snprintf(buffer, sizeof(buffer),
244 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000245 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000246 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000247 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000248 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 PyErr_SetString(PyExc_ValueError,
250 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000251 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000252 }
Tim Petersef14d732000-09-23 03:39:17 +0000253 if (x == 0.0) {
254 /* See above -- may have been strtod being anal
255 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000256 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000257 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000258 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000259 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000261 result = PyFloat_FromDouble(x);
262 error:
263 if (s_buffer)
264 PyMem_FREE(s_buffer);
265 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266}
267
Guido van Rossum234f9421993-06-17 12:35:49 +0000268static void
Fred Drakefd99de62000-07-09 05:02:18 +0000269float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000270{
Guido van Rossum9475a232001-10-05 20:51:39 +0000271 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000272 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000273 free_list = op;
274 }
275 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000276 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000277}
278
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279double
Fred Drakefd99de62000-07-09 05:02:18 +0000280PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 PyNumberMethods *nb;
283 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000286 if (op && PyFloat_Check(op))
287 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000289 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 return -1;
292 }
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Christian Heimes90aa7642007-12-19 02:45:37 +0000294 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000295 PyErr_SetString(PyExc_TypeError, "a float is required");
296 return -1;
297 }
298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300 if (fo == NULL)
301 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 if (!PyFloat_Check(fo)) {
303 PyErr_SetString(PyExc_TypeError,
304 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 return -1;
306 }
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 val = PyFloat_AS_DOUBLE(fo);
309 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312}
313
314/* Methods */
315
Tim Peters97019e42001-11-28 22:43:45 +0000316static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000317format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318{
319 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000320 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000321 int i;
322
323 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324 We want float numbers to be recognizable as such,
325 i.e., they should contain a decimal point or an exponent.
326 However, %g may print the number as an integer;
327 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000328
Martin v. Löwis737ea822004-06-08 18:52:54 +0000329 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000330 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331 cp = buf;
332 if (*cp == '-')
333 cp++;
334 for (; *cp != '\0'; cp++) {
335 /* Any non-digit means it's not an integer;
336 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000337 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 break;
339 }
340 if (*cp == '\0') {
341 *cp++ = '.';
342 *cp++ = '0';
343 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000344 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345 }
Christian Heimes99170a52007-12-19 02:07:34 +0000346 /* Checking the next three chars should be more than enough to
347 * detect inf or nan, even on Windows. We check for inf or nan
348 * at last because they are rare cases.
349 */
350 for (i=0; *cp != '\0' && i<3; cp++, i++) {
351 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
352 continue;
353 /* found something that is neither a digit nor point
354 * it might be a NaN or INF
355 */
356#ifdef Py_NAN
357 if (Py_IS_NAN(ob_fval)) {
358 strcpy(buf, "nan");
359 }
360 else
361#endif
362 if (Py_IS_INFINITY(ob_fval)) {
363 cp = buf;
364 if (*cp == '-')
365 cp++;
366 strcpy(cp, "inf");
367 }
368 break;
369 }
370
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371}
372
Neal Norwitz545686b2006-12-28 04:45:06 +0000373static void
374format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000375{
Neal Norwitz545686b2006-12-28 04:45:06 +0000376 assert(PyFloat_Check(v));
377 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000378}
379
Christian Heimesb76922a2007-12-11 01:06:40 +0000380#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000381/* The following function is based on Tcl_PrintDouble,
382 * from tclUtil.c.
383 */
384
385#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
386#define is_nan(d) ((d) != (d))
387
388static void
389format_double_repr(char *dst, double value)
390{
391 char *p, c;
392 int exp;
393 int signum;
394 char buffer[30];
395
396 /*
397 * Handle NaN.
398 */
399
400 if (is_nan(value)) {
401 strcpy(dst, "nan");
402 return;
403 }
404
405 /*
406 * Handle infinities.
407 */
408
409 if (is_infinite(value)) {
410 if (value < 0) {
411 strcpy(dst, "-inf");
412 } else {
413 strcpy(dst, "inf");
414 }
415 return;
416 }
417
418 /*
419 * Ordinary (normal and denormal) values.
420 */
421
422 exp = _PyFloat_Digits(buffer, value, &signum)+1;
423 if (signum) {
424 *dst++ = '-';
425 }
426 p = buffer;
427 if (exp < -3 || exp > 17) {
428 /*
429 * E format for numbers < 1e-3 or >= 1e17.
430 */
431
432 *dst++ = *p++;
433 c = *p;
434 if (c != '\0') {
435 *dst++ = '.';
436 while (c != '\0') {
437 *dst++ = c;
438 c = *++p;
439 }
440 }
441 sprintf(dst, "e%+d", exp-1);
442 } else {
443 /*
444 * F format for others.
445 */
446
447 if (exp <= 0) {
448 *dst++ = '0';
449 }
450 c = *p;
451 while (exp-- > 0) {
452 if (c != '\0') {
453 *dst++ = c;
454 c = *++p;
455 } else {
456 *dst++ = '0';
457 }
458 }
459 *dst++ = '.';
460 if (c == '\0') {
461 *dst++ = '0';
462 } else {
463 while (++exp < 0) {
464 *dst++ = '0';
465 }
466 while (c != '\0') {
467 *dst++ = c;
468 c = *++p;
469 }
470 }
471 *dst++ = '\0';
472 }
473}
474
475static void
476format_float_repr(char *buf, PyFloatObject *v)
477{
478 assert(PyFloat_Check(v));
479 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
480}
481
Christian Heimesb76922a2007-12-11 01:06:40 +0000482#endif /* Py_BROKEN_REPR */
483
Neil Schemenauer32117e52001-01-04 01:44:34 +0000484/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000485 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000486 set to NULL, and the function invoking this macro returns NULL. If
487 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
488 stored in obj, and returned from the function invoking this macro.
489*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000490#define CONVERT_TO_DOUBLE(obj, dbl) \
491 if (PyFloat_Check(obj)) \
492 dbl = PyFloat_AS_DOUBLE(obj); \
493 else if (convert_to_double(&(obj), &(dbl)) < 0) \
494 return obj;
495
496static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000497convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000498{
499 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000500
Guido van Rossumddefaf32007-01-14 03:31:43 +0000501 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000502 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000503 if (*dbl == -1.0 && PyErr_Occurred()) {
504 *v = NULL;
505 return -1;
506 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000507 }
508 else {
509 Py_INCREF(Py_NotImplemented);
510 *v = Py_NotImplemented;
511 return -1;
512 }
513 return 0;
514}
515
Guido van Rossum57072eb1999-12-23 19:00:28 +0000516/* Precisions used by repr() and str(), respectively.
517
518 The repr() precision (17 significant decimal digits) is the minimal number
519 that is guaranteed to have enough precision so that if the number is read
520 back in the exact same binary value is recreated. This is true for IEEE
521 floating point by design, and also happens to work for all other modern
522 hardware.
523
524 The str() precision is chosen so that in most cases, the rounding noise
525 created by various operations is suppressed, while giving plenty of
526 precision for practical use.
527
528*/
529
530#define PREC_REPR 17
531#define PREC_STR 12
532
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000534float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535{
Christian Heimesb76922a2007-12-11 01:06:40 +0000536#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000537 char buf[30];
538 format_float_repr(buf, v);
Christian Heimesb76922a2007-12-11 01:06:40 +0000539#else
540 char buf[100];
541 format_float(buf, sizeof(buf), v, PREC_REPR);
542#endif
543
Walter Dörwald1ab83302007-05-18 17:15:44 +0000544 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000545}
546
547static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000548float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000549{
550 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000551 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000552 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Tim Peters307fa782004-09-23 08:06:40 +0000555/* Comparison is pretty much a nightmare. When comparing float to float,
556 * we do it as straightforwardly (and long-windedly) as conceivable, so
557 * that, e.g., Python x == y delivers the same result as the platform
558 * C x == y when x and/or y is a NaN.
559 * When mixing float with an integer type, there's no good *uniform* approach.
560 * Converting the double to an integer obviously doesn't work, since we
561 * may lose info from fractional bits. Converting the integer to a double
562 * also has two failure modes: (1) a long int may trigger overflow (too
563 * large to fit in the dynamic range of a C double); (2) even a C long may have
564 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
565 * 63 bits of precision, but a C double probably has only 53), and then
566 * we can falsely claim equality when low-order integer bits are lost by
567 * coercion to double. So this part is painful too.
568 */
569
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000570static PyObject*
571float_richcompare(PyObject *v, PyObject *w, int op)
572{
573 double i, j;
574 int r = 0;
575
Tim Peters307fa782004-09-23 08:06:40 +0000576 assert(PyFloat_Check(v));
577 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000578
Tim Peters307fa782004-09-23 08:06:40 +0000579 /* Switch on the type of w. Set i and j to doubles to be compared,
580 * and op to the richcomp to use.
581 */
582 if (PyFloat_Check(w))
583 j = PyFloat_AS_DOUBLE(w);
584
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000586 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000587 /* If i is an infinity, its magnitude exceeds any
588 * finite integer, so it doesn't matter which int we
589 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000590 */
591 j = 0.0;
592 else
593 goto Unimplemented;
594 }
595
Tim Peters307fa782004-09-23 08:06:40 +0000596 else if (PyLong_Check(w)) {
597 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
598 int wsign = _PyLong_Sign(w);
599 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000600 int exponent;
601
602 if (vsign != wsign) {
603 /* Magnitudes are irrelevant -- the signs alone
604 * determine the outcome.
605 */
606 i = (double)vsign;
607 j = (double)wsign;
608 goto Compare;
609 }
610 /* The signs are the same. */
611 /* Convert w to a double if it fits. In particular, 0 fits. */
612 nbits = _PyLong_NumBits(w);
613 if (nbits == (size_t)-1 && PyErr_Occurred()) {
614 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000615 * to hold the # of bits. Replace with little doubles
616 * that give the same outcome -- w is so large that
617 * its magnitude must exceed the magnitude of any
618 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000619 */
620 PyErr_Clear();
621 i = (double)vsign;
622 assert(wsign != 0);
623 j = wsign * 2.0;
624 goto Compare;
625 }
626 if (nbits <= 48) {
627 j = PyLong_AsDouble(w);
628 /* It's impossible that <= 48 bits overflowed. */
629 assert(j != -1.0 || ! PyErr_Occurred());
630 goto Compare;
631 }
632 assert(wsign != 0); /* else nbits was 0 */
633 assert(vsign != 0); /* if vsign were 0, then since wsign is
634 * not 0, we would have taken the
635 * vsign != wsign branch at the start */
636 /* We want to work with non-negative numbers. */
637 if (vsign < 0) {
638 /* "Multiply both sides" by -1; this also swaps the
639 * comparator.
640 */
641 i = -i;
642 op = _Py_SwappedOp[op];
643 }
644 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000645 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000646 /* exponent is the # of bits in v before the radix point;
647 * we know that nbits (the # of bits in w) > 48 at this point
648 */
649 if (exponent < 0 || (size_t)exponent < nbits) {
650 i = 1.0;
651 j = 2.0;
652 goto Compare;
653 }
654 if ((size_t)exponent > nbits) {
655 i = 2.0;
656 j = 1.0;
657 goto Compare;
658 }
659 /* v and w have the same number of bits before the radix
660 * point. Construct two longs that have the same comparison
661 * outcome.
662 */
663 {
664 double fracpart;
665 double intpart;
666 PyObject *result = NULL;
667 PyObject *one = NULL;
668 PyObject *vv = NULL;
669 PyObject *ww = w;
670
671 if (wsign < 0) {
672 ww = PyNumber_Negative(w);
673 if (ww == NULL)
674 goto Error;
675 }
676 else
677 Py_INCREF(ww);
678
679 fracpart = modf(i, &intpart);
680 vv = PyLong_FromDouble(intpart);
681 if (vv == NULL)
682 goto Error;
683
684 if (fracpart != 0.0) {
685 /* Shift left, and or a 1 bit into vv
686 * to represent the lost fraction.
687 */
688 PyObject *temp;
689
Christian Heimes217cfd12007-12-02 14:31:20 +0000690 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000691 if (one == NULL)
692 goto Error;
693
694 temp = PyNumber_Lshift(ww, one);
695 if (temp == NULL)
696 goto Error;
697 Py_DECREF(ww);
698 ww = temp;
699
700 temp = PyNumber_Lshift(vv, one);
701 if (temp == NULL)
702 goto Error;
703 Py_DECREF(vv);
704 vv = temp;
705
706 temp = PyNumber_Or(vv, one);
707 if (temp == NULL)
708 goto Error;
709 Py_DECREF(vv);
710 vv = temp;
711 }
712
713 r = PyObject_RichCompareBool(vv, ww, op);
714 if (r < 0)
715 goto Error;
716 result = PyBool_FromLong(r);
717 Error:
718 Py_XDECREF(vv);
719 Py_XDECREF(ww);
720 Py_XDECREF(one);
721 return result;
722 }
723 } /* else if (PyLong_Check(w)) */
724
725 else /* w isn't float, int, or long */
726 goto Unimplemented;
727
728 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000729 PyFPE_START_PROTECT("richcompare", return NULL)
730 switch (op) {
731 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000732 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000733 break;
734 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000735 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000736 break;
737 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000738 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000739 break;
740 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000741 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000742 break;
743 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000744 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000745 break;
746 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000747 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000748 break;
749 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000750 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000751 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000752
753 Unimplemented:
754 Py_INCREF(Py_NotImplemented);
755 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000756}
757
Guido van Rossum9bfef441993-03-29 10:43:31 +0000758static long
Fred Drakefd99de62000-07-09 05:02:18 +0000759float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000760{
Tim Peters39dce292000-08-15 03:34:48 +0000761 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000762}
763
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000765float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000767 double a,b;
768 CONVERT_TO_DOUBLE(v, a);
769 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000770 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000771 a = a + b;
772 PyFPE_END_PROTECT(a)
773 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774}
775
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000777float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000779 double a,b;
780 CONVERT_TO_DOUBLE(v, a);
781 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000782 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000783 a = a - b;
784 PyFPE_END_PROTECT(a)
785 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786}
787
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000789float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000791 double a,b;
792 CONVERT_TO_DOUBLE(v, a);
793 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000794 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000795 a = a * b;
796 PyFPE_END_PROTECT(a)
797 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798}
799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000801float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000803 double a,b;
804 CONVERT_TO_DOUBLE(v, a);
805 CONVERT_TO_DOUBLE(w, b);
806 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000807 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808 return NULL;
809 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000810 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000811 a = a / b;
812 PyFPE_END_PROTECT(a)
813 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000814}
815
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000816static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000817float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000819 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000820 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000821 CONVERT_TO_DOUBLE(v, vx);
822 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825 return NULL;
826 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000827 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000828 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000829 /* note: checking mod*wx < 0 is incorrect -- underflows to
830 0 if wx < sqrt(smallest nonzero double) */
831 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000832 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000833 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000834 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000836}
837
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000838static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000839float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000840{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000841 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000842 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000843 CONVERT_TO_DOUBLE(v, vx);
844 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000845 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000846 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000847 return NULL;
848 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000849 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000850 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000851 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000852 exact multiple of wx. But this is fp arithmetic, and fp
853 vx - mod is an approximation; the result is that div may
854 not be an exact integral value after the division, although
855 it will always be very close to one.
856 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000857 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000858 if (mod) {
859 /* ensure the remainder has the same sign as the denominator */
860 if ((wx < 0) != (mod < 0)) {
861 mod += wx;
862 div -= 1.0;
863 }
864 }
865 else {
866 /* the remainder is zero, and in the presence of signed zeroes
867 fmod returns different results across platforms; ensure
868 it has the same sign as the denominator; we'd like to do
869 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000870 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000871 if (wx < 0.0)
872 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000873 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000874 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000875 if (div) {
876 floordiv = floor(div);
877 if (div - floordiv > 0.5)
878 floordiv += 1.0;
879 }
880 else {
881 /* div is zero - get the same sign as the true quotient */
882 div *= div; /* hide "div = +0" from optimizers */
883 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
884 }
885 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000886 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000887}
888
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000890float_floor_div(PyObject *v, PyObject *w)
891{
892 PyObject *t, *r;
893
894 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000895 if (t == NULL || t == Py_NotImplemented)
896 return t;
897 assert(PyTuple_CheckExact(t));
898 r = PyTuple_GET_ITEM(t, 0);
899 Py_INCREF(r);
900 Py_DECREF(t);
901 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000902}
903
904static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000905float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000906{
907 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000908
909 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000910 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000911 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000912 return NULL;
913 }
914
Neil Schemenauer32117e52001-01-04 01:44:34 +0000915 CONVERT_TO_DOUBLE(v, iv);
916 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000917
918 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000919 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000920 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000921 }
Tim Peters96685bf2001-08-23 22:31:37 +0000922 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000923 if (iw < 0.0) {
924 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000925 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000926 return NULL;
927 }
928 return PyFloat_FromDouble(0.0);
929 }
Tim Peterse87568d2003-05-24 20:18:24 +0000930 if (iv < 0.0) {
931 /* Whether this is an error is a mess, and bumps into libm
932 * bugs so we have to figure it out ourselves.
933 */
934 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000935 /* Negative numbers raised to fractional powers
936 * become complex.
937 */
938 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000939 }
940 /* iw is an exact integer, albeit perhaps a very large one.
941 * -1 raised to an exact integer should never be exceptional.
942 * Alas, some libms (chiefly glibc as of early 2003) return
943 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
944 * happen to be representable in a *C* integer. That's a
945 * bug; we let that slide in math.pow() (which currently
946 * reflects all platform accidents), but not for Python's **.
947 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000948 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000949 /* Return 1 if iw is even, -1 if iw is odd; there's
950 * no guarantee that any C integral type is big
951 * enough to hold iw, so we have to check this
952 * indirectly.
953 */
954 ix = floor(iw * 0.5) * 2.0;
955 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
956 }
957 /* Else iv != -1.0, and overflow or underflow are possible.
958 * Unless we're to write pow() ourselves, we have to trust
959 * the platform to do this correctly.
960 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000961 }
Tim Peters96685bf2001-08-23 22:31:37 +0000962 errno = 0;
963 PyFPE_START_PROTECT("pow", return NULL)
964 ix = pow(iv, iw);
965 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000966 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000967 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000968 /* We don't expect any errno value other than ERANGE, but
969 * the range of libm bugs appears unbounded.
970 */
971 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
972 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000973 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000974 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000976}
977
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000978static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000979float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000980{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000981 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000982}
983
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000985float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000986{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000987 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000988}
989
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000990static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000991float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000992{
993 return v->ob_fval != 0.0;
994}
995
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000997float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000998{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000999 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001000 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001001
1002 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001003 /* Try to get out cheap if this fits in a Python int. The attempt
1004 * to cast to long must be protected, as C doesn't define what
1005 * happens if the double is too big to fit in a long. Some rare
1006 * systems raise an exception then (RISCOS was mentioned as one,
1007 * and someone using a non-default option on Sun also bumped into
1008 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1009 * still be vulnerable: if a long has more bits of precision than
1010 * a double, casting MIN/MAX to double may yield an approximation,
1011 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1012 * yield true from the C expression wholepart<=LONG_MAX, despite
1013 * that wholepart is actually greater than LONG_MAX.
1014 */
1015 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1016 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +00001017 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001018 }
1019 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001020}
1021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001022static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001023float_round(PyObject *v, PyObject *args)
1024{
1025#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1026 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001027 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001028 double flr, cil;
1029 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001030 int ndigits = UNDEF_NDIGITS;
1031
1032 if (!PyArg_ParseTuple(args, "|i", &ndigits))
1033 return NULL;
1034
1035 x = PyFloat_AsDouble(v);
1036
1037 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001038 f = pow(10.0, ndigits);
1039 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001040 }
1041
1042 flr = floor(x);
1043 cil = ceil(x);
1044
1045 if (x-flr > 0.5)
1046 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001047 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001048 rounded = fmod(flr, 2) == 0 ? flr : cil;
1049 else
1050 rounded = flr;
1051
1052 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001053 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001054 return PyFloat_FromDouble(rounded);
1055 }
1056
1057 return PyLong_FromDouble(rounded);
1058#undef UNDEF_NDIGITS
1059}
1060
1061static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001062float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001064 if (PyFloat_CheckExact(v))
1065 Py_INCREF(v);
1066 else
1067 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001068 return v;
1069}
1070
1071
Jeremy Hylton938ace62002-07-17 16:30:39 +00001072static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001073float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1074
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075static PyObject *
1076float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1077{
1078 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001079 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
Guido van Rossumbef14172001-08-29 15:47:46 +00001081 if (type != &PyFloat_Type)
1082 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1084 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001085 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001086 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 return PyNumber_Float(x);
1088}
1089
Guido van Rossumbef14172001-08-29 15:47:46 +00001090/* Wimpy, slow approach to tp_new calls for subtypes of float:
1091 first create a regular float from whatever arguments we got,
1092 then allocate a subtype instance and initialize its ob_fval
1093 from the regular float. The regular float is then thrown away.
1094*/
1095static PyObject *
1096float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1097{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001098 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001099
1100 assert(PyType_IsSubtype(type, &PyFloat_Type));
1101 tmp = float_new(&PyFloat_Type, args, kwds);
1102 if (tmp == NULL)
1103 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001104 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001105 newobj = type->tp_alloc(type, 0);
1106 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001107 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001108 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001109 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001110 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001111 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001112 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001113}
1114
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001115static PyObject *
1116float_getnewargs(PyFloatObject *v)
1117{
1118 return Py_BuildValue("(d)", v->ob_fval);
1119}
1120
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001121/* this is for the benefit of the pack/unpack routines below */
1122
1123typedef enum {
1124 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1125} float_format_type;
1126
1127static float_format_type double_format, float_format;
1128static float_format_type detected_double_format, detected_float_format;
1129
1130static PyObject *
1131float_getformat(PyTypeObject *v, PyObject* arg)
1132{
1133 char* s;
1134 float_format_type r;
1135
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001136 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001137 PyErr_Format(PyExc_TypeError,
1138 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001139 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001140 return NULL;
1141 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001142 s = PyUnicode_AsString(arg);
1143 if (s == NULL)
1144 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001145 if (strcmp(s, "double") == 0) {
1146 r = double_format;
1147 }
1148 else if (strcmp(s, "float") == 0) {
1149 r = float_format;
1150 }
1151 else {
1152 PyErr_SetString(PyExc_ValueError,
1153 "__getformat__() argument 1 must be "
1154 "'double' or 'float'");
1155 return NULL;
1156 }
1157
1158 switch (r) {
1159 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001160 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001161 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001162 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001163 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001164 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001165 default:
1166 Py_FatalError("insane float_format or double_format");
1167 return NULL;
1168 }
1169}
1170
1171PyDoc_STRVAR(float_getformat_doc,
1172"float.__getformat__(typestr) -> string\n"
1173"\n"
1174"You probably don't want to use this function. It exists mainly to be\n"
1175"used in Python's test suite.\n"
1176"\n"
1177"typestr must be 'double' or 'float'. This function returns whichever of\n"
1178"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1179"format of floating point numbers used by the C type named by typestr.");
1180
1181static PyObject *
1182float_setformat(PyTypeObject *v, PyObject* args)
1183{
1184 char* typestr;
1185 char* format;
1186 float_format_type f;
1187 float_format_type detected;
1188 float_format_type *p;
1189
1190 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1191 return NULL;
1192
1193 if (strcmp(typestr, "double") == 0) {
1194 p = &double_format;
1195 detected = detected_double_format;
1196 }
1197 else if (strcmp(typestr, "float") == 0) {
1198 p = &float_format;
1199 detected = detected_float_format;
1200 }
1201 else {
1202 PyErr_SetString(PyExc_ValueError,
1203 "__setformat__() argument 1 must "
1204 "be 'double' or 'float'");
1205 return NULL;
1206 }
1207
1208 if (strcmp(format, "unknown") == 0) {
1209 f = unknown_format;
1210 }
1211 else if (strcmp(format, "IEEE, little-endian") == 0) {
1212 f = ieee_little_endian_format;
1213 }
1214 else if (strcmp(format, "IEEE, big-endian") == 0) {
1215 f = ieee_big_endian_format;
1216 }
1217 else {
1218 PyErr_SetString(PyExc_ValueError,
1219 "__setformat__() argument 2 must be "
1220 "'unknown', 'IEEE, little-endian' or "
1221 "'IEEE, big-endian'");
1222 return NULL;
1223
1224 }
1225
1226 if (f != unknown_format && f != detected) {
1227 PyErr_Format(PyExc_ValueError,
1228 "can only set %s format to 'unknown' or the "
1229 "detected platform value", typestr);
1230 return NULL;
1231 }
1232
1233 *p = f;
1234 Py_RETURN_NONE;
1235}
1236
1237PyDoc_STRVAR(float_setformat_doc,
1238"float.__setformat__(typestr, fmt) -> None\n"
1239"\n"
1240"You probably don't want to use this function. It exists mainly to be\n"
1241"used in Python's test suite.\n"
1242"\n"
1243"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1244"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1245"one of the latter two if it appears to match the underlying C reality.\n"
1246"\n"
1247"Overrides the automatic determination of C-level floating point type.\n"
1248"This affects how floats are converted to and from binary strings.");
1249
Guido van Rossumb43daf72007-08-01 18:08:08 +00001250static PyObject *
1251float_getzero(PyObject *v, void *closure)
1252{
1253 return PyFloat_FromDouble(0.0);
1254}
1255
Eric Smith8c663262007-08-25 02:26:07 +00001256static PyObject *
1257float__format__(PyObject *self, PyObject *args)
1258{
1259 /* when back porting this to 2.6, check type of the format_spec
1260 and call either unicode_long__format__ or
1261 string_long__format__ */
1262 return unicode_float__format__(self, args);
1263}
1264
1265PyDoc_STRVAR(float__format__doc,
1266"float.__format__(format_spec) -> string\n"
1267"\n"
1268"Formats the float according to format_spec.");
1269
1270
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001271static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001272 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1273 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001274 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1275 "Returns the Integral closest to x between 0 and x."},
1276 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1277 "Returns the Integral closest to x, rounding half toward even.\n"
1278 "When an argument is passed, works like built-in round(x, ndigits)."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001279 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001280 {"__getformat__", (PyCFunction)float_getformat,
1281 METH_O|METH_CLASS, float_getformat_doc},
1282 {"__setformat__", (PyCFunction)float_setformat,
1283 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001284 {"__format__", (PyCFunction)float__format__,
1285 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001286 {NULL, NULL} /* sentinel */
1287};
1288
Guido van Rossumb43daf72007-08-01 18:08:08 +00001289static PyGetSetDef float_getset[] = {
1290 {"real",
1291 (getter)float_float, (setter)NULL,
1292 "the real part of a complex number",
1293 NULL},
1294 {"imag",
1295 (getter)float_getzero, (setter)NULL,
1296 "the imaginary part of a complex number",
1297 NULL},
1298 {NULL} /* Sentinel */
1299};
1300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001301PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302"float(x) -> floating point number\n\
1303\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001304Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
1306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001308 float_add, /*nb_add*/
1309 float_sub, /*nb_subtract*/
1310 float_mul, /*nb_multiply*/
1311 float_rem, /*nb_remainder*/
1312 float_divmod, /*nb_divmod*/
1313 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001314 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001315 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001316 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001317 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001318 0, /*nb_invert*/
1319 0, /*nb_lshift*/
1320 0, /*nb_rshift*/
1321 0, /*nb_and*/
1322 0, /*nb_xor*/
1323 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001324 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001325 float_trunc, /*nb_int*/
1326 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001327 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001328 0, /* nb_oct */
1329 0, /* nb_hex */
1330 0, /* nb_inplace_add */
1331 0, /* nb_inplace_subtract */
1332 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001333 0, /* nb_inplace_remainder */
1334 0, /* nb_inplace_power */
1335 0, /* nb_inplace_lshift */
1336 0, /* nb_inplace_rshift */
1337 0, /* nb_inplace_and */
1338 0, /* nb_inplace_xor */
1339 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001340 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001341 float_div, /* nb_true_divide */
1342 0, /* nb_inplace_floor_divide */
1343 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001344};
1345
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001346PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001347 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001348 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001349 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001350 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001351 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001352 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 0, /* tp_getattr */
1354 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001355 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 (reprfunc)float_repr, /* tp_repr */
1357 &float_as_number, /* tp_as_number */
1358 0, /* tp_as_sequence */
1359 0, /* tp_as_mapping */
1360 (hashfunc)float_hash, /* tp_hash */
1361 0, /* tp_call */
1362 (reprfunc)float_str, /* tp_str */
1363 PyObject_GenericGetAttr, /* tp_getattro */
1364 0, /* tp_setattro */
1365 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001366 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367 float_doc, /* tp_doc */
1368 0, /* tp_traverse */
1369 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001370 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371 0, /* tp_weaklistoffset */
1372 0, /* tp_iter */
1373 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001374 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001376 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 0, /* tp_base */
1378 0, /* tp_dict */
1379 0, /* tp_descr_get */
1380 0, /* tp_descr_set */
1381 0, /* tp_dictoffset */
1382 0, /* tp_init */
1383 0, /* tp_alloc */
1384 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001385};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001386
1387void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001388_PyFloat_Init(void)
1389{
1390 /* We attempt to determine if this machine is using IEEE
1391 floating point formats by peering at the bits of some
1392 carefully chosen values. If it looks like we are on an
1393 IEEE platform, the float packing/unpacking routines can
1394 just copy bits, if not they resort to arithmetic & shifts
1395 and masks. The shifts & masks approach works on all finite
1396 values, but what happens to infinities, NaNs and signed
1397 zeroes on packing is an accident, and attempting to unpack
1398 a NaN or an infinity will raise an exception.
1399
1400 Note that if we're on some whacked-out platform which uses
1401 IEEE formats but isn't strictly little-endian or big-
1402 endian, we will fall back to the portable shifts & masks
1403 method. */
1404
1405#if SIZEOF_DOUBLE == 8
1406 {
1407 double x = 9006104071832581.0;
1408 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1409 detected_double_format = ieee_big_endian_format;
1410 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1411 detected_double_format = ieee_little_endian_format;
1412 else
1413 detected_double_format = unknown_format;
1414 }
1415#else
1416 detected_double_format = unknown_format;
1417#endif
1418
1419#if SIZEOF_FLOAT == 4
1420 {
1421 float y = 16711938.0;
1422 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1423 detected_float_format = ieee_big_endian_format;
1424 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1425 detected_float_format = ieee_little_endian_format;
1426 else
1427 detected_float_format = unknown_format;
1428 }
1429#else
1430 detected_float_format = unknown_format;
1431#endif
1432
1433 double_format = detected_double_format;
1434 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001435
1436#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001437 /* Initialize floating point repr */
1438 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001439#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001440}
1441
1442void
Fred Drakefd99de62000-07-09 05:02:18 +00001443PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001444{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001445 PyFloatObject *p;
1446 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001447 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001448 int bc, bf; /* block count, number of freed blocks */
1449 int frem, fsum; /* remaining unfreed floats per block, total */
1450
1451 bc = 0;
1452 bf = 0;
1453 fsum = 0;
1454 list = block_list;
1455 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001456 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001457 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001458 bc++;
1459 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001460 for (i = 0, p = &list->objects[0];
1461 i < N_FLOATOBJECTS;
1462 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001463 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001464 frem++;
1465 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001466 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001467 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001468 list->next = block_list;
1469 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001470 for (i = 0, p = &list->objects[0];
1471 i < N_FLOATOBJECTS;
1472 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001473 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001474 Py_REFCNT(p) == 0) {
1475 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001476 free_list;
1477 free_list = p;
1478 }
1479 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001480 }
1481 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001482 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001483 bf++;
1484 }
1485 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001486 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001487 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001488 if (!Py_VerboseFlag)
1489 return;
1490 fprintf(stderr, "# cleanup floats");
1491 if (!fsum) {
1492 fprintf(stderr, "\n");
1493 }
1494 else {
1495 fprintf(stderr,
1496 ": %d unfreed float%s in %d out of %d block%s\n",
1497 fsum, fsum == 1 ? "" : "s",
1498 bc - bf, bc, bc == 1 ? "" : "s");
1499 }
1500 if (Py_VerboseFlag > 1) {
1501 list = block_list;
1502 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001503 for (i = 0, p = &list->objects[0];
1504 i < N_FLOATOBJECTS;
1505 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001506 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001507 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001508 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001509 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001510 /* XXX(twouters) cast refcount to
1511 long until %zd is universally
1512 available
1513 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001514 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001515 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001516 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001517 }
1518 }
1519 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001520 }
1521 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001522}
Tim Peters9905b942003-03-20 20:53:32 +00001523
1524/*----------------------------------------------------------------------------
1525 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1526 *
1527 * TODO: On platforms that use the standard IEEE-754 single and double
1528 * formats natively, these routines could simply copy the bytes.
1529 */
1530int
1531_PyFloat_Pack4(double x, unsigned char *p, int le)
1532{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001533 if (float_format == unknown_format) {
1534 unsigned char sign;
1535 int e;
1536 double f;
1537 unsigned int fbits;
1538 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001539
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001540 if (le) {
1541 p += 3;
1542 incr = -1;
1543 }
Tim Peters9905b942003-03-20 20:53:32 +00001544
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001545 if (x < 0) {
1546 sign = 1;
1547 x = -x;
1548 }
1549 else
1550 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001551
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001552 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001553
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001554 /* Normalize f to be in the range [1.0, 2.0) */
1555 if (0.5 <= f && f < 1.0) {
1556 f *= 2.0;
1557 e--;
1558 }
1559 else if (f == 0.0)
1560 e = 0;
1561 else {
1562 PyErr_SetString(PyExc_SystemError,
1563 "frexp() result out of range");
1564 return -1;
1565 }
1566
1567 if (e >= 128)
1568 goto Overflow;
1569 else if (e < -126) {
1570 /* Gradual underflow */
1571 f = ldexp(f, 126 + e);
1572 e = 0;
1573 }
1574 else if (!(e == 0 && f == 0.0)) {
1575 e += 127;
1576 f -= 1.0; /* Get rid of leading 1 */
1577 }
1578
1579 f *= 8388608.0; /* 2**23 */
1580 fbits = (unsigned int)(f + 0.5); /* Round */
1581 assert(fbits <= 8388608);
1582 if (fbits >> 23) {
1583 /* The carry propagated out of a string of 23 1 bits. */
1584 fbits = 0;
1585 ++e;
1586 if (e >= 255)
1587 goto Overflow;
1588 }
1589
1590 /* First byte */
1591 *p = (sign << 7) | (e >> 1);
1592 p += incr;
1593
1594 /* Second byte */
1595 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1596 p += incr;
1597
1598 /* Third byte */
1599 *p = (fbits >> 8) & 0xFF;
1600 p += incr;
1601
1602 /* Fourth byte */
1603 *p = fbits & 0xFF;
1604
1605 /* Done */
1606 return 0;
1607
1608 Overflow:
1609 PyErr_SetString(PyExc_OverflowError,
1610 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001611 return -1;
1612 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001614 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615 const char *s = (char*)&y;
1616 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001617
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001618 if ((float_format == ieee_little_endian_format && !le)
1619 || (float_format == ieee_big_endian_format && le)) {
1620 p += 3;
1621 incr = -1;
1622 }
1623
1624 for (i = 0; i < 4; i++) {
1625 *p = *s++;
1626 p += incr;
1627 }
1628 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001629 }
Tim Peters9905b942003-03-20 20:53:32 +00001630}
1631
1632int
1633_PyFloat_Pack8(double x, unsigned char *p, int le)
1634{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001635 if (double_format == unknown_format) {
1636 unsigned char sign;
1637 int e;
1638 double f;
1639 unsigned int fhi, flo;
1640 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001641
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001642 if (le) {
1643 p += 7;
1644 incr = -1;
1645 }
Tim Peters9905b942003-03-20 20:53:32 +00001646
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001647 if (x < 0) {
1648 sign = 1;
1649 x = -x;
1650 }
1651 else
1652 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001653
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001654 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001655
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001656 /* Normalize f to be in the range [1.0, 2.0) */
1657 if (0.5 <= f && f < 1.0) {
1658 f *= 2.0;
1659 e--;
1660 }
1661 else if (f == 0.0)
1662 e = 0;
1663 else {
1664 PyErr_SetString(PyExc_SystemError,
1665 "frexp() result out of range");
1666 return -1;
1667 }
1668
1669 if (e >= 1024)
1670 goto Overflow;
1671 else if (e < -1022) {
1672 /* Gradual underflow */
1673 f = ldexp(f, 1022 + e);
1674 e = 0;
1675 }
1676 else if (!(e == 0 && f == 0.0)) {
1677 e += 1023;
1678 f -= 1.0; /* Get rid of leading 1 */
1679 }
1680
1681 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1682 f *= 268435456.0; /* 2**28 */
1683 fhi = (unsigned int)f; /* Truncate */
1684 assert(fhi < 268435456);
1685
1686 f -= (double)fhi;
1687 f *= 16777216.0; /* 2**24 */
1688 flo = (unsigned int)(f + 0.5); /* Round */
1689 assert(flo <= 16777216);
1690 if (flo >> 24) {
1691 /* The carry propagated out of a string of 24 1 bits. */
1692 flo = 0;
1693 ++fhi;
1694 if (fhi >> 28) {
1695 /* And it also progagated out of the next 28 bits. */
1696 fhi = 0;
1697 ++e;
1698 if (e >= 2047)
1699 goto Overflow;
1700 }
1701 }
1702
1703 /* First byte */
1704 *p = (sign << 7) | (e >> 4);
1705 p += incr;
1706
1707 /* Second byte */
1708 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1709 p += incr;
1710
1711 /* Third byte */
1712 *p = (fhi >> 16) & 0xFF;
1713 p += incr;
1714
1715 /* Fourth byte */
1716 *p = (fhi >> 8) & 0xFF;
1717 p += incr;
1718
1719 /* Fifth byte */
1720 *p = fhi & 0xFF;
1721 p += incr;
1722
1723 /* Sixth byte */
1724 *p = (flo >> 16) & 0xFF;
1725 p += incr;
1726
1727 /* Seventh byte */
1728 *p = (flo >> 8) & 0xFF;
1729 p += incr;
1730
1731 /* Eighth byte */
1732 *p = flo & 0xFF;
1733 p += incr;
1734
1735 /* Done */
1736 return 0;
1737
1738 Overflow:
1739 PyErr_SetString(PyExc_OverflowError,
1740 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001741 return -1;
1742 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001743 else {
1744 const char *s = (char*)&x;
1745 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001746
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001747 if ((double_format == ieee_little_endian_format && !le)
1748 || (double_format == ieee_big_endian_format && le)) {
1749 p += 7;
1750 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001751 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001752
1753 for (i = 0; i < 8; i++) {
1754 *p = *s++;
1755 p += incr;
1756 }
1757 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001758 }
Tim Peters9905b942003-03-20 20:53:32 +00001759}
1760
Neal Norwitz545686b2006-12-28 04:45:06 +00001761/* Should only be used by marshal. */
1762int
1763_PyFloat_Repr(double x, char *p, size_t len)
1764{
1765 format_double(p, len, x, PREC_REPR);
1766 return (int)strlen(p);
1767}
1768
Tim Peters9905b942003-03-20 20:53:32 +00001769double
1770_PyFloat_Unpack4(const unsigned char *p, int le)
1771{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001772 if (float_format == unknown_format) {
1773 unsigned char sign;
1774 int e;
1775 unsigned int f;
1776 double x;
1777 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001778
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001779 if (le) {
1780 p += 3;
1781 incr = -1;
1782 }
1783
1784 /* First byte */
1785 sign = (*p >> 7) & 1;
1786 e = (*p & 0x7F) << 1;
1787 p += incr;
1788
1789 /* Second byte */
1790 e |= (*p >> 7) & 1;
1791 f = (*p & 0x7F) << 16;
1792 p += incr;
1793
1794 if (e == 255) {
1795 PyErr_SetString(
1796 PyExc_ValueError,
1797 "can't unpack IEEE 754 special value "
1798 "on non-IEEE platform");
1799 return -1;
1800 }
1801
1802 /* Third byte */
1803 f |= *p << 8;
1804 p += incr;
1805
1806 /* Fourth byte */
1807 f |= *p;
1808
1809 x = (double)f / 8388608.0;
1810
1811 /* XXX This sadly ignores Inf/NaN issues */
1812 if (e == 0)
1813 e = -126;
1814 else {
1815 x += 1.0;
1816 e -= 127;
1817 }
1818 x = ldexp(x, e);
1819
1820 if (sign)
1821 x = -x;
1822
1823 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001824 }
Tim Peters9905b942003-03-20 20:53:32 +00001825 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001826 float x;
1827
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001828 if ((float_format == ieee_little_endian_format && !le)
1829 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001830 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001831 char *d = &buf[3];
1832 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001833
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001834 for (i = 0; i < 4; i++) {
1835 *d-- = *p++;
1836 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001837 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001838 }
1839 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001840 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001841 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001842
1843 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001844 }
Tim Peters9905b942003-03-20 20:53:32 +00001845}
1846
1847double
1848_PyFloat_Unpack8(const unsigned char *p, int le)
1849{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001850 if (double_format == unknown_format) {
1851 unsigned char sign;
1852 int e;
1853 unsigned int fhi, flo;
1854 double x;
1855 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001856
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001857 if (le) {
1858 p += 7;
1859 incr = -1;
1860 }
1861
1862 /* First byte */
1863 sign = (*p >> 7) & 1;
1864 e = (*p & 0x7F) << 4;
1865
1866 p += incr;
1867
1868 /* Second byte */
1869 e |= (*p >> 4) & 0xF;
1870 fhi = (*p & 0xF) << 24;
1871 p += incr;
1872
1873 if (e == 2047) {
1874 PyErr_SetString(
1875 PyExc_ValueError,
1876 "can't unpack IEEE 754 special value "
1877 "on non-IEEE platform");
1878 return -1.0;
1879 }
1880
1881 /* Third byte */
1882 fhi |= *p << 16;
1883 p += incr;
1884
1885 /* Fourth byte */
1886 fhi |= *p << 8;
1887 p += incr;
1888
1889 /* Fifth byte */
1890 fhi |= *p;
1891 p += incr;
1892
1893 /* Sixth byte */
1894 flo = *p << 16;
1895 p += incr;
1896
1897 /* Seventh byte */
1898 flo |= *p << 8;
1899 p += incr;
1900
1901 /* Eighth byte */
1902 flo |= *p;
1903
1904 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1905 x /= 268435456.0; /* 2**28 */
1906
1907 if (e == 0)
1908 e = -1022;
1909 else {
1910 x += 1.0;
1911 e -= 1023;
1912 }
1913 x = ldexp(x, e);
1914
1915 if (sign)
1916 x = -x;
1917
1918 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001919 }
Tim Peters9905b942003-03-20 20:53:32 +00001920 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001921 double x;
1922
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001923 if ((double_format == ieee_little_endian_format && !le)
1924 || (double_format == ieee_big_endian_format && le)) {
1925 char buf[8];
1926 char *d = &buf[7];
1927 int i;
1928
1929 for (i = 0; i < 8; i++) {
1930 *d-- = *p++;
1931 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001932 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001933 }
1934 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001935 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001937
1938 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001939 }
Tim Peters9905b942003-03-20 20:53:32 +00001940}