blob: a748abbdada63799a20c258adebb71e00e924dcb [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
Christian Heimesbbe741d2008-03-28 10:53:29 +000015#ifdef HAVE_IEEEFP_H
16#include <ieeefp.h>
17#endif
18
Guido van Rossum6923e131990-11-02 17:50:43 +000019
Christian Heimes969fe572008-01-25 11:23:10 +000020#ifdef _OSF_SOURCE
21/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
22extern int finite(double);
23#endif
24
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000026#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000027#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000028#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000029
Guido van Rossum3fce8831999-03-12 19:43:17 +000030struct _floatblock {
31 struct _floatblock *next;
32 PyFloatObject objects[N_FLOATOBJECTS];
33};
34
35typedef struct _floatblock PyFloatBlock;
36
37static PyFloatBlock *block_list = NULL;
38static PyFloatObject *free_list = NULL;
39
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000041fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042{
43 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000044 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
45 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000048 ((PyFloatBlock *)p)->next = block_list;
49 block_list = (PyFloatBlock *)p;
50 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000051 q = p + N_FLOATOBJECTS;
52 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000053 Py_TYPE(q) = (struct _typeobject *)(q-1);
54 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055 return p + N_FLOATOBJECTS - 1;
56}
57
Christian Heimes93852662007-12-01 12:22:32 +000058double
59PyFloat_GetMax(void)
60{
61 return DBL_MAX;
62}
63
64double
65PyFloat_GetMin(void)
66{
67 return DBL_MIN;
68}
69
Christian Heimesd32ed6f2008-01-14 18:49:24 +000070static PyTypeObject FloatInfoType;
71
72PyDoc_STRVAR(floatinfo__doc__,
73"sys.floatinfo\n\
74\n\
75A structseq holding information about the float type. It contains low level\n\
76information about the precision and internal representation. Please study\n\
77your system's :file:`float.h` for more information.");
78
79static PyStructSequence_Field floatinfo_fields[] = {
80 {"max", "DBL_MAX -- maximum representable finite float"},
81 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
82 "is representable"},
83 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
84 "is representable"},
85 {"min", "DBL_MIN -- Minimum positive normalizer float"},
86 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
87 "is a normalized float"},
88 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
89 "a normalized"},
90 {"dig", "DBL_DIG -- digits"},
91 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
92 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
93 "representable float"},
94 {"radix", "FLT_RADIX -- radix of exponent"},
95 {"rounds", "FLT_ROUNDS -- addition rounds"},
96 {0}
97};
98
99static PyStructSequence_Desc floatinfo_desc = {
100 "sys.floatinfo", /* name */
101 floatinfo__doc__, /* doc */
102 floatinfo_fields, /* fields */
103 11
104};
105
Christian Heimes93852662007-12-01 12:22:32 +0000106PyObject *
107PyFloat_GetInfo(void)
108{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000109 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000110 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000111
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000112 floatinfo = PyStructSequence_New(&FloatInfoType);
113 if (floatinfo == NULL) {
114 return NULL;
115 }
Christian Heimes93852662007-12-01 12:22:32 +0000116
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000117#define SetIntFlag(flag) \
118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
119#define SetDblFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000121
Christian Heimesd32ed6f2008-01-14 18:49:24 +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 Heimesd32ed6f2008-01-14 18:49:24 +0000140 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000141}
142
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000146 register PyFloatObject *op;
147 if (free_list == NULL) {
148 if ((free_list = fill_free_list()) == NULL)
149 return NULL;
150 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000151 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000152 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000153 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000154 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000155 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157}
158
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000160PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000161{
Christian Heimes99170a52007-12-19 02:07:34 +0000162 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000163 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000164 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000165 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000166 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000167 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000168
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000169 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000170 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
171 if (s_buffer == NULL)
172 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000173 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000174 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000175 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000176 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000177 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000178 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000179 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000180 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000181 else if (PyObject_AsCharBuffer(v, &s, &len)) {
182 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000183 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000185 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000186
Guido van Rossum4c08d552000-03-10 22:55:18 +0000187 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 while (*s && isspace(Py_CHARMASK(*s)))
189 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000190 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000192 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000193 }
Christian Heimes99170a52007-12-19 02:07:34 +0000194 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000195 /* We don't care about overflow or underflow. If the platform supports
196 * them, infinities and signed zeroes (on underflow) are fine.
197 * However, strtod can return 0 for denormalized numbers, where atof
198 * does not. So (alas!) we special-case a zero result. Note that
199 * whether strtod sets errno on underflow is not defined, so we can't
200 * key off errno.
201 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000202 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000203 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000204 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000205 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000206 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000207 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 if (end > last)
209 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000210 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000211 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000212 char *p = (char*)sp;
213 int sign = 1;
214
215 if (*p == '-') {
216 sign = -1;
217 p++;
218 }
219 if (*p == '+') {
220 p++;
221 }
222 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000223 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000224 }
225#ifdef Py_NAN
226 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000227 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000228 }
229#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000230 PyOS_snprintf(buffer, sizeof(buffer),
231 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000232 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000233 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000234 }
235 /* Since end != s, the platform made *some* kind of sense out
236 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237 while (*end && isspace(Py_CHARMASK(*end)))
238 end++;
239 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000240 PyOS_snprintf(buffer, sizeof(buffer),
241 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000242 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000243 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000244 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000245 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000246 PyErr_SetString(PyExc_ValueError,
247 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000248 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 }
Tim Petersef14d732000-09-23 03:39:17 +0000250 if (x == 0.0) {
251 /* See above -- may have been strtod being anal
252 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000253 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000254 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000255 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000256 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000257 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000258 result = PyFloat_FromDouble(x);
259 error:
260 if (s_buffer)
261 PyMem_FREE(s_buffer);
262 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000263}
264
Guido van Rossum234f9421993-06-17 12:35:49 +0000265static void
Fred Drakefd99de62000-07-09 05:02:18 +0000266float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000267{
Guido van Rossum9475a232001-10-05 20:51:39 +0000268 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000269 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000270 free_list = op;
271 }
272 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000273 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000274}
275
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276double
Fred Drakefd99de62000-07-09 05:02:18 +0000277PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000278{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 PyNumberMethods *nb;
280 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000281 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000282
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283 if (op && PyFloat_Check(op))
284 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000285
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000286 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288 return -1;
289 }
Tim Petersd2364e82001-11-01 20:09:42 +0000290
Christian Heimes90aa7642007-12-19 02:45:37 +0000291 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000292 PyErr_SetString(PyExc_TypeError, "a float is required");
293 return -1;
294 }
295
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297 if (fo == NULL)
298 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 if (!PyFloat_Check(fo)) {
300 PyErr_SetString(PyExc_TypeError,
301 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000302 return -1;
303 }
Tim Petersd2364e82001-11-01 20:09:42 +0000304
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 val = PyFloat_AS_DOUBLE(fo);
306 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309}
310
311/* Methods */
312
Tim Peters97019e42001-11-28 22:43:45 +0000313static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000314format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
316 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000317 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000318 int i;
319
320 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321 We want float numbers to be recognizable as such,
322 i.e., they should contain a decimal point or an exponent.
323 However, %g may print the number as an integer;
324 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000325
Martin v. Löwis737ea822004-06-08 18:52:54 +0000326 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000327 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328 cp = buf;
329 if (*cp == '-')
330 cp++;
331 for (; *cp != '\0'; cp++) {
332 /* Any non-digit means it's not an integer;
333 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000334 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 break;
336 }
337 if (*cp == '\0') {
338 *cp++ = '.';
339 *cp++ = '0';
340 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000341 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342 }
Christian Heimes99170a52007-12-19 02:07:34 +0000343 /* Checking the next three chars should be more than enough to
344 * detect inf or nan, even on Windows. We check for inf or nan
345 * at last because they are rare cases.
346 */
347 for (i=0; *cp != '\0' && i<3; cp++, i++) {
348 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
349 continue;
350 /* found something that is neither a digit nor point
351 * it might be a NaN or INF
352 */
353#ifdef Py_NAN
354 if (Py_IS_NAN(ob_fval)) {
355 strcpy(buf, "nan");
356 }
357 else
358#endif
359 if (Py_IS_INFINITY(ob_fval)) {
360 cp = buf;
361 if (*cp == '-')
362 cp++;
363 strcpy(cp, "inf");
364 }
365 break;
366 }
367
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Neal Norwitz545686b2006-12-28 04:45:06 +0000370static void
371format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000372{
Neal Norwitz545686b2006-12-28 04:45:06 +0000373 assert(PyFloat_Check(v));
374 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000375}
376
Neil Schemenauer32117e52001-01-04 01:44:34 +0000377/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000378 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000379 set to NULL, and the function invoking this macro returns NULL. If
380 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
381 stored in obj, and returned from the function invoking this macro.
382*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000383#define CONVERT_TO_DOUBLE(obj, dbl) \
384 if (PyFloat_Check(obj)) \
385 dbl = PyFloat_AS_DOUBLE(obj); \
386 else if (convert_to_double(&(obj), &(dbl)) < 0) \
387 return obj;
388
389static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000390convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000391{
392 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000393
Guido van Rossumddefaf32007-01-14 03:31:43 +0000394 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000395 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000396 if (*dbl == -1.0 && PyErr_Occurred()) {
397 *v = NULL;
398 return -1;
399 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000400 }
401 else {
402 Py_INCREF(Py_NotImplemented);
403 *v = Py_NotImplemented;
404 return -1;
405 }
406 return 0;
407}
408
Guido van Rossum57072eb1999-12-23 19:00:28 +0000409/* Precisions used by repr() and str(), respectively.
410
411 The repr() precision (17 significant decimal digits) is the minimal number
412 that is guaranteed to have enough precision so that if the number is read
413 back in the exact same binary value is recreated. This is true for IEEE
414 floating point by design, and also happens to work for all other modern
415 hardware.
416
417 The str() precision is chosen so that in most cases, the rounding noise
418 created by various operations is suppressed, while giving plenty of
419 precision for practical use.
420
421*/
422
423#define PREC_REPR 17
424#define PREC_STR 12
425
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000427float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000428{
Christian Heimesb76922a2007-12-11 01:06:40 +0000429 char buf[100];
430 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesb76922a2007-12-11 01:06:40 +0000431
Walter Dörwald1ab83302007-05-18 17:15:44 +0000432 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000433}
434
435static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000436float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000437{
438 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000439 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000440 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441}
442
Tim Peters307fa782004-09-23 08:06:40 +0000443/* Comparison is pretty much a nightmare. When comparing float to float,
444 * we do it as straightforwardly (and long-windedly) as conceivable, so
445 * that, e.g., Python x == y delivers the same result as the platform
446 * C x == y when x and/or y is a NaN.
447 * When mixing float with an integer type, there's no good *uniform* approach.
448 * Converting the double to an integer obviously doesn't work, since we
449 * may lose info from fractional bits. Converting the integer to a double
450 * also has two failure modes: (1) a long int may trigger overflow (too
451 * large to fit in the dynamic range of a C double); (2) even a C long may have
452 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
453 * 63 bits of precision, but a C double probably has only 53), and then
454 * we can falsely claim equality when low-order integer bits are lost by
455 * coercion to double. So this part is painful too.
456 */
457
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000458static PyObject*
459float_richcompare(PyObject *v, PyObject *w, int op)
460{
461 double i, j;
462 int r = 0;
463
Tim Peters307fa782004-09-23 08:06:40 +0000464 assert(PyFloat_Check(v));
465 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000466
Tim Peters307fa782004-09-23 08:06:40 +0000467 /* Switch on the type of w. Set i and j to doubles to be compared,
468 * and op to the richcomp to use.
469 */
470 if (PyFloat_Check(w))
471 j = PyFloat_AS_DOUBLE(w);
472
Thomas Wouters477c8d52006-05-27 19:21:47 +0000473 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000474 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000475 /* If i is an infinity, its magnitude exceeds any
476 * finite integer, so it doesn't matter which int we
477 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000478 */
479 j = 0.0;
480 else
481 goto Unimplemented;
482 }
483
Tim Peters307fa782004-09-23 08:06:40 +0000484 else if (PyLong_Check(w)) {
485 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
486 int wsign = _PyLong_Sign(w);
487 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000488 int exponent;
489
490 if (vsign != wsign) {
491 /* Magnitudes are irrelevant -- the signs alone
492 * determine the outcome.
493 */
494 i = (double)vsign;
495 j = (double)wsign;
496 goto Compare;
497 }
498 /* The signs are the same. */
499 /* Convert w to a double if it fits. In particular, 0 fits. */
500 nbits = _PyLong_NumBits(w);
501 if (nbits == (size_t)-1 && PyErr_Occurred()) {
502 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000503 * to hold the # of bits. Replace with little doubles
504 * that give the same outcome -- w is so large that
505 * its magnitude must exceed the magnitude of any
506 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000507 */
508 PyErr_Clear();
509 i = (double)vsign;
510 assert(wsign != 0);
511 j = wsign * 2.0;
512 goto Compare;
513 }
514 if (nbits <= 48) {
515 j = PyLong_AsDouble(w);
516 /* It's impossible that <= 48 bits overflowed. */
517 assert(j != -1.0 || ! PyErr_Occurred());
518 goto Compare;
519 }
520 assert(wsign != 0); /* else nbits was 0 */
521 assert(vsign != 0); /* if vsign were 0, then since wsign is
522 * not 0, we would have taken the
523 * vsign != wsign branch at the start */
524 /* We want to work with non-negative numbers. */
525 if (vsign < 0) {
526 /* "Multiply both sides" by -1; this also swaps the
527 * comparator.
528 */
529 i = -i;
530 op = _Py_SwappedOp[op];
531 }
532 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000533 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000534 /* exponent is the # of bits in v before the radix point;
535 * we know that nbits (the # of bits in w) > 48 at this point
536 */
537 if (exponent < 0 || (size_t)exponent < nbits) {
538 i = 1.0;
539 j = 2.0;
540 goto Compare;
541 }
542 if ((size_t)exponent > nbits) {
543 i = 2.0;
544 j = 1.0;
545 goto Compare;
546 }
547 /* v and w have the same number of bits before the radix
548 * point. Construct two longs that have the same comparison
549 * outcome.
550 */
551 {
552 double fracpart;
553 double intpart;
554 PyObject *result = NULL;
555 PyObject *one = NULL;
556 PyObject *vv = NULL;
557 PyObject *ww = w;
558
559 if (wsign < 0) {
560 ww = PyNumber_Negative(w);
561 if (ww == NULL)
562 goto Error;
563 }
564 else
565 Py_INCREF(ww);
566
567 fracpart = modf(i, &intpart);
568 vv = PyLong_FromDouble(intpart);
569 if (vv == NULL)
570 goto Error;
571
572 if (fracpart != 0.0) {
573 /* Shift left, and or a 1 bit into vv
574 * to represent the lost fraction.
575 */
576 PyObject *temp;
577
Christian Heimes217cfd12007-12-02 14:31:20 +0000578 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000579 if (one == NULL)
580 goto Error;
581
582 temp = PyNumber_Lshift(ww, one);
583 if (temp == NULL)
584 goto Error;
585 Py_DECREF(ww);
586 ww = temp;
587
588 temp = PyNumber_Lshift(vv, one);
589 if (temp == NULL)
590 goto Error;
591 Py_DECREF(vv);
592 vv = temp;
593
594 temp = PyNumber_Or(vv, one);
595 if (temp == NULL)
596 goto Error;
597 Py_DECREF(vv);
598 vv = temp;
599 }
600
601 r = PyObject_RichCompareBool(vv, ww, op);
602 if (r < 0)
603 goto Error;
604 result = PyBool_FromLong(r);
605 Error:
606 Py_XDECREF(vv);
607 Py_XDECREF(ww);
608 Py_XDECREF(one);
609 return result;
610 }
611 } /* else if (PyLong_Check(w)) */
612
613 else /* w isn't float, int, or long */
614 goto Unimplemented;
615
616 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000617 PyFPE_START_PROTECT("richcompare", return NULL)
618 switch (op) {
619 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000620 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000621 break;
622 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000623 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000624 break;
625 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000626 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000627 break;
628 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000629 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000630 break;
631 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000632 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633 break;
634 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000635 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000636 break;
637 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000638 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000639 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000640
641 Unimplemented:
642 Py_INCREF(Py_NotImplemented);
643 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000644}
645
Guido van Rossum9bfef441993-03-29 10:43:31 +0000646static long
Fred Drakefd99de62000-07-09 05:02:18 +0000647float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000648{
Tim Peters39dce292000-08-15 03:34:48 +0000649 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000650}
651
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000653float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000654{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000655 double a,b;
656 CONVERT_TO_DOUBLE(v, a);
657 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000658 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000659 a = a + b;
660 PyFPE_END_PROTECT(a)
661 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662}
663
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000664static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000665float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000666{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000667 double a,b;
668 CONVERT_TO_DOUBLE(v, a);
669 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000670 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000671 a = a - b;
672 PyFPE_END_PROTECT(a)
673 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674}
675
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000679 double a,b;
680 CONVERT_TO_DOUBLE(v, a);
681 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000682 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000683 a = a * b;
684 PyFPE_END_PROTECT(a)
685 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686}
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000689float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000690{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000691 double a,b;
692 CONVERT_TO_DOUBLE(v, a);
693 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000694#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000695 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000696 PyErr_SetString(PyExc_ZeroDivisionError,
697 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000698 return NULL;
699 }
Christian Heimes53876d92008-04-19 00:31:39 +0000700#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000701 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000702 a = a / b;
703 PyFPE_END_PROTECT(a)
704 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000705}
706
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000707static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000708float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000709{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000710 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000711 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000712 CONVERT_TO_DOUBLE(v, vx);
713 CONVERT_TO_DOUBLE(w, wx);
714#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000716 PyErr_SetString(PyExc_ZeroDivisionError,
717 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718 return NULL;
719 }
Christian Heimes53876d92008-04-19 00:31:39 +0000720#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000721 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000722 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000723 /* note: checking mod*wx < 0 is incorrect -- underflows to
724 0 if wx < sqrt(smallest nonzero double) */
725 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000726 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000727 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000728 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730}
731
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000733float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000734{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000735 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000736 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000737 CONVERT_TO_DOUBLE(v, vx);
738 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000739 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000741 return NULL;
742 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000743 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000744 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000745 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000746 exact multiple of wx. But this is fp arithmetic, and fp
747 vx - mod is an approximation; the result is that div may
748 not be an exact integral value after the division, although
749 it will always be very close to one.
750 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000751 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000752 if (mod) {
753 /* ensure the remainder has the same sign as the denominator */
754 if ((wx < 0) != (mod < 0)) {
755 mod += wx;
756 div -= 1.0;
757 }
758 }
759 else {
760 /* the remainder is zero, and in the presence of signed zeroes
761 fmod returns different results across platforms; ensure
762 it has the same sign as the denominator; we'd like to do
763 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000764 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000765 if (wx < 0.0)
766 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000767 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000768 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000769 if (div) {
770 floordiv = floor(div);
771 if (div - floordiv > 0.5)
772 floordiv += 1.0;
773 }
774 else {
775 /* div is zero - get the same sign as the true quotient */
776 div *= div; /* hide "div = +0" from optimizers */
777 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
778 }
779 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000780 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000781}
782
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000784float_floor_div(PyObject *v, PyObject *w)
785{
786 PyObject *t, *r;
787
788 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000789 if (t == NULL || t == Py_NotImplemented)
790 return t;
791 assert(PyTuple_CheckExact(t));
792 r = PyTuple_GET_ITEM(t, 0);
793 Py_INCREF(r);
794 Py_DECREF(t);
795 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000796}
797
798static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000799float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800{
801 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000802
803 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000804 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000805 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000806 return NULL;
807 }
808
Neil Schemenauer32117e52001-01-04 01:44:34 +0000809 CONVERT_TO_DOUBLE(v, iv);
810 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000811
812 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000813 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000814 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000815 }
Tim Peters96685bf2001-08-23 22:31:37 +0000816 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000817 if (iw < 0.0) {
818 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000819 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000820 return NULL;
821 }
822 return PyFloat_FromDouble(0.0);
823 }
Christian Heimes53876d92008-04-19 00:31:39 +0000824 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
825 return PyFloat_FromDouble(1.0);
826 }
Tim Peterse87568d2003-05-24 20:18:24 +0000827 if (iv < 0.0) {
828 /* Whether this is an error is a mess, and bumps into libm
829 * bugs so we have to figure it out ourselves.
830 */
831 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000832 /* Negative numbers raised to fractional powers
833 * become complex.
834 */
835 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000836 }
837 /* iw is an exact integer, albeit perhaps a very large one.
838 * -1 raised to an exact integer should never be exceptional.
839 * Alas, some libms (chiefly glibc as of early 2003) return
840 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
841 * happen to be representable in a *C* integer. That's a
842 * bug; we let that slide in math.pow() (which currently
843 * reflects all platform accidents), but not for Python's **.
844 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000846 /* Return 1 if iw is even, -1 if iw is odd; there's
847 * no guarantee that any C integral type is big
848 * enough to hold iw, so we have to check this
849 * indirectly.
850 */
851 ix = floor(iw * 0.5) * 2.0;
852 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
853 }
854 /* Else iv != -1.0, and overflow or underflow are possible.
855 * Unless we're to write pow() ourselves, we have to trust
856 * the platform to do this correctly.
857 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000858 }
Tim Peters96685bf2001-08-23 22:31:37 +0000859 errno = 0;
860 PyFPE_START_PROTECT("pow", return NULL)
861 ix = pow(iv, iw);
862 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000863 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000864 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000865 /* We don't expect any errno value other than ERANGE, but
866 * the range of libm bugs appears unbounded.
867 */
868 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
869 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000870 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000871 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000873}
874
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000875static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000876float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000878 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879}
880
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000882float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000883{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000884 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000885}
886
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000887static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000888float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000889{
890 return v->ob_fval != 0.0;
891}
892
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000893static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000894float_is_integer(PyObject *v)
895{
896 double x = PyFloat_AsDouble(v);
897 PyObject *o;
898
899 if (x == -1.0 && PyErr_Occurred())
900 return NULL;
901 if (!Py_IS_FINITE(x))
902 Py_RETURN_FALSE;
903 PyFPE_START_PROTECT("is_integer", return NULL)
904 o = (floor(x) == x) ? Py_True : Py_False;
905 PyFPE_END_PROTECT(x)
906 if (errno != 0) {
907 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
908 PyExc_ValueError);
909 return NULL;
910 }
911 Py_INCREF(o);
912 return o;
913}
914
915#if 0
916static PyObject *
917float_is_inf(PyObject *v)
918{
919 double x = PyFloat_AsDouble(v);
920 if (x == -1.0 && PyErr_Occurred())
921 return NULL;
922 return PyBool_FromLong((long)Py_IS_INFINITY(x));
923}
924
925static PyObject *
926float_is_nan(PyObject *v)
927{
928 double x = PyFloat_AsDouble(v);
929 if (x == -1.0 && PyErr_Occurred())
930 return NULL;
931 return PyBool_FromLong((long)Py_IS_NAN(x));
932}
933
934static PyObject *
935float_is_finite(PyObject *v)
936{
937 double x = PyFloat_AsDouble(v);
938 if (x == -1.0 && PyErr_Occurred())
939 return NULL;
940 return PyBool_FromLong((long)Py_IS_FINITE(x));
941}
942#endif
943
944static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000945float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000946{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000947 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000948 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000949
950 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000951 /* Try to get out cheap if this fits in a Python int. The attempt
952 * to cast to long must be protected, as C doesn't define what
953 * happens if the double is too big to fit in a long. Some rare
954 * systems raise an exception then (RISCOS was mentioned as one,
955 * and someone using a non-default option on Sun also bumped into
956 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
957 * still be vulnerable: if a long has more bits of precision than
958 * a double, casting MIN/MAX to double may yield an approximation,
959 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
960 * yield true from the C expression wholepart<=LONG_MAX, despite
961 * that wholepart is actually greater than LONG_MAX.
962 */
963 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
964 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000965 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000966 }
967 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000968}
969
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000970static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000971float_round(PyObject *v, PyObject *args)
972{
973#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
974 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000975 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000976 double flr, cil;
977 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000978 int ndigits = UNDEF_NDIGITS;
979
980 if (!PyArg_ParseTuple(args, "|i", &ndigits))
981 return NULL;
982
983 x = PyFloat_AsDouble(v);
984
985 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000986 f = pow(10.0, ndigits);
987 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000988 }
989
990 flr = floor(x);
991 cil = ceil(x);
992
993 if (x-flr > 0.5)
994 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000995 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000996 rounded = fmod(flr, 2) == 0 ? flr : cil;
997 else
998 rounded = flr;
999
1000 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001001 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001002 return PyFloat_FromDouble(rounded);
1003 }
1004
1005 return PyLong_FromDouble(rounded);
1006#undef UNDEF_NDIGITS
1007}
1008
1009static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001010float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001011{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001012 if (PyFloat_CheckExact(v))
1013 Py_INCREF(v);
1014 else
1015 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001016 return v;
1017}
1018
Christian Heimes26855632008-01-27 23:50:43 +00001019static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001020float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001021{
1022 double self;
1023 double float_part;
1024 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001025 int i;
1026
Christian Heimes26855632008-01-27 23:50:43 +00001027 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001028 PyObject *py_exponent = NULL;
1029 PyObject *numerator = NULL;
1030 PyObject *denominator = NULL;
1031 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001032 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001033
1034#define INPLACE_UPDATE(obj, call) \
1035 prev = obj; \
1036 obj = call; \
1037 Py_DECREF(prev); \
1038
1039 CONVERT_TO_DOUBLE(v, self);
1040
1041 if (Py_IS_INFINITY(self)) {
1042 PyErr_SetString(PyExc_OverflowError,
1043 "Cannot pass infinity to float.as_integer_ratio.");
1044 return NULL;
1045 }
1046#ifdef Py_NAN
1047 if (Py_IS_NAN(self)) {
1048 PyErr_SetString(PyExc_ValueError,
1049 "Cannot pass nan to float.as_integer_ratio.");
1050 return NULL;
1051 }
1052#endif
1053
Christian Heimes26855632008-01-27 23:50:43 +00001054 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001055 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001056 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001057
1058 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1059 float_part *= 2.0;
1060 exponent--;
1061 }
1062 /* self == float_part * 2**exponent exactly and float_part is integral.
1063 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1064 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001065
Christian Heimes292d3512008-02-03 16:51:08 +00001066 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001067 if (numerator == NULL) goto error;
1068
Christian Heimes292d3512008-02-03 16:51:08 +00001069 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001070 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001071 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001072 if (py_exponent == NULL) goto error;
1073 INPLACE_UPDATE(py_exponent,
1074 long_methods->nb_lshift(denominator, py_exponent));
1075 if (py_exponent == NULL) goto error;
1076 if (exponent > 0) {
1077 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001078 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001079 if (numerator == NULL) goto error;
1080 }
1081 else {
1082 Py_DECREF(denominator);
1083 denominator = py_exponent;
1084 py_exponent = NULL;
1085 }
1086
Christian Heimes292d3512008-02-03 16:51:08 +00001087 /* Returns ints instead of longs where possible */
1088 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1089 if (numerator == NULL) goto error;
1090 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1091 if (denominator == NULL) goto error;
1092
Christian Heimes26855632008-01-27 23:50:43 +00001093 result_pair = PyTuple_Pack(2, numerator, denominator);
1094
1095#undef INPLACE_UPDATE
1096error:
1097 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001098 Py_XDECREF(denominator);
1099 Py_XDECREF(numerator);
1100 return result_pair;
1101}
1102
1103PyDoc_STRVAR(float_as_integer_ratio_doc,
1104"float.as_integer_ratio() -> (int, int)\n"
1105"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001106"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1107"float and with a positive denominator.\n"
1108"Raises OverflowError on infinities and a ValueError on nans.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001109"\n"
1110">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001111"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001112">>> (0.0).as_integer_ratio()\n"
1113"(0, 1)\n"
1114">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001115"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001116
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001117
Jeremy Hylton938ace62002-07-17 16:30:39 +00001118static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001119float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1120
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121static PyObject *
1122float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1123{
1124 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001125 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126
Guido van Rossumbef14172001-08-29 15:47:46 +00001127 if (type != &PyFloat_Type)
1128 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1130 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001131 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001132 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133 return PyNumber_Float(x);
1134}
1135
Guido van Rossumbef14172001-08-29 15:47:46 +00001136/* Wimpy, slow approach to tp_new calls for subtypes of float:
1137 first create a regular float from whatever arguments we got,
1138 then allocate a subtype instance and initialize its ob_fval
1139 from the regular float. The regular float is then thrown away.
1140*/
1141static PyObject *
1142float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1143{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001144 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001145
1146 assert(PyType_IsSubtype(type, &PyFloat_Type));
1147 tmp = float_new(&PyFloat_Type, args, kwds);
1148 if (tmp == NULL)
1149 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001150 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151 newobj = type->tp_alloc(type, 0);
1152 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001153 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001154 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001155 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001156 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001157 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001158 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001159}
1160
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001161static PyObject *
1162float_getnewargs(PyFloatObject *v)
1163{
1164 return Py_BuildValue("(d)", v->ob_fval);
1165}
1166
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001167/* this is for the benefit of the pack/unpack routines below */
1168
1169typedef enum {
1170 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1171} float_format_type;
1172
1173static float_format_type double_format, float_format;
1174static float_format_type detected_double_format, detected_float_format;
1175
1176static PyObject *
1177float_getformat(PyTypeObject *v, PyObject* arg)
1178{
1179 char* s;
1180 float_format_type r;
1181
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001182 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001183 PyErr_Format(PyExc_TypeError,
1184 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001185 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001186 return NULL;
1187 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001188 s = PyUnicode_AsString(arg);
1189 if (s == NULL)
1190 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001191 if (strcmp(s, "double") == 0) {
1192 r = double_format;
1193 }
1194 else if (strcmp(s, "float") == 0) {
1195 r = float_format;
1196 }
1197 else {
1198 PyErr_SetString(PyExc_ValueError,
1199 "__getformat__() argument 1 must be "
1200 "'double' or 'float'");
1201 return NULL;
1202 }
1203
1204 switch (r) {
1205 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001206 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001207 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001208 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001209 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001210 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001211 default:
1212 Py_FatalError("insane float_format or double_format");
1213 return NULL;
1214 }
1215}
1216
1217PyDoc_STRVAR(float_getformat_doc,
1218"float.__getformat__(typestr) -> string\n"
1219"\n"
1220"You probably don't want to use this function. It exists mainly to be\n"
1221"used in Python's test suite.\n"
1222"\n"
1223"typestr must be 'double' or 'float'. This function returns whichever of\n"
1224"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1225"format of floating point numbers used by the C type named by typestr.");
1226
1227static PyObject *
1228float_setformat(PyTypeObject *v, PyObject* args)
1229{
1230 char* typestr;
1231 char* format;
1232 float_format_type f;
1233 float_format_type detected;
1234 float_format_type *p;
1235
1236 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1237 return NULL;
1238
1239 if (strcmp(typestr, "double") == 0) {
1240 p = &double_format;
1241 detected = detected_double_format;
1242 }
1243 else if (strcmp(typestr, "float") == 0) {
1244 p = &float_format;
1245 detected = detected_float_format;
1246 }
1247 else {
1248 PyErr_SetString(PyExc_ValueError,
1249 "__setformat__() argument 1 must "
1250 "be 'double' or 'float'");
1251 return NULL;
1252 }
1253
1254 if (strcmp(format, "unknown") == 0) {
1255 f = unknown_format;
1256 }
1257 else if (strcmp(format, "IEEE, little-endian") == 0) {
1258 f = ieee_little_endian_format;
1259 }
1260 else if (strcmp(format, "IEEE, big-endian") == 0) {
1261 f = ieee_big_endian_format;
1262 }
1263 else {
1264 PyErr_SetString(PyExc_ValueError,
1265 "__setformat__() argument 2 must be "
1266 "'unknown', 'IEEE, little-endian' or "
1267 "'IEEE, big-endian'");
1268 return NULL;
1269
1270 }
1271
1272 if (f != unknown_format && f != detected) {
1273 PyErr_Format(PyExc_ValueError,
1274 "can only set %s format to 'unknown' or the "
1275 "detected platform value", typestr);
1276 return NULL;
1277 }
1278
1279 *p = f;
1280 Py_RETURN_NONE;
1281}
1282
1283PyDoc_STRVAR(float_setformat_doc,
1284"float.__setformat__(typestr, fmt) -> None\n"
1285"\n"
1286"You probably don't want to use this function. It exists mainly to be\n"
1287"used in Python's test suite.\n"
1288"\n"
1289"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1290"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1291"one of the latter two if it appears to match the underlying C reality.\n"
1292"\n"
1293"Overrides the automatic determination of C-level floating point type.\n"
1294"This affects how floats are converted to and from binary strings.");
1295
Guido van Rossumb43daf72007-08-01 18:08:08 +00001296static PyObject *
1297float_getzero(PyObject *v, void *closure)
1298{
1299 return PyFloat_FromDouble(0.0);
1300}
1301
Eric Smith8c663262007-08-25 02:26:07 +00001302static PyObject *
1303float__format__(PyObject *self, PyObject *args)
1304{
1305 /* when back porting this to 2.6, check type of the format_spec
1306 and call either unicode_long__format__ or
1307 string_long__format__ */
1308 return unicode_float__format__(self, args);
1309}
1310
1311PyDoc_STRVAR(float__format__doc,
1312"float.__format__(format_spec) -> string\n"
1313"\n"
1314"Formats the float according to format_spec.");
1315
1316
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001317static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001318 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001319 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001320 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1321 "Returns the Integral closest to x between 0 and x."},
1322 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1323 "Returns the Integral closest to x, rounding half toward even.\n"
1324 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001325 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1326 float_as_integer_ratio_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001327 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1328 "Returns True if the float is an integer."},
1329#if 0
1330 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1331 "Returns True if the float is positive or negative infinite."},
1332 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1333 "Returns True if the float is finite, neither infinite nor NaN."},
1334 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1335 "Returns True if the float is not a number (NaN)."},
1336#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001337 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001338 {"__getformat__", (PyCFunction)float_getformat,
1339 METH_O|METH_CLASS, float_getformat_doc},
1340 {"__setformat__", (PyCFunction)float_setformat,
1341 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001342 {"__format__", (PyCFunction)float__format__,
1343 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001344 {NULL, NULL} /* sentinel */
1345};
1346
Guido van Rossumb43daf72007-08-01 18:08:08 +00001347static PyGetSetDef float_getset[] = {
1348 {"real",
1349 (getter)float_float, (setter)NULL,
1350 "the real part of a complex number",
1351 NULL},
1352 {"imag",
1353 (getter)float_getzero, (setter)NULL,
1354 "the imaginary part of a complex number",
1355 NULL},
1356 {NULL} /* Sentinel */
1357};
1358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001359PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360"float(x) -> floating point number\n\
1361\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001362Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363
1364
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001366 float_add, /*nb_add*/
1367 float_sub, /*nb_subtract*/
1368 float_mul, /*nb_multiply*/
1369 float_rem, /*nb_remainder*/
1370 float_divmod, /*nb_divmod*/
1371 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001372 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001373 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001374 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001375 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001376 0, /*nb_invert*/
1377 0, /*nb_lshift*/
1378 0, /*nb_rshift*/
1379 0, /*nb_and*/
1380 0, /*nb_xor*/
1381 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001382 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001383 float_trunc, /*nb_int*/
1384 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001385 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001386 0, /* nb_oct */
1387 0, /* nb_hex */
1388 0, /* nb_inplace_add */
1389 0, /* nb_inplace_subtract */
1390 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001391 0, /* nb_inplace_remainder */
1392 0, /* nb_inplace_power */
1393 0, /* nb_inplace_lshift */
1394 0, /* nb_inplace_rshift */
1395 0, /* nb_inplace_and */
1396 0, /* nb_inplace_xor */
1397 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001398 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001399 float_div, /* nb_true_divide */
1400 0, /* nb_inplace_floor_divide */
1401 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001402};
1403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001404PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001406 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001407 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001408 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001410 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411 0, /* tp_getattr */
1412 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001413 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 (reprfunc)float_repr, /* tp_repr */
1415 &float_as_number, /* tp_as_number */
1416 0, /* tp_as_sequence */
1417 0, /* tp_as_mapping */
1418 (hashfunc)float_hash, /* tp_hash */
1419 0, /* tp_call */
1420 (reprfunc)float_str, /* tp_str */
1421 PyObject_GenericGetAttr, /* tp_getattro */
1422 0, /* tp_setattro */
1423 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 float_doc, /* tp_doc */
1426 0, /* tp_traverse */
1427 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001428 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429 0, /* tp_weaklistoffset */
1430 0, /* tp_iter */
1431 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001432 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001434 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435 0, /* tp_base */
1436 0, /* tp_dict */
1437 0, /* tp_descr_get */
1438 0, /* tp_descr_set */
1439 0, /* tp_dictoffset */
1440 0, /* tp_init */
1441 0, /* tp_alloc */
1442 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001443};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001444
1445void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001446_PyFloat_Init(void)
1447{
1448 /* We attempt to determine if this machine is using IEEE
1449 floating point formats by peering at the bits of some
1450 carefully chosen values. If it looks like we are on an
1451 IEEE platform, the float packing/unpacking routines can
1452 just copy bits, if not they resort to arithmetic & shifts
1453 and masks. The shifts & masks approach works on all finite
1454 values, but what happens to infinities, NaNs and signed
1455 zeroes on packing is an accident, and attempting to unpack
1456 a NaN or an infinity will raise an exception.
1457
1458 Note that if we're on some whacked-out platform which uses
1459 IEEE formats but isn't strictly little-endian or big-
1460 endian, we will fall back to the portable shifts & masks
1461 method. */
1462
1463#if SIZEOF_DOUBLE == 8
1464 {
1465 double x = 9006104071832581.0;
1466 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1467 detected_double_format = ieee_big_endian_format;
1468 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1469 detected_double_format = ieee_little_endian_format;
1470 else
1471 detected_double_format = unknown_format;
1472 }
1473#else
1474 detected_double_format = unknown_format;
1475#endif
1476
1477#if SIZEOF_FLOAT == 4
1478 {
1479 float y = 16711938.0;
1480 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1481 detected_float_format = ieee_big_endian_format;
1482 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1483 detected_float_format = ieee_little_endian_format;
1484 else
1485 detected_float_format = unknown_format;
1486 }
1487#else
1488 detected_float_format = unknown_format;
1489#endif
1490
1491 double_format = detected_double_format;
1492 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001493
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001494 /* Init float info */
1495 if (FloatInfoType.tp_name == 0)
1496 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001497}
1498
1499void
Christian Heimes15ebc882008-02-04 18:48:49 +00001500PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001501{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001502 PyFloatObject *p;
1503 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001504 unsigned i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001505 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1506 size_t fsum = 0; /* total unfreed ints */
1507 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001508
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001509 list = block_list;
1510 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001511 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001512 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001513 bc++;
1514 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001515 for (i = 0, p = &list->objects[0];
1516 i < N_FLOATOBJECTS;
1517 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001518 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001519 frem++;
1520 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001521 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001522 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001523 list->next = block_list;
1524 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001525 for (i = 0, p = &list->objects[0];
1526 i < N_FLOATOBJECTS;
1527 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001528 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001529 Py_REFCNT(p) == 0) {
1530 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001531 free_list;
1532 free_list = p;
1533 }
1534 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001535 }
1536 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001537 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001538 bf++;
1539 }
1540 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001541 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001542 }
Christian Heimes15ebc882008-02-04 18:48:49 +00001543 *pbc = bc;
1544 *pbf = bf;
1545 *bsum = fsum;
1546}
1547
1548void
1549PyFloat_Fini(void)
1550{
1551 PyFloatObject *p;
1552 PyFloatBlock *list;
1553 unsigned i;
1554 size_t bc, bf; /* block count, number of freed blocks */
1555 size_t fsum; /* total unfreed floats per block */
1556
1557 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1558
Guido van Rossum3fce8831999-03-12 19:43:17 +00001559 if (!Py_VerboseFlag)
1560 return;
1561 fprintf(stderr, "# cleanup floats");
1562 if (!fsum) {
1563 fprintf(stderr, "\n");
1564 }
1565 else {
1566 fprintf(stderr,
Christian Heimesba4af492008-03-28 00:55:15 +00001567 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes15ebc882008-02-04 18:48:49 +00001568 PY_FORMAT_SIZE_T "d out of %"
1569 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001570 fsum, fsum == 1 ? "" : "s",
1571 bc - bf, bc, bc == 1 ? "" : "s");
1572 }
1573 if (Py_VerboseFlag > 1) {
1574 list = block_list;
1575 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001576 for (i = 0, p = &list->objects[0];
1577 i < N_FLOATOBJECTS;
1578 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001579 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001580 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001581 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001582 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001583 /* XXX(twouters) cast refcount to
1584 long until %zd is universally
1585 available
1586 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001587 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001588 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001589 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001590 }
1591 }
1592 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001593 }
1594 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001595}
Tim Peters9905b942003-03-20 20:53:32 +00001596
1597/*----------------------------------------------------------------------------
1598 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001599 */
1600int
1601_PyFloat_Pack4(double x, unsigned char *p, int le)
1602{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001603 if (float_format == unknown_format) {
1604 unsigned char sign;
1605 int e;
1606 double f;
1607 unsigned int fbits;
1608 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001609
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001610 if (le) {
1611 p += 3;
1612 incr = -1;
1613 }
Tim Peters9905b942003-03-20 20:53:32 +00001614
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615 if (x < 0) {
1616 sign = 1;
1617 x = -x;
1618 }
1619 else
1620 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001621
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001622 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001623
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001624 /* Normalize f to be in the range [1.0, 2.0) */
1625 if (0.5 <= f && f < 1.0) {
1626 f *= 2.0;
1627 e--;
1628 }
1629 else if (f == 0.0)
1630 e = 0;
1631 else {
1632 PyErr_SetString(PyExc_SystemError,
1633 "frexp() result out of range");
1634 return -1;
1635 }
1636
1637 if (e >= 128)
1638 goto Overflow;
1639 else if (e < -126) {
1640 /* Gradual underflow */
1641 f = ldexp(f, 126 + e);
1642 e = 0;
1643 }
1644 else if (!(e == 0 && f == 0.0)) {
1645 e += 127;
1646 f -= 1.0; /* Get rid of leading 1 */
1647 }
1648
1649 f *= 8388608.0; /* 2**23 */
1650 fbits = (unsigned int)(f + 0.5); /* Round */
1651 assert(fbits <= 8388608);
1652 if (fbits >> 23) {
1653 /* The carry propagated out of a string of 23 1 bits. */
1654 fbits = 0;
1655 ++e;
1656 if (e >= 255)
1657 goto Overflow;
1658 }
1659
1660 /* First byte */
1661 *p = (sign << 7) | (e >> 1);
1662 p += incr;
1663
1664 /* Second byte */
1665 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1666 p += incr;
1667
1668 /* Third byte */
1669 *p = (fbits >> 8) & 0xFF;
1670 p += incr;
1671
1672 /* Fourth byte */
1673 *p = fbits & 0xFF;
1674
1675 /* Done */
1676 return 0;
1677
Tim Peters9905b942003-03-20 20:53:32 +00001678 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001679 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001680 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001681 const char *s = (char*)&y;
1682 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001683
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001684 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1685 goto Overflow;
1686
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 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001692
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001693 for (i = 0; i < 4; i++) {
1694 *p = *s++;
1695 p += incr;
1696 }
1697 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001698 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001699 Overflow:
1700 PyErr_SetString(PyExc_OverflowError,
1701 "float too large to pack with f format");
1702 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001703}
1704
1705int
1706_PyFloat_Pack8(double x, unsigned char *p, int le)
1707{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001708 if (double_format == unknown_format) {
1709 unsigned char sign;
1710 int e;
1711 double f;
1712 unsigned int fhi, flo;
1713 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001714
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001715 if (le) {
1716 p += 7;
1717 incr = -1;
1718 }
Tim Peters9905b942003-03-20 20:53:32 +00001719
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001720 if (x < 0) {
1721 sign = 1;
1722 x = -x;
1723 }
1724 else
1725 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001726
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001727 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001728
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001729 /* Normalize f to be in the range [1.0, 2.0) */
1730 if (0.5 <= f && f < 1.0) {
1731 f *= 2.0;
1732 e--;
1733 }
1734 else if (f == 0.0)
1735 e = 0;
1736 else {
1737 PyErr_SetString(PyExc_SystemError,
1738 "frexp() result out of range");
1739 return -1;
1740 }
1741
1742 if (e >= 1024)
1743 goto Overflow;
1744 else if (e < -1022) {
1745 /* Gradual underflow */
1746 f = ldexp(f, 1022 + e);
1747 e = 0;
1748 }
1749 else if (!(e == 0 && f == 0.0)) {
1750 e += 1023;
1751 f -= 1.0; /* Get rid of leading 1 */
1752 }
1753
1754 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1755 f *= 268435456.0; /* 2**28 */
1756 fhi = (unsigned int)f; /* Truncate */
1757 assert(fhi < 268435456);
1758
1759 f -= (double)fhi;
1760 f *= 16777216.0; /* 2**24 */
1761 flo = (unsigned int)(f + 0.5); /* Round */
1762 assert(flo <= 16777216);
1763 if (flo >> 24) {
1764 /* The carry propagated out of a string of 24 1 bits. */
1765 flo = 0;
1766 ++fhi;
1767 if (fhi >> 28) {
1768 /* And it also progagated out of the next 28 bits. */
1769 fhi = 0;
1770 ++e;
1771 if (e >= 2047)
1772 goto Overflow;
1773 }
1774 }
1775
1776 /* First byte */
1777 *p = (sign << 7) | (e >> 4);
1778 p += incr;
1779
1780 /* Second byte */
1781 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1782 p += incr;
1783
1784 /* Third byte */
1785 *p = (fhi >> 16) & 0xFF;
1786 p += incr;
1787
1788 /* Fourth byte */
1789 *p = (fhi >> 8) & 0xFF;
1790 p += incr;
1791
1792 /* Fifth byte */
1793 *p = fhi & 0xFF;
1794 p += incr;
1795
1796 /* Sixth byte */
1797 *p = (flo >> 16) & 0xFF;
1798 p += incr;
1799
1800 /* Seventh byte */
1801 *p = (flo >> 8) & 0xFF;
1802 p += incr;
1803
1804 /* Eighth byte */
1805 *p = flo & 0xFF;
1806 p += incr;
1807
1808 /* Done */
1809 return 0;
1810
1811 Overflow:
1812 PyErr_SetString(PyExc_OverflowError,
1813 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001814 return -1;
1815 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001816 else {
1817 const char *s = (char*)&x;
1818 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001819
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001820 if ((double_format == ieee_little_endian_format && !le)
1821 || (double_format == ieee_big_endian_format && le)) {
1822 p += 7;
1823 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001824 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001825
1826 for (i = 0; i < 8; i++) {
1827 *p = *s++;
1828 p += incr;
1829 }
1830 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001831 }
Tim Peters9905b942003-03-20 20:53:32 +00001832}
1833
Neal Norwitz545686b2006-12-28 04:45:06 +00001834/* Should only be used by marshal. */
1835int
1836_PyFloat_Repr(double x, char *p, size_t len)
1837{
1838 format_double(p, len, x, PREC_REPR);
1839 return (int)strlen(p);
1840}
1841
Tim Peters9905b942003-03-20 20:53:32 +00001842double
1843_PyFloat_Unpack4(const unsigned char *p, int le)
1844{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001845 if (float_format == unknown_format) {
1846 unsigned char sign;
1847 int e;
1848 unsigned int f;
1849 double x;
1850 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001851
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001852 if (le) {
1853 p += 3;
1854 incr = -1;
1855 }
1856
1857 /* First byte */
1858 sign = (*p >> 7) & 1;
1859 e = (*p & 0x7F) << 1;
1860 p += incr;
1861
1862 /* Second byte */
1863 e |= (*p >> 7) & 1;
1864 f = (*p & 0x7F) << 16;
1865 p += incr;
1866
1867 if (e == 255) {
1868 PyErr_SetString(
1869 PyExc_ValueError,
1870 "can't unpack IEEE 754 special value "
1871 "on non-IEEE platform");
1872 return -1;
1873 }
1874
1875 /* Third byte */
1876 f |= *p << 8;
1877 p += incr;
1878
1879 /* Fourth byte */
1880 f |= *p;
1881
1882 x = (double)f / 8388608.0;
1883
1884 /* XXX This sadly ignores Inf/NaN issues */
1885 if (e == 0)
1886 e = -126;
1887 else {
1888 x += 1.0;
1889 e -= 127;
1890 }
1891 x = ldexp(x, e);
1892
1893 if (sign)
1894 x = -x;
1895
1896 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001897 }
Tim Peters9905b942003-03-20 20:53:32 +00001898 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001899 float x;
1900
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001901 if ((float_format == ieee_little_endian_format && !le)
1902 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001903 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001904 char *d = &buf[3];
1905 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001906
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907 for (i = 0; i < 4; i++) {
1908 *d-- = *p++;
1909 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001910 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001911 }
1912 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001913 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001914 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001915
1916 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001917 }
Tim Peters9905b942003-03-20 20:53:32 +00001918}
1919
1920double
1921_PyFloat_Unpack8(const unsigned char *p, int le)
1922{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001923 if (double_format == unknown_format) {
1924 unsigned char sign;
1925 int e;
1926 unsigned int fhi, flo;
1927 double x;
1928 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001929
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930 if (le) {
1931 p += 7;
1932 incr = -1;
1933 }
1934
1935 /* First byte */
1936 sign = (*p >> 7) & 1;
1937 e = (*p & 0x7F) << 4;
1938
1939 p += incr;
1940
1941 /* Second byte */
1942 e |= (*p >> 4) & 0xF;
1943 fhi = (*p & 0xF) << 24;
1944 p += incr;
1945
1946 if (e == 2047) {
1947 PyErr_SetString(
1948 PyExc_ValueError,
1949 "can't unpack IEEE 754 special value "
1950 "on non-IEEE platform");
1951 return -1.0;
1952 }
1953
1954 /* Third byte */
1955 fhi |= *p << 16;
1956 p += incr;
1957
1958 /* Fourth byte */
1959 fhi |= *p << 8;
1960 p += incr;
1961
1962 /* Fifth byte */
1963 fhi |= *p;
1964 p += incr;
1965
1966 /* Sixth byte */
1967 flo = *p << 16;
1968 p += incr;
1969
1970 /* Seventh byte */
1971 flo |= *p << 8;
1972 p += incr;
1973
1974 /* Eighth byte */
1975 flo |= *p;
1976
1977 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1978 x /= 268435456.0; /* 2**28 */
1979
1980 if (e == 0)
1981 e = -1022;
1982 else {
1983 x += 1.0;
1984 e -= 1023;
1985 }
1986 x = ldexp(x, e);
1987
1988 if (sign)
1989 x = -x;
1990
1991 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001992 }
Tim Peters9905b942003-03-20 20:53:32 +00001993 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001994 double x;
1995
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001996 if ((double_format == ieee_little_endian_format && !le)
1997 || (double_format == ieee_big_endian_format && le)) {
1998 char buf[8];
1999 char *d = &buf[7];
2000 int i;
2001
2002 for (i = 0; i < 8; i++) {
2003 *d-- = *p++;
2004 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002005 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002006 }
2007 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002008 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002010
2011 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002012 }
Tim Peters9905b942003-03-20 20:53:32 +00002013}