blob: 5cb32017b034b6c9da0e159b62b12342f8bfbc9d [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
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) {
223 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
224 }
225#ifdef Py_NAN
226 if(PyOS_strnicmp(p, "nan", 4) == 0) {
227 return PyFloat_FromDouble(Py_NAN);
228 }
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
Christian Heimesb76922a2007-12-11 01:06:40 +0000377#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000378/* The following function is based on Tcl_PrintDouble,
379 * from tclUtil.c.
380 */
381
382#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
383#define is_nan(d) ((d) != (d))
384
385static void
386format_double_repr(char *dst, double value)
387{
388 char *p, c;
389 int exp;
390 int signum;
391 char buffer[30];
392
393 /*
394 * Handle NaN.
395 */
396
397 if (is_nan(value)) {
398 strcpy(dst, "nan");
399 return;
400 }
401
402 /*
403 * Handle infinities.
404 */
405
406 if (is_infinite(value)) {
407 if (value < 0) {
408 strcpy(dst, "-inf");
409 } else {
410 strcpy(dst, "inf");
411 }
412 return;
413 }
414
415 /*
416 * Ordinary (normal and denormal) values.
417 */
418
419 exp = _PyFloat_Digits(buffer, value, &signum)+1;
420 if (signum) {
421 *dst++ = '-';
422 }
423 p = buffer;
424 if (exp < -3 || exp > 17) {
425 /*
426 * E format for numbers < 1e-3 or >= 1e17.
427 */
428
429 *dst++ = *p++;
430 c = *p;
431 if (c != '\0') {
432 *dst++ = '.';
433 while (c != '\0') {
434 *dst++ = c;
435 c = *++p;
436 }
437 }
438 sprintf(dst, "e%+d", exp-1);
439 } else {
440 /*
441 * F format for others.
442 */
443
444 if (exp <= 0) {
445 *dst++ = '0';
446 }
447 c = *p;
448 while (exp-- > 0) {
449 if (c != '\0') {
450 *dst++ = c;
451 c = *++p;
452 } else {
453 *dst++ = '0';
454 }
455 }
456 *dst++ = '.';
457 if (c == '\0') {
458 *dst++ = '0';
459 } else {
460 while (++exp < 0) {
461 *dst++ = '0';
462 }
463 while (c != '\0') {
464 *dst++ = c;
465 c = *++p;
466 }
467 }
468 *dst++ = '\0';
469 }
470}
471
472static void
473format_float_repr(char *buf, PyFloatObject *v)
474{
475 assert(PyFloat_Check(v));
476 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
477}
478
Christian Heimesb76922a2007-12-11 01:06:40 +0000479#endif /* Py_BROKEN_REPR */
480
Neil Schemenauer32117e52001-01-04 01:44:34 +0000481/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000482 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000483 set to NULL, and the function invoking this macro returns NULL. If
484 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
485 stored in obj, and returned from the function invoking this macro.
486*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000487#define CONVERT_TO_DOUBLE(obj, dbl) \
488 if (PyFloat_Check(obj)) \
489 dbl = PyFloat_AS_DOUBLE(obj); \
490 else if (convert_to_double(&(obj), &(dbl)) < 0) \
491 return obj;
492
493static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000494convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000495{
496 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000497
Guido van Rossumddefaf32007-01-14 03:31:43 +0000498 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000499 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000500 if (*dbl == -1.0 && PyErr_Occurred()) {
501 *v = NULL;
502 return -1;
503 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000504 }
505 else {
506 Py_INCREF(Py_NotImplemented);
507 *v = Py_NotImplemented;
508 return -1;
509 }
510 return 0;
511}
512
Guido van Rossum57072eb1999-12-23 19:00:28 +0000513/* Precisions used by repr() and str(), respectively.
514
515 The repr() precision (17 significant decimal digits) is the minimal number
516 that is guaranteed to have enough precision so that if the number is read
517 back in the exact same binary value is recreated. This is true for IEEE
518 floating point by design, and also happens to work for all other modern
519 hardware.
520
521 The str() precision is chosen so that in most cases, the rounding noise
522 created by various operations is suppressed, while giving plenty of
523 precision for practical use.
524
525*/
526
527#define PREC_REPR 17
528#define PREC_STR 12
529
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000531float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532{
Christian Heimesb76922a2007-12-11 01:06:40 +0000533#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000534 char buf[30];
535 format_float_repr(buf, v);
Christian Heimesb76922a2007-12-11 01:06:40 +0000536#else
537 char buf[100];
538 format_float(buf, sizeof(buf), v, PREC_REPR);
539#endif
540
Walter Dörwald1ab83302007-05-18 17:15:44 +0000541 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000542}
543
544static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000545float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000546{
547 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000548 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000549 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550}
551
Tim Peters307fa782004-09-23 08:06:40 +0000552/* Comparison is pretty much a nightmare. When comparing float to float,
553 * we do it as straightforwardly (and long-windedly) as conceivable, so
554 * that, e.g., Python x == y delivers the same result as the platform
555 * C x == y when x and/or y is a NaN.
556 * When mixing float with an integer type, there's no good *uniform* approach.
557 * Converting the double to an integer obviously doesn't work, since we
558 * may lose info from fractional bits. Converting the integer to a double
559 * also has two failure modes: (1) a long int may trigger overflow (too
560 * large to fit in the dynamic range of a C double); (2) even a C long may have
561 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
562 * 63 bits of precision, but a C double probably has only 53), and then
563 * we can falsely claim equality when low-order integer bits are lost by
564 * coercion to double. So this part is painful too.
565 */
566
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000567static PyObject*
568float_richcompare(PyObject *v, PyObject *w, int op)
569{
570 double i, j;
571 int r = 0;
572
Tim Peters307fa782004-09-23 08:06:40 +0000573 assert(PyFloat_Check(v));
574 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000575
Tim Peters307fa782004-09-23 08:06:40 +0000576 /* Switch on the type of w. Set i and j to doubles to be compared,
577 * and op to the richcomp to use.
578 */
579 if (PyFloat_Check(w))
580 j = PyFloat_AS_DOUBLE(w);
581
Thomas Wouters477c8d52006-05-27 19:21:47 +0000582 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000583 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000584 /* If i is an infinity, its magnitude exceeds any
585 * finite integer, so it doesn't matter which int we
586 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000587 */
588 j = 0.0;
589 else
590 goto Unimplemented;
591 }
592
Tim Peters307fa782004-09-23 08:06:40 +0000593 else if (PyLong_Check(w)) {
594 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
595 int wsign = _PyLong_Sign(w);
596 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000597 int exponent;
598
599 if (vsign != wsign) {
600 /* Magnitudes are irrelevant -- the signs alone
601 * determine the outcome.
602 */
603 i = (double)vsign;
604 j = (double)wsign;
605 goto Compare;
606 }
607 /* The signs are the same. */
608 /* Convert w to a double if it fits. In particular, 0 fits. */
609 nbits = _PyLong_NumBits(w);
610 if (nbits == (size_t)-1 && PyErr_Occurred()) {
611 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000612 * to hold the # of bits. Replace with little doubles
613 * that give the same outcome -- w is so large that
614 * its magnitude must exceed the magnitude of any
615 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000616 */
617 PyErr_Clear();
618 i = (double)vsign;
619 assert(wsign != 0);
620 j = wsign * 2.0;
621 goto Compare;
622 }
623 if (nbits <= 48) {
624 j = PyLong_AsDouble(w);
625 /* It's impossible that <= 48 bits overflowed. */
626 assert(j != -1.0 || ! PyErr_Occurred());
627 goto Compare;
628 }
629 assert(wsign != 0); /* else nbits was 0 */
630 assert(vsign != 0); /* if vsign were 0, then since wsign is
631 * not 0, we would have taken the
632 * vsign != wsign branch at the start */
633 /* We want to work with non-negative numbers. */
634 if (vsign < 0) {
635 /* "Multiply both sides" by -1; this also swaps the
636 * comparator.
637 */
638 i = -i;
639 op = _Py_SwappedOp[op];
640 }
641 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000642 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000643 /* exponent is the # of bits in v before the radix point;
644 * we know that nbits (the # of bits in w) > 48 at this point
645 */
646 if (exponent < 0 || (size_t)exponent < nbits) {
647 i = 1.0;
648 j = 2.0;
649 goto Compare;
650 }
651 if ((size_t)exponent > nbits) {
652 i = 2.0;
653 j = 1.0;
654 goto Compare;
655 }
656 /* v and w have the same number of bits before the radix
657 * point. Construct two longs that have the same comparison
658 * outcome.
659 */
660 {
661 double fracpart;
662 double intpart;
663 PyObject *result = NULL;
664 PyObject *one = NULL;
665 PyObject *vv = NULL;
666 PyObject *ww = w;
667
668 if (wsign < 0) {
669 ww = PyNumber_Negative(w);
670 if (ww == NULL)
671 goto Error;
672 }
673 else
674 Py_INCREF(ww);
675
676 fracpart = modf(i, &intpart);
677 vv = PyLong_FromDouble(intpart);
678 if (vv == NULL)
679 goto Error;
680
681 if (fracpart != 0.0) {
682 /* Shift left, and or a 1 bit into vv
683 * to represent the lost fraction.
684 */
685 PyObject *temp;
686
Christian Heimes217cfd12007-12-02 14:31:20 +0000687 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000688 if (one == NULL)
689 goto Error;
690
691 temp = PyNumber_Lshift(ww, one);
692 if (temp == NULL)
693 goto Error;
694 Py_DECREF(ww);
695 ww = temp;
696
697 temp = PyNumber_Lshift(vv, one);
698 if (temp == NULL)
699 goto Error;
700 Py_DECREF(vv);
701 vv = temp;
702
703 temp = PyNumber_Or(vv, one);
704 if (temp == NULL)
705 goto Error;
706 Py_DECREF(vv);
707 vv = temp;
708 }
709
710 r = PyObject_RichCompareBool(vv, ww, op);
711 if (r < 0)
712 goto Error;
713 result = PyBool_FromLong(r);
714 Error:
715 Py_XDECREF(vv);
716 Py_XDECREF(ww);
717 Py_XDECREF(one);
718 return result;
719 }
720 } /* else if (PyLong_Check(w)) */
721
722 else /* w isn't float, int, or long */
723 goto Unimplemented;
724
725 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000726 PyFPE_START_PROTECT("richcompare", return NULL)
727 switch (op) {
728 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000729 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000730 break;
731 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000732 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000733 break;
734 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000735 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000736 break;
737 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000738 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000739 break;
740 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000741 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000742 break;
743 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000744 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000745 break;
746 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000747 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000748 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000749
750 Unimplemented:
751 Py_INCREF(Py_NotImplemented);
752 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000753}
754
Guido van Rossum9bfef441993-03-29 10:43:31 +0000755static long
Fred Drakefd99de62000-07-09 05:02:18 +0000756float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000757{
Tim Peters39dce292000-08-15 03:34:48 +0000758 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000759}
760
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000762float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000764 double a,b;
765 CONVERT_TO_DOUBLE(v, a);
766 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000767 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000768 a = a + b;
769 PyFPE_END_PROTECT(a)
770 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771}
772
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000774float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000776 double a,b;
777 CONVERT_TO_DOUBLE(v, a);
778 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000779 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000780 a = a - b;
781 PyFPE_END_PROTECT(a)
782 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783}
784
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000785static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000786float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000788 double a,b;
789 CONVERT_TO_DOUBLE(v, a);
790 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000791 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000792 a = a * b;
793 PyFPE_END_PROTECT(a)
794 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795}
796
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000798float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000800 double a,b;
801 CONVERT_TO_DOUBLE(v, a);
802 CONVERT_TO_DOUBLE(w, b);
803 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805 return NULL;
806 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000807 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000808 a = a / b;
809 PyFPE_END_PROTECT(a)
810 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811}
812
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000813static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000814float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000816 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000817 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000818 CONVERT_TO_DOUBLE(v, vx);
819 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000821 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822 return NULL;
823 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000824 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000825 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000826 /* note: checking mod*wx < 0 is incorrect -- underflows to
827 0 if wx < sqrt(smallest nonzero double) */
828 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000829 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000830 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000831 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000836float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000837{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000838 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000839 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000840 CONVERT_TO_DOUBLE(v, vx);
841 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000842 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000844 return NULL;
845 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000846 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000847 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000848 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000849 exact multiple of wx. But this is fp arithmetic, and fp
850 vx - mod is an approximation; the result is that div may
851 not be an exact integral value after the division, although
852 it will always be very close to one.
853 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000854 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000855 if (mod) {
856 /* ensure the remainder has the same sign as the denominator */
857 if ((wx < 0) != (mod < 0)) {
858 mod += wx;
859 div -= 1.0;
860 }
861 }
862 else {
863 /* the remainder is zero, and in the presence of signed zeroes
864 fmod returns different results across platforms; ensure
865 it has the same sign as the denominator; we'd like to do
866 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000867 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000868 if (wx < 0.0)
869 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000870 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000871 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000872 if (div) {
873 floordiv = floor(div);
874 if (div - floordiv > 0.5)
875 floordiv += 1.0;
876 }
877 else {
878 /* div is zero - get the same sign as the true quotient */
879 div *= div; /* hide "div = +0" from optimizers */
880 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
881 }
882 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000883 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000884}
885
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000886static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000887float_floor_div(PyObject *v, PyObject *w)
888{
889 PyObject *t, *r;
890
891 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000892 if (t == NULL || t == Py_NotImplemented)
893 return t;
894 assert(PyTuple_CheckExact(t));
895 r = PyTuple_GET_ITEM(t, 0);
896 Py_INCREF(r);
897 Py_DECREF(t);
898 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000899}
900
901static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000902float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000903{
904 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000905
906 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000907 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000908 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000909 return NULL;
910 }
911
Neil Schemenauer32117e52001-01-04 01:44:34 +0000912 CONVERT_TO_DOUBLE(v, iv);
913 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000914
915 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000916 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000917 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000918 }
Tim Peters96685bf2001-08-23 22:31:37 +0000919 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000920 if (iw < 0.0) {
921 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000922 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000923 return NULL;
924 }
925 return PyFloat_FromDouble(0.0);
926 }
Tim Peterse87568d2003-05-24 20:18:24 +0000927 if (iv < 0.0) {
928 /* Whether this is an error is a mess, and bumps into libm
929 * bugs so we have to figure it out ourselves.
930 */
931 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000932 /* Negative numbers raised to fractional powers
933 * become complex.
934 */
935 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000936 }
937 /* iw is an exact integer, albeit perhaps a very large one.
938 * -1 raised to an exact integer should never be exceptional.
939 * Alas, some libms (chiefly glibc as of early 2003) return
940 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
941 * happen to be representable in a *C* integer. That's a
942 * bug; we let that slide in math.pow() (which currently
943 * reflects all platform accidents), but not for Python's **.
944 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000945 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000946 /* Return 1 if iw is even, -1 if iw is odd; there's
947 * no guarantee that any C integral type is big
948 * enough to hold iw, so we have to check this
949 * indirectly.
950 */
951 ix = floor(iw * 0.5) * 2.0;
952 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
953 }
954 /* Else iv != -1.0, and overflow or underflow are possible.
955 * Unless we're to write pow() ourselves, we have to trust
956 * the platform to do this correctly.
957 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000958 }
Tim Peters96685bf2001-08-23 22:31:37 +0000959 errno = 0;
960 PyFPE_START_PROTECT("pow", return NULL)
961 ix = pow(iv, iw);
962 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000963 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000964 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000965 /* We don't expect any errno value other than ERANGE, but
966 * the range of libm bugs appears unbounded.
967 */
968 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
969 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000970 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000971 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000972 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000973}
974
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000976float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000977{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000978 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000979}
980
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000981static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000982float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000983{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000984 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000985}
986
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000987static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000988float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000989{
990 return v->ob_fval != 0.0;
991}
992
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000993static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000994float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000995{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000997 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000998
999 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001000 /* Try to get out cheap if this fits in a Python int. The attempt
1001 * to cast to long must be protected, as C doesn't define what
1002 * happens if the double is too big to fit in a long. Some rare
1003 * systems raise an exception then (RISCOS was mentioned as one,
1004 * and someone using a non-default option on Sun also bumped into
1005 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1006 * still be vulnerable: if a long has more bits of precision than
1007 * a double, casting MIN/MAX to double may yield an approximation,
1008 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1009 * yield true from the C expression wholepart<=LONG_MAX, despite
1010 * that wholepart is actually greater than LONG_MAX.
1011 */
1012 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1013 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +00001014 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001015 }
1016 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001017}
1018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001020float_round(PyObject *v, PyObject *args)
1021{
1022#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1023 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001024 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001025 double flr, cil;
1026 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001027 int ndigits = UNDEF_NDIGITS;
1028
1029 if (!PyArg_ParseTuple(args, "|i", &ndigits))
1030 return NULL;
1031
1032 x = PyFloat_AsDouble(v);
1033
1034 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001035 f = pow(10.0, ndigits);
1036 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001037 }
1038
1039 flr = floor(x);
1040 cil = ceil(x);
1041
1042 if (x-flr > 0.5)
1043 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001044 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001045 rounded = fmod(flr, 2) == 0 ? flr : cil;
1046 else
1047 rounded = flr;
1048
1049 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001050 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001051 return PyFloat_FromDouble(rounded);
1052 }
1053
1054 return PyLong_FromDouble(rounded);
1055#undef UNDEF_NDIGITS
1056}
1057
1058static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001059float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001060{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001061 if (PyFloat_CheckExact(v))
1062 Py_INCREF(v);
1063 else
1064 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001065 return v;
1066}
1067
Christian Heimes26855632008-01-27 23:50:43 +00001068static PyObject *
1069float_as_integer_ratio(PyObject *v)
1070{
1071 double self;
1072 double float_part;
1073 int exponent;
1074 int is_negative;
1075 const int chunk_size = 28;
1076 PyObject *prev;
1077 PyObject *py_chunk = NULL;
1078 PyObject *py_exponent = NULL;
1079 PyObject *numerator = NULL;
1080 PyObject *denominator = NULL;
1081 PyObject *result_pair = NULL;
1082 PyNumberMethods *long_methods;
1083
1084#define INPLACE_UPDATE(obj, call) \
1085 prev = obj; \
1086 obj = call; \
1087 Py_DECREF(prev); \
1088
1089 CONVERT_TO_DOUBLE(v, self);
1090
1091 if (Py_IS_INFINITY(self)) {
1092 PyErr_SetString(PyExc_OverflowError,
1093 "Cannot pass infinity to float.as_integer_ratio.");
1094 return NULL;
1095 }
1096#ifdef Py_NAN
1097 if (Py_IS_NAN(self)) {
1098 PyErr_SetString(PyExc_ValueError,
1099 "Cannot pass nan to float.as_integer_ratio.");
1100 return NULL;
1101 }
1102#endif
1103
1104 if (self == 0) {
1105 numerator = PyLong_FromLong(0);
1106 if (numerator == NULL) goto error;
1107 denominator = PyLong_FromLong(1);
1108 if (denominator == NULL) goto error;
1109 result_pair = PyTuple_Pack(2, numerator, denominator);
1110 /* Hand ownership over to the tuple. If the tuple
1111 wasn't created successfully, we want to delete the
1112 ints anyway. */
1113 Py_DECREF(numerator);
1114 Py_DECREF(denominator);
1115 return result_pair;
1116 }
1117
1118 /* XXX: Could perhaps handle FLT_RADIX!=2 by using ilogb and
1119 scalbn, but those may not be in C89. */
1120 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1121 float_part = frexp(self, &exponent);
1122 is_negative = 0;
1123 if (float_part < 0) {
1124 float_part = -float_part;
1125 is_negative = 1;
1126 /* 0.5 <= float_part < 1.0 */
1127 }
1128 PyFPE_END_PROTECT(float_part);
1129 /* abs(self) == float_part * 2**exponent exactly */
1130
1131 /* Suck up chunk_size bits at a time; 28 is enough so that we
1132 suck up all bits in 2 iterations for all known binary
1133 double-precision formats, and small enough to fit in a
1134 long. */
1135 numerator = PyLong_FromLong(0);
1136 if (numerator == NULL) goto error;
1137
1138 long_methods = PyLong_Type.tp_as_number;
1139
1140 py_chunk = PyLong_FromLong(chunk_size);
1141 if (py_chunk == NULL) goto error;
1142
1143 while (float_part != 0) {
1144 /* invariant: abs(self) ==
1145 (numerator + float_part) * 2**exponent exactly */
1146 long digit;
1147 PyObject *py_digit;
1148
1149 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1150 /* Pull chunk_size bits out of float_part, into digits. */
1151 float_part = ldexp(float_part, chunk_size);
1152 digit = (long)float_part;
1153 float_part -= digit;
1154 /* 0 <= float_part < 1 */
1155 exponent -= chunk_size;
1156 PyFPE_END_PROTECT(float_part);
1157
1158 /* Shift digits into numerator. */
1159 // numerator <<= chunk_size
1160 INPLACE_UPDATE(numerator,
1161 long_methods->nb_lshift(numerator, py_chunk));
1162 if (numerator == NULL) goto error;
1163
1164 // numerator |= digit
1165 py_digit = PyLong_FromLong(digit);
1166 if (py_digit == NULL) goto error;
1167 INPLACE_UPDATE(numerator,
1168 long_methods->nb_or(numerator, py_digit));
1169 Py_DECREF(py_digit);
1170 if (numerator == NULL) goto error;
1171 }
1172
1173 /* Add in the sign bit. */
1174 if (is_negative) {
1175 INPLACE_UPDATE(numerator,
1176 long_methods->nb_negative(numerator));
1177 if (numerator == NULL) goto error;
1178 }
1179
1180 /* now self = numerator * 2**exponent exactly; fold in 2**exponent */
1181 denominator = PyLong_FromLong(1);
1182 py_exponent = PyLong_FromLong(labs(exponent));
1183 if (py_exponent == NULL) goto error;
1184 INPLACE_UPDATE(py_exponent,
1185 long_methods->nb_lshift(denominator, py_exponent));
1186 if (py_exponent == NULL) goto error;
1187 if (exponent > 0) {
1188 INPLACE_UPDATE(numerator,
1189 long_methods->nb_multiply(numerator,
1190 py_exponent));
1191 if (numerator == NULL) goto error;
1192 }
1193 else {
1194 Py_DECREF(denominator);
1195 denominator = py_exponent;
1196 py_exponent = NULL;
1197 }
1198
1199 result_pair = PyTuple_Pack(2, numerator, denominator);
1200
1201#undef INPLACE_UPDATE
1202error:
1203 Py_XDECREF(py_exponent);
1204 Py_XDECREF(py_chunk);
1205 Py_XDECREF(denominator);
1206 Py_XDECREF(numerator);
1207 return result_pair;
1208}
1209
1210PyDoc_STRVAR(float_as_integer_ratio_doc,
1211"float.as_integer_ratio() -> (int, int)\n"
1212"\n"
1213"Returns a pair of integers, not necessarily in lowest terms, whose\n"
1214"ratio is exactly equal to the original float. This method raises an\n"
1215"OverflowError on infinities and a ValueError on nans. The resulting\n"
1216"denominator will be positive.\n"
1217"\n"
1218">>> (10.0).as_integer_ratio()\n"
1219"(167772160L, 16777216L)\n"
1220">>> (0.0).as_integer_ratio()\n"
1221"(0, 1)\n"
1222">>> (-.25).as_integer_ratio()\n"
1223"(-134217728L, 536870912L)");
1224
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001225
Jeremy Hylton938ace62002-07-17 16:30:39 +00001226static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001227float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1228
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229static PyObject *
1230float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1231{
1232 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001233 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234
Guido van Rossumbef14172001-08-29 15:47:46 +00001235 if (type != &PyFloat_Type)
1236 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1238 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001239 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001240 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 return PyNumber_Float(x);
1242}
1243
Guido van Rossumbef14172001-08-29 15:47:46 +00001244/* Wimpy, slow approach to tp_new calls for subtypes of float:
1245 first create a regular float from whatever arguments we got,
1246 then allocate a subtype instance and initialize its ob_fval
1247 from the regular float. The regular float is then thrown away.
1248*/
1249static PyObject *
1250float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1251{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001252 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001253
1254 assert(PyType_IsSubtype(type, &PyFloat_Type));
1255 tmp = float_new(&PyFloat_Type, args, kwds);
1256 if (tmp == NULL)
1257 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001258 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001259 newobj = type->tp_alloc(type, 0);
1260 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001261 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001262 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001263 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001264 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001265 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001266 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001267}
1268
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001269static PyObject *
1270float_getnewargs(PyFloatObject *v)
1271{
1272 return Py_BuildValue("(d)", v->ob_fval);
1273}
1274
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001275/* this is for the benefit of the pack/unpack routines below */
1276
1277typedef enum {
1278 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1279} float_format_type;
1280
1281static float_format_type double_format, float_format;
1282static float_format_type detected_double_format, detected_float_format;
1283
1284static PyObject *
1285float_getformat(PyTypeObject *v, PyObject* arg)
1286{
1287 char* s;
1288 float_format_type r;
1289
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001290 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001291 PyErr_Format(PyExc_TypeError,
1292 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001293 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001294 return NULL;
1295 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001296 s = PyUnicode_AsString(arg);
1297 if (s == NULL)
1298 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001299 if (strcmp(s, "double") == 0) {
1300 r = double_format;
1301 }
1302 else if (strcmp(s, "float") == 0) {
1303 r = float_format;
1304 }
1305 else {
1306 PyErr_SetString(PyExc_ValueError,
1307 "__getformat__() argument 1 must be "
1308 "'double' or 'float'");
1309 return NULL;
1310 }
1311
1312 switch (r) {
1313 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001314 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001315 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001316 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001317 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001318 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001319 default:
1320 Py_FatalError("insane float_format or double_format");
1321 return NULL;
1322 }
1323}
1324
1325PyDoc_STRVAR(float_getformat_doc,
1326"float.__getformat__(typestr) -> string\n"
1327"\n"
1328"You probably don't want to use this function. It exists mainly to be\n"
1329"used in Python's test suite.\n"
1330"\n"
1331"typestr must be 'double' or 'float'. This function returns whichever of\n"
1332"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1333"format of floating point numbers used by the C type named by typestr.");
1334
1335static PyObject *
1336float_setformat(PyTypeObject *v, PyObject* args)
1337{
1338 char* typestr;
1339 char* format;
1340 float_format_type f;
1341 float_format_type detected;
1342 float_format_type *p;
1343
1344 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1345 return NULL;
1346
1347 if (strcmp(typestr, "double") == 0) {
1348 p = &double_format;
1349 detected = detected_double_format;
1350 }
1351 else if (strcmp(typestr, "float") == 0) {
1352 p = &float_format;
1353 detected = detected_float_format;
1354 }
1355 else {
1356 PyErr_SetString(PyExc_ValueError,
1357 "__setformat__() argument 1 must "
1358 "be 'double' or 'float'");
1359 return NULL;
1360 }
1361
1362 if (strcmp(format, "unknown") == 0) {
1363 f = unknown_format;
1364 }
1365 else if (strcmp(format, "IEEE, little-endian") == 0) {
1366 f = ieee_little_endian_format;
1367 }
1368 else if (strcmp(format, "IEEE, big-endian") == 0) {
1369 f = ieee_big_endian_format;
1370 }
1371 else {
1372 PyErr_SetString(PyExc_ValueError,
1373 "__setformat__() argument 2 must be "
1374 "'unknown', 'IEEE, little-endian' or "
1375 "'IEEE, big-endian'");
1376 return NULL;
1377
1378 }
1379
1380 if (f != unknown_format && f != detected) {
1381 PyErr_Format(PyExc_ValueError,
1382 "can only set %s format to 'unknown' or the "
1383 "detected platform value", typestr);
1384 return NULL;
1385 }
1386
1387 *p = f;
1388 Py_RETURN_NONE;
1389}
1390
1391PyDoc_STRVAR(float_setformat_doc,
1392"float.__setformat__(typestr, fmt) -> None\n"
1393"\n"
1394"You probably don't want to use this function. It exists mainly to be\n"
1395"used in Python's test suite.\n"
1396"\n"
1397"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1398"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1399"one of the latter two if it appears to match the underlying C reality.\n"
1400"\n"
1401"Overrides the automatic determination of C-level floating point type.\n"
1402"This affects how floats are converted to and from binary strings.");
1403
Guido van Rossumb43daf72007-08-01 18:08:08 +00001404static PyObject *
1405float_getzero(PyObject *v, void *closure)
1406{
1407 return PyFloat_FromDouble(0.0);
1408}
1409
Eric Smith8c663262007-08-25 02:26:07 +00001410static PyObject *
1411float__format__(PyObject *self, PyObject *args)
1412{
1413 /* when back porting this to 2.6, check type of the format_spec
1414 and call either unicode_long__format__ or
1415 string_long__format__ */
1416 return unicode_float__format__(self, args);
1417}
1418
1419PyDoc_STRVAR(float__format__doc,
1420"float.__format__(format_spec) -> string\n"
1421"\n"
1422"Formats the float according to format_spec.");
1423
1424
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001425static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001426 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1427 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001428 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1429 "Returns the Integral closest to x between 0 and x."},
1430 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1431 "Returns the Integral closest to x, rounding half toward even.\n"
1432 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001433 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1434 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001435 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001436 {"__getformat__", (PyCFunction)float_getformat,
1437 METH_O|METH_CLASS, float_getformat_doc},
1438 {"__setformat__", (PyCFunction)float_setformat,
1439 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001440 {"__format__", (PyCFunction)float__format__,
1441 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001442 {NULL, NULL} /* sentinel */
1443};
1444
Guido van Rossumb43daf72007-08-01 18:08:08 +00001445static PyGetSetDef float_getset[] = {
1446 {"real",
1447 (getter)float_float, (setter)NULL,
1448 "the real part of a complex number",
1449 NULL},
1450 {"imag",
1451 (getter)float_getzero, (setter)NULL,
1452 "the imaginary part of a complex number",
1453 NULL},
1454 {NULL} /* Sentinel */
1455};
1456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458"float(x) -> floating point number\n\
1459\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001460Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461
1462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001463static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001464 float_add, /*nb_add*/
1465 float_sub, /*nb_subtract*/
1466 float_mul, /*nb_multiply*/
1467 float_rem, /*nb_remainder*/
1468 float_divmod, /*nb_divmod*/
1469 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001470 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001471 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001472 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001473 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001474 0, /*nb_invert*/
1475 0, /*nb_lshift*/
1476 0, /*nb_rshift*/
1477 0, /*nb_and*/
1478 0, /*nb_xor*/
1479 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001480 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001481 float_trunc, /*nb_int*/
1482 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001483 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001484 0, /* nb_oct */
1485 0, /* nb_hex */
1486 0, /* nb_inplace_add */
1487 0, /* nb_inplace_subtract */
1488 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001489 0, /* nb_inplace_remainder */
1490 0, /* nb_inplace_power */
1491 0, /* nb_inplace_lshift */
1492 0, /* nb_inplace_rshift */
1493 0, /* nb_inplace_and */
1494 0, /* nb_inplace_xor */
1495 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001496 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001497 float_div, /* nb_true_divide */
1498 0, /* nb_inplace_floor_divide */
1499 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001500};
1501
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001502PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001503 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001504 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001505 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001506 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001508 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509 0, /* tp_getattr */
1510 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001511 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512 (reprfunc)float_repr, /* tp_repr */
1513 &float_as_number, /* tp_as_number */
1514 0, /* tp_as_sequence */
1515 0, /* tp_as_mapping */
1516 (hashfunc)float_hash, /* tp_hash */
1517 0, /* tp_call */
1518 (reprfunc)float_str, /* tp_str */
1519 PyObject_GenericGetAttr, /* tp_getattro */
1520 0, /* tp_setattro */
1521 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001522 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 float_doc, /* tp_doc */
1524 0, /* tp_traverse */
1525 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001526 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 0, /* tp_weaklistoffset */
1528 0, /* tp_iter */
1529 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001530 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001532 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 0, /* tp_base */
1534 0, /* tp_dict */
1535 0, /* tp_descr_get */
1536 0, /* tp_descr_set */
1537 0, /* tp_dictoffset */
1538 0, /* tp_init */
1539 0, /* tp_alloc */
1540 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001541};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001542
1543void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001544_PyFloat_Init(void)
1545{
1546 /* We attempt to determine if this machine is using IEEE
1547 floating point formats by peering at the bits of some
1548 carefully chosen values. If it looks like we are on an
1549 IEEE platform, the float packing/unpacking routines can
1550 just copy bits, if not they resort to arithmetic & shifts
1551 and masks. The shifts & masks approach works on all finite
1552 values, but what happens to infinities, NaNs and signed
1553 zeroes on packing is an accident, and attempting to unpack
1554 a NaN or an infinity will raise an exception.
1555
1556 Note that if we're on some whacked-out platform which uses
1557 IEEE formats but isn't strictly little-endian or big-
1558 endian, we will fall back to the portable shifts & masks
1559 method. */
1560
1561#if SIZEOF_DOUBLE == 8
1562 {
1563 double x = 9006104071832581.0;
1564 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1565 detected_double_format = ieee_big_endian_format;
1566 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1567 detected_double_format = ieee_little_endian_format;
1568 else
1569 detected_double_format = unknown_format;
1570 }
1571#else
1572 detected_double_format = unknown_format;
1573#endif
1574
1575#if SIZEOF_FLOAT == 4
1576 {
1577 float y = 16711938.0;
1578 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1579 detected_float_format = ieee_big_endian_format;
1580 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1581 detected_float_format = ieee_little_endian_format;
1582 else
1583 detected_float_format = unknown_format;
1584 }
1585#else
1586 detected_float_format = unknown_format;
1587#endif
1588
1589 double_format = detected_double_format;
1590 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001591
1592#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001593 /* Initialize floating point repr */
1594 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001595#endif
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001596 /* Init float info */
1597 if (FloatInfoType.tp_name == 0)
1598 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001599}
1600
1601void
Fred Drakefd99de62000-07-09 05:02:18 +00001602PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001603{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001604 PyFloatObject *p;
1605 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001606 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001607 int bc, bf; /* block count, number of freed blocks */
1608 int frem, fsum; /* remaining unfreed floats per block, total */
1609
1610 bc = 0;
1611 bf = 0;
1612 fsum = 0;
1613 list = block_list;
1614 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001615 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001616 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001617 bc++;
1618 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001619 for (i = 0, p = &list->objects[0];
1620 i < N_FLOATOBJECTS;
1621 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001622 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001623 frem++;
1624 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001625 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001626 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001627 list->next = block_list;
1628 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001629 for (i = 0, p = &list->objects[0];
1630 i < N_FLOATOBJECTS;
1631 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001632 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001633 Py_REFCNT(p) == 0) {
1634 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001635 free_list;
1636 free_list = p;
1637 }
1638 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001639 }
1640 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001641 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001642 bf++;
1643 }
1644 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001645 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001646 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001647 if (!Py_VerboseFlag)
1648 return;
1649 fprintf(stderr, "# cleanup floats");
1650 if (!fsum) {
1651 fprintf(stderr, "\n");
1652 }
1653 else {
1654 fprintf(stderr,
1655 ": %d unfreed float%s in %d out of %d block%s\n",
1656 fsum, fsum == 1 ? "" : "s",
1657 bc - bf, bc, bc == 1 ? "" : "s");
1658 }
1659 if (Py_VerboseFlag > 1) {
1660 list = block_list;
1661 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001662 for (i = 0, p = &list->objects[0];
1663 i < N_FLOATOBJECTS;
1664 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001665 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001666 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001667 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001668 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001669 /* XXX(twouters) cast refcount to
1670 long until %zd is universally
1671 available
1672 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001673 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001674 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001675 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001676 }
1677 }
1678 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001679 }
1680 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001681}
Tim Peters9905b942003-03-20 20:53:32 +00001682
1683/*----------------------------------------------------------------------------
1684 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1685 *
1686 * TODO: On platforms that use the standard IEEE-754 single and double
1687 * formats natively, these routines could simply copy the bytes.
1688 */
1689int
1690_PyFloat_Pack4(double x, unsigned char *p, int le)
1691{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001692 if (float_format == unknown_format) {
1693 unsigned char sign;
1694 int e;
1695 double f;
1696 unsigned int fbits;
1697 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001698
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001699 if (le) {
1700 p += 3;
1701 incr = -1;
1702 }
Tim Peters9905b942003-03-20 20:53:32 +00001703
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001704 if (x < 0) {
1705 sign = 1;
1706 x = -x;
1707 }
1708 else
1709 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001710
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001712
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001713 /* Normalize f to be in the range [1.0, 2.0) */
1714 if (0.5 <= f && f < 1.0) {
1715 f *= 2.0;
1716 e--;
1717 }
1718 else if (f == 0.0)
1719 e = 0;
1720 else {
1721 PyErr_SetString(PyExc_SystemError,
1722 "frexp() result out of range");
1723 return -1;
1724 }
1725
1726 if (e >= 128)
1727 goto Overflow;
1728 else if (e < -126) {
1729 /* Gradual underflow */
1730 f = ldexp(f, 126 + e);
1731 e = 0;
1732 }
1733 else if (!(e == 0 && f == 0.0)) {
1734 e += 127;
1735 f -= 1.0; /* Get rid of leading 1 */
1736 }
1737
1738 f *= 8388608.0; /* 2**23 */
1739 fbits = (unsigned int)(f + 0.5); /* Round */
1740 assert(fbits <= 8388608);
1741 if (fbits >> 23) {
1742 /* The carry propagated out of a string of 23 1 bits. */
1743 fbits = 0;
1744 ++e;
1745 if (e >= 255)
1746 goto Overflow;
1747 }
1748
1749 /* First byte */
1750 *p = (sign << 7) | (e >> 1);
1751 p += incr;
1752
1753 /* Second byte */
1754 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1755 p += incr;
1756
1757 /* Third byte */
1758 *p = (fbits >> 8) & 0xFF;
1759 p += incr;
1760
1761 /* Fourth byte */
1762 *p = fbits & 0xFF;
1763
1764 /* Done */
1765 return 0;
1766
1767 Overflow:
1768 PyErr_SetString(PyExc_OverflowError,
1769 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001770 return -1;
1771 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001772 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001773 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001774 const char *s = (char*)&y;
1775 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001776
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777 if ((float_format == ieee_little_endian_format && !le)
1778 || (float_format == ieee_big_endian_format && le)) {
1779 p += 3;
1780 incr = -1;
1781 }
1782
1783 for (i = 0; i < 4; i++) {
1784 *p = *s++;
1785 p += incr;
1786 }
1787 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001788 }
Tim Peters9905b942003-03-20 20:53:32 +00001789}
1790
1791int
1792_PyFloat_Pack8(double x, unsigned char *p, int le)
1793{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001794 if (double_format == unknown_format) {
1795 unsigned char sign;
1796 int e;
1797 double f;
1798 unsigned int fhi, flo;
1799 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001800
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001801 if (le) {
1802 p += 7;
1803 incr = -1;
1804 }
Tim Peters9905b942003-03-20 20:53:32 +00001805
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001806 if (x < 0) {
1807 sign = 1;
1808 x = -x;
1809 }
1810 else
1811 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001812
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001813 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001814
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001815 /* Normalize f to be in the range [1.0, 2.0) */
1816 if (0.5 <= f && f < 1.0) {
1817 f *= 2.0;
1818 e--;
1819 }
1820 else if (f == 0.0)
1821 e = 0;
1822 else {
1823 PyErr_SetString(PyExc_SystemError,
1824 "frexp() result out of range");
1825 return -1;
1826 }
1827
1828 if (e >= 1024)
1829 goto Overflow;
1830 else if (e < -1022) {
1831 /* Gradual underflow */
1832 f = ldexp(f, 1022 + e);
1833 e = 0;
1834 }
1835 else if (!(e == 0 && f == 0.0)) {
1836 e += 1023;
1837 f -= 1.0; /* Get rid of leading 1 */
1838 }
1839
1840 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1841 f *= 268435456.0; /* 2**28 */
1842 fhi = (unsigned int)f; /* Truncate */
1843 assert(fhi < 268435456);
1844
1845 f -= (double)fhi;
1846 f *= 16777216.0; /* 2**24 */
1847 flo = (unsigned int)(f + 0.5); /* Round */
1848 assert(flo <= 16777216);
1849 if (flo >> 24) {
1850 /* The carry propagated out of a string of 24 1 bits. */
1851 flo = 0;
1852 ++fhi;
1853 if (fhi >> 28) {
1854 /* And it also progagated out of the next 28 bits. */
1855 fhi = 0;
1856 ++e;
1857 if (e >= 2047)
1858 goto Overflow;
1859 }
1860 }
1861
1862 /* First byte */
1863 *p = (sign << 7) | (e >> 4);
1864 p += incr;
1865
1866 /* Second byte */
1867 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1868 p += incr;
1869
1870 /* Third byte */
1871 *p = (fhi >> 16) & 0xFF;
1872 p += incr;
1873
1874 /* Fourth byte */
1875 *p = (fhi >> 8) & 0xFF;
1876 p += incr;
1877
1878 /* Fifth byte */
1879 *p = fhi & 0xFF;
1880 p += incr;
1881
1882 /* Sixth byte */
1883 *p = (flo >> 16) & 0xFF;
1884 p += incr;
1885
1886 /* Seventh byte */
1887 *p = (flo >> 8) & 0xFF;
1888 p += incr;
1889
1890 /* Eighth byte */
1891 *p = flo & 0xFF;
1892 p += incr;
1893
1894 /* Done */
1895 return 0;
1896
1897 Overflow:
1898 PyErr_SetString(PyExc_OverflowError,
1899 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001900 return -1;
1901 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001902 else {
1903 const char *s = (char*)&x;
1904 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001905
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906 if ((double_format == ieee_little_endian_format && !le)
1907 || (double_format == ieee_big_endian_format && le)) {
1908 p += 7;
1909 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001910 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001911
1912 for (i = 0; i < 8; i++) {
1913 *p = *s++;
1914 p += incr;
1915 }
1916 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001917 }
Tim Peters9905b942003-03-20 20:53:32 +00001918}
1919
Neal Norwitz545686b2006-12-28 04:45:06 +00001920/* Should only be used by marshal. */
1921int
1922_PyFloat_Repr(double x, char *p, size_t len)
1923{
1924 format_double(p, len, x, PREC_REPR);
1925 return (int)strlen(p);
1926}
1927
Tim Peters9905b942003-03-20 20:53:32 +00001928double
1929_PyFloat_Unpack4(const unsigned char *p, int le)
1930{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931 if (float_format == unknown_format) {
1932 unsigned char sign;
1933 int e;
1934 unsigned int f;
1935 double x;
1936 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001937
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001938 if (le) {
1939 p += 3;
1940 incr = -1;
1941 }
1942
1943 /* First byte */
1944 sign = (*p >> 7) & 1;
1945 e = (*p & 0x7F) << 1;
1946 p += incr;
1947
1948 /* Second byte */
1949 e |= (*p >> 7) & 1;
1950 f = (*p & 0x7F) << 16;
1951 p += incr;
1952
1953 if (e == 255) {
1954 PyErr_SetString(
1955 PyExc_ValueError,
1956 "can't unpack IEEE 754 special value "
1957 "on non-IEEE platform");
1958 return -1;
1959 }
1960
1961 /* Third byte */
1962 f |= *p << 8;
1963 p += incr;
1964
1965 /* Fourth byte */
1966 f |= *p;
1967
1968 x = (double)f / 8388608.0;
1969
1970 /* XXX This sadly ignores Inf/NaN issues */
1971 if (e == 0)
1972 e = -126;
1973 else {
1974 x += 1.0;
1975 e -= 127;
1976 }
1977 x = ldexp(x, e);
1978
1979 if (sign)
1980 x = -x;
1981
1982 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001983 }
Tim Peters9905b942003-03-20 20:53:32 +00001984 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001985 float x;
1986
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001987 if ((float_format == ieee_little_endian_format && !le)
1988 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001989 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001990 char *d = &buf[3];
1991 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001992
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001993 for (i = 0; i < 4; i++) {
1994 *d-- = *p++;
1995 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001996 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997 }
1998 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001999 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002000 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002001
2002 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003 }
Tim Peters9905b942003-03-20 20:53:32 +00002004}
2005
2006double
2007_PyFloat_Unpack8(const unsigned char *p, int le)
2008{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 if (double_format == unknown_format) {
2010 unsigned char sign;
2011 int e;
2012 unsigned int fhi, flo;
2013 double x;
2014 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002015
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002016 if (le) {
2017 p += 7;
2018 incr = -1;
2019 }
2020
2021 /* First byte */
2022 sign = (*p >> 7) & 1;
2023 e = (*p & 0x7F) << 4;
2024
2025 p += incr;
2026
2027 /* Second byte */
2028 e |= (*p >> 4) & 0xF;
2029 fhi = (*p & 0xF) << 24;
2030 p += incr;
2031
2032 if (e == 2047) {
2033 PyErr_SetString(
2034 PyExc_ValueError,
2035 "can't unpack IEEE 754 special value "
2036 "on non-IEEE platform");
2037 return -1.0;
2038 }
2039
2040 /* Third byte */
2041 fhi |= *p << 16;
2042 p += incr;
2043
2044 /* Fourth byte */
2045 fhi |= *p << 8;
2046 p += incr;
2047
2048 /* Fifth byte */
2049 fhi |= *p;
2050 p += incr;
2051
2052 /* Sixth byte */
2053 flo = *p << 16;
2054 p += incr;
2055
2056 /* Seventh byte */
2057 flo |= *p << 8;
2058 p += incr;
2059
2060 /* Eighth byte */
2061 flo |= *p;
2062
2063 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2064 x /= 268435456.0; /* 2**28 */
2065
2066 if (e == 0)
2067 e = -1022;
2068 else {
2069 x += 1.0;
2070 e -= 1023;
2071 }
2072 x = ldexp(x, e);
2073
2074 if (sign)
2075 x = -x;
2076
2077 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002078 }
Tim Peters9905b942003-03-20 20:53:32 +00002079 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002080 double x;
2081
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002082 if ((double_format == ieee_little_endian_format && !le)
2083 || (double_format == ieee_big_endian_format && le)) {
2084 char buf[8];
2085 char *d = &buf[7];
2086 int i;
2087
2088 for (i = 0; i < 8; i++) {
2089 *d-- = *p++;
2090 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002091 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002092 }
2093 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002094 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002095 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002096
2097 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002098 }
Tim Peters9905b942003-03-20 20:53:32 +00002099}