blob: e074a3704c5483985e01c6bc3bbc86698d5910d7 [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 *
Christian Heimes292d3512008-02-03 16:51:08 +00001069float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001070{
1071 double self;
1072 double float_part;
1073 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001074 int i;
1075
Christian Heimes26855632008-01-27 23:50:43 +00001076 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001077 PyObject *py_exponent = NULL;
1078 PyObject *numerator = NULL;
1079 PyObject *denominator = NULL;
1080 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001081 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001082
1083#define INPLACE_UPDATE(obj, call) \
1084 prev = obj; \
1085 obj = call; \
1086 Py_DECREF(prev); \
1087
1088 CONVERT_TO_DOUBLE(v, self);
1089
1090 if (Py_IS_INFINITY(self)) {
1091 PyErr_SetString(PyExc_OverflowError,
1092 "Cannot pass infinity to float.as_integer_ratio.");
1093 return NULL;
1094 }
1095#ifdef Py_NAN
1096 if (Py_IS_NAN(self)) {
1097 PyErr_SetString(PyExc_ValueError,
1098 "Cannot pass nan to float.as_integer_ratio.");
1099 return NULL;
1100 }
1101#endif
1102
Christian Heimes26855632008-01-27 23:50:43 +00001103 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001104 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001105 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001106
1107 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1108 float_part *= 2.0;
1109 exponent--;
1110 }
1111 /* self == float_part * 2**exponent exactly and float_part is integral.
1112 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1113 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001114
Christian Heimes292d3512008-02-03 16:51:08 +00001115 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001116 if (numerator == NULL) goto error;
1117
Christian Heimes292d3512008-02-03 16:51:08 +00001118 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001119 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001120 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001121 if (py_exponent == NULL) goto error;
1122 INPLACE_UPDATE(py_exponent,
1123 long_methods->nb_lshift(denominator, py_exponent));
1124 if (py_exponent == NULL) goto error;
1125 if (exponent > 0) {
1126 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001127 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001128 if (numerator == NULL) goto error;
1129 }
1130 else {
1131 Py_DECREF(denominator);
1132 denominator = py_exponent;
1133 py_exponent = NULL;
1134 }
1135
Christian Heimes292d3512008-02-03 16:51:08 +00001136 /* Returns ints instead of longs where possible */
1137 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1138 if (numerator == NULL) goto error;
1139 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1140 if (denominator == NULL) goto error;
1141
Christian Heimes26855632008-01-27 23:50:43 +00001142 result_pair = PyTuple_Pack(2, numerator, denominator);
1143
1144#undef INPLACE_UPDATE
1145error:
1146 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001147 Py_XDECREF(denominator);
1148 Py_XDECREF(numerator);
1149 return result_pair;
1150}
1151
1152PyDoc_STRVAR(float_as_integer_ratio_doc,
1153"float.as_integer_ratio() -> (int, int)\n"
1154"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001155"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1156"float and with a positive denominator.\n"
1157"Raises OverflowError on infinities and a ValueError on nans.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001158"\n"
1159">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001160"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001161">>> (0.0).as_integer_ratio()\n"
1162"(0, 1)\n"
1163">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001164"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001165
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001166
Jeremy Hylton938ace62002-07-17 16:30:39 +00001167static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001168float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1169
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170static PyObject *
1171float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1172{
1173 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001174 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175
Guido van Rossumbef14172001-08-29 15:47:46 +00001176 if (type != &PyFloat_Type)
1177 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1179 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001180 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001181 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 return PyNumber_Float(x);
1183}
1184
Guido van Rossumbef14172001-08-29 15:47:46 +00001185/* Wimpy, slow approach to tp_new calls for subtypes of float:
1186 first create a regular float from whatever arguments we got,
1187 then allocate a subtype instance and initialize its ob_fval
1188 from the regular float. The regular float is then thrown away.
1189*/
1190static PyObject *
1191float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1192{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001193 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001194
1195 assert(PyType_IsSubtype(type, &PyFloat_Type));
1196 tmp = float_new(&PyFloat_Type, args, kwds);
1197 if (tmp == NULL)
1198 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001199 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001200 newobj = type->tp_alloc(type, 0);
1201 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001202 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001203 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001204 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001205 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001206 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001207 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001208}
1209
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001210static PyObject *
1211float_getnewargs(PyFloatObject *v)
1212{
1213 return Py_BuildValue("(d)", v->ob_fval);
1214}
1215
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001216/* this is for the benefit of the pack/unpack routines below */
1217
1218typedef enum {
1219 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1220} float_format_type;
1221
1222static float_format_type double_format, float_format;
1223static float_format_type detected_double_format, detected_float_format;
1224
1225static PyObject *
1226float_getformat(PyTypeObject *v, PyObject* arg)
1227{
1228 char* s;
1229 float_format_type r;
1230
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001231 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001232 PyErr_Format(PyExc_TypeError,
1233 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001234 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001235 return NULL;
1236 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001237 s = PyUnicode_AsString(arg);
1238 if (s == NULL)
1239 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001240 if (strcmp(s, "double") == 0) {
1241 r = double_format;
1242 }
1243 else if (strcmp(s, "float") == 0) {
1244 r = float_format;
1245 }
1246 else {
1247 PyErr_SetString(PyExc_ValueError,
1248 "__getformat__() argument 1 must be "
1249 "'double' or 'float'");
1250 return NULL;
1251 }
1252
1253 switch (r) {
1254 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001255 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001256 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001257 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001258 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001259 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001260 default:
1261 Py_FatalError("insane float_format or double_format");
1262 return NULL;
1263 }
1264}
1265
1266PyDoc_STRVAR(float_getformat_doc,
1267"float.__getformat__(typestr) -> string\n"
1268"\n"
1269"You probably don't want to use this function. It exists mainly to be\n"
1270"used in Python's test suite.\n"
1271"\n"
1272"typestr must be 'double' or 'float'. This function returns whichever of\n"
1273"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1274"format of floating point numbers used by the C type named by typestr.");
1275
1276static PyObject *
1277float_setformat(PyTypeObject *v, PyObject* args)
1278{
1279 char* typestr;
1280 char* format;
1281 float_format_type f;
1282 float_format_type detected;
1283 float_format_type *p;
1284
1285 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1286 return NULL;
1287
1288 if (strcmp(typestr, "double") == 0) {
1289 p = &double_format;
1290 detected = detected_double_format;
1291 }
1292 else if (strcmp(typestr, "float") == 0) {
1293 p = &float_format;
1294 detected = detected_float_format;
1295 }
1296 else {
1297 PyErr_SetString(PyExc_ValueError,
1298 "__setformat__() argument 1 must "
1299 "be 'double' or 'float'");
1300 return NULL;
1301 }
1302
1303 if (strcmp(format, "unknown") == 0) {
1304 f = unknown_format;
1305 }
1306 else if (strcmp(format, "IEEE, little-endian") == 0) {
1307 f = ieee_little_endian_format;
1308 }
1309 else if (strcmp(format, "IEEE, big-endian") == 0) {
1310 f = ieee_big_endian_format;
1311 }
1312 else {
1313 PyErr_SetString(PyExc_ValueError,
1314 "__setformat__() argument 2 must be "
1315 "'unknown', 'IEEE, little-endian' or "
1316 "'IEEE, big-endian'");
1317 return NULL;
1318
1319 }
1320
1321 if (f != unknown_format && f != detected) {
1322 PyErr_Format(PyExc_ValueError,
1323 "can only set %s format to 'unknown' or the "
1324 "detected platform value", typestr);
1325 return NULL;
1326 }
1327
1328 *p = f;
1329 Py_RETURN_NONE;
1330}
1331
1332PyDoc_STRVAR(float_setformat_doc,
1333"float.__setformat__(typestr, fmt) -> None\n"
1334"\n"
1335"You probably don't want to use this function. It exists mainly to be\n"
1336"used in Python's test suite.\n"
1337"\n"
1338"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1339"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1340"one of the latter two if it appears to match the underlying C reality.\n"
1341"\n"
1342"Overrides the automatic determination of C-level floating point type.\n"
1343"This affects how floats are converted to and from binary strings.");
1344
Guido van Rossumb43daf72007-08-01 18:08:08 +00001345static PyObject *
1346float_getzero(PyObject *v, void *closure)
1347{
1348 return PyFloat_FromDouble(0.0);
1349}
1350
Eric Smith8c663262007-08-25 02:26:07 +00001351static PyObject *
1352float__format__(PyObject *self, PyObject *args)
1353{
1354 /* when back porting this to 2.6, check type of the format_spec
1355 and call either unicode_long__format__ or
1356 string_long__format__ */
1357 return unicode_float__format__(self, args);
1358}
1359
1360PyDoc_STRVAR(float__format__doc,
1361"float.__format__(format_spec) -> string\n"
1362"\n"
1363"Formats the float according to format_spec.");
1364
1365
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001366static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001367 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1368 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001369 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1370 "Returns the Integral closest to x between 0 and x."},
1371 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1372 "Returns the Integral closest to x, rounding half toward even.\n"
1373 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001374 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1375 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001376 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001377 {"__getformat__", (PyCFunction)float_getformat,
1378 METH_O|METH_CLASS, float_getformat_doc},
1379 {"__setformat__", (PyCFunction)float_setformat,
1380 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001381 {"__format__", (PyCFunction)float__format__,
1382 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001383 {NULL, NULL} /* sentinel */
1384};
1385
Guido van Rossumb43daf72007-08-01 18:08:08 +00001386static PyGetSetDef float_getset[] = {
1387 {"real",
1388 (getter)float_float, (setter)NULL,
1389 "the real part of a complex number",
1390 NULL},
1391 {"imag",
1392 (getter)float_getzero, (setter)NULL,
1393 "the imaginary part of a complex number",
1394 NULL},
1395 {NULL} /* Sentinel */
1396};
1397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001398PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399"float(x) -> floating point number\n\
1400\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001401Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402
1403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001404static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001405 float_add, /*nb_add*/
1406 float_sub, /*nb_subtract*/
1407 float_mul, /*nb_multiply*/
1408 float_rem, /*nb_remainder*/
1409 float_divmod, /*nb_divmod*/
1410 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001411 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001412 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001413 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001414 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001415 0, /*nb_invert*/
1416 0, /*nb_lshift*/
1417 0, /*nb_rshift*/
1418 0, /*nb_and*/
1419 0, /*nb_xor*/
1420 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001421 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001422 float_trunc, /*nb_int*/
1423 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001424 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001425 0, /* nb_oct */
1426 0, /* nb_hex */
1427 0, /* nb_inplace_add */
1428 0, /* nb_inplace_subtract */
1429 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001430 0, /* nb_inplace_remainder */
1431 0, /* nb_inplace_power */
1432 0, /* nb_inplace_lshift */
1433 0, /* nb_inplace_rshift */
1434 0, /* nb_inplace_and */
1435 0, /* nb_inplace_xor */
1436 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001437 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001438 float_div, /* nb_true_divide */
1439 0, /* nb_inplace_floor_divide */
1440 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001441};
1442
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001443PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001444 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001445 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001446 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001447 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001449 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450 0, /* tp_getattr */
1451 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001452 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 (reprfunc)float_repr, /* tp_repr */
1454 &float_as_number, /* tp_as_number */
1455 0, /* tp_as_sequence */
1456 0, /* tp_as_mapping */
1457 (hashfunc)float_hash, /* tp_hash */
1458 0, /* tp_call */
1459 (reprfunc)float_str, /* tp_str */
1460 PyObject_GenericGetAttr, /* tp_getattro */
1461 0, /* tp_setattro */
1462 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001463 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 float_doc, /* tp_doc */
1465 0, /* tp_traverse */
1466 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001467 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 0, /* tp_weaklistoffset */
1469 0, /* tp_iter */
1470 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001471 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001473 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 0, /* tp_base */
1475 0, /* tp_dict */
1476 0, /* tp_descr_get */
1477 0, /* tp_descr_set */
1478 0, /* tp_dictoffset */
1479 0, /* tp_init */
1480 0, /* tp_alloc */
1481 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001483
1484void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001485_PyFloat_Init(void)
1486{
1487 /* We attempt to determine if this machine is using IEEE
1488 floating point formats by peering at the bits of some
1489 carefully chosen values. If it looks like we are on an
1490 IEEE platform, the float packing/unpacking routines can
1491 just copy bits, if not they resort to arithmetic & shifts
1492 and masks. The shifts & masks approach works on all finite
1493 values, but what happens to infinities, NaNs and signed
1494 zeroes on packing is an accident, and attempting to unpack
1495 a NaN or an infinity will raise an exception.
1496
1497 Note that if we're on some whacked-out platform which uses
1498 IEEE formats but isn't strictly little-endian or big-
1499 endian, we will fall back to the portable shifts & masks
1500 method. */
1501
1502#if SIZEOF_DOUBLE == 8
1503 {
1504 double x = 9006104071832581.0;
1505 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1506 detected_double_format = ieee_big_endian_format;
1507 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1508 detected_double_format = ieee_little_endian_format;
1509 else
1510 detected_double_format = unknown_format;
1511 }
1512#else
1513 detected_double_format = unknown_format;
1514#endif
1515
1516#if SIZEOF_FLOAT == 4
1517 {
1518 float y = 16711938.0;
1519 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1520 detected_float_format = ieee_big_endian_format;
1521 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1522 detected_float_format = ieee_little_endian_format;
1523 else
1524 detected_float_format = unknown_format;
1525 }
1526#else
1527 detected_float_format = unknown_format;
1528#endif
1529
1530 double_format = detected_double_format;
1531 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001532
1533#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001534 /* Initialize floating point repr */
1535 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001536#endif
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001537 /* Init float info */
1538 if (FloatInfoType.tp_name == 0)
1539 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001540}
1541
1542void
Christian Heimes15ebc882008-02-04 18:48:49 +00001543PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001544{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001545 PyFloatObject *p;
1546 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001547 unsigned i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001548 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1549 size_t fsum = 0; /* total unfreed ints */
1550 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001551
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001552 list = block_list;
1553 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001554 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001555 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001556 bc++;
1557 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001558 for (i = 0, p = &list->objects[0];
1559 i < N_FLOATOBJECTS;
1560 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001561 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001562 frem++;
1563 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001564 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001565 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001566 list->next = block_list;
1567 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001568 for (i = 0, p = &list->objects[0];
1569 i < N_FLOATOBJECTS;
1570 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001571 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001572 Py_REFCNT(p) == 0) {
1573 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001574 free_list;
1575 free_list = p;
1576 }
1577 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001578 }
1579 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001580 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001581 bf++;
1582 }
1583 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001584 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001585 }
Christian Heimes15ebc882008-02-04 18:48:49 +00001586 *pbc = bc;
1587 *pbf = bf;
1588 *bsum = fsum;
1589}
1590
1591void
1592PyFloat_Fini(void)
1593{
1594 PyFloatObject *p;
1595 PyFloatBlock *list;
1596 unsigned i;
1597 size_t bc, bf; /* block count, number of freed blocks */
1598 size_t fsum; /* total unfreed floats per block */
1599
1600 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1601
Guido van Rossum3fce8831999-03-12 19:43:17 +00001602 if (!Py_VerboseFlag)
1603 return;
1604 fprintf(stderr, "# cleanup floats");
1605 if (!fsum) {
1606 fprintf(stderr, "\n");
1607 }
1608 else {
1609 fprintf(stderr,
Christian Heimes15ebc882008-02-04 18:48:49 +00001610 ": %" PY_FORMAT_SIZE_T "d unfreed floats%s in %"
1611 PY_FORMAT_SIZE_T "d out of %"
1612 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001613 fsum, fsum == 1 ? "" : "s",
1614 bc - bf, bc, bc == 1 ? "" : "s");
1615 }
1616 if (Py_VerboseFlag > 1) {
1617 list = block_list;
1618 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001619 for (i = 0, p = &list->objects[0];
1620 i < N_FLOATOBJECTS;
1621 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001622 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001623 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001624 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001625 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001626 /* XXX(twouters) cast refcount to
1627 long until %zd is universally
1628 available
1629 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001630 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001631 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001632 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001633 }
1634 }
1635 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001636 }
1637 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001638}
Tim Peters9905b942003-03-20 20:53:32 +00001639
1640/*----------------------------------------------------------------------------
1641 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1642 *
1643 * TODO: On platforms that use the standard IEEE-754 single and double
1644 * formats natively, these routines could simply copy the bytes.
1645 */
1646int
1647_PyFloat_Pack4(double x, unsigned char *p, int le)
1648{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001649 if (float_format == unknown_format) {
1650 unsigned char sign;
1651 int e;
1652 double f;
1653 unsigned int fbits;
1654 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001655
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001656 if (le) {
1657 p += 3;
1658 incr = -1;
1659 }
Tim Peters9905b942003-03-20 20:53:32 +00001660
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001661 if (x < 0) {
1662 sign = 1;
1663 x = -x;
1664 }
1665 else
1666 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001667
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001668 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001669
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001670 /* Normalize f to be in the range [1.0, 2.0) */
1671 if (0.5 <= f && f < 1.0) {
1672 f *= 2.0;
1673 e--;
1674 }
1675 else if (f == 0.0)
1676 e = 0;
1677 else {
1678 PyErr_SetString(PyExc_SystemError,
1679 "frexp() result out of range");
1680 return -1;
1681 }
1682
1683 if (e >= 128)
1684 goto Overflow;
1685 else if (e < -126) {
1686 /* Gradual underflow */
1687 f = ldexp(f, 126 + e);
1688 e = 0;
1689 }
1690 else if (!(e == 0 && f == 0.0)) {
1691 e += 127;
1692 f -= 1.0; /* Get rid of leading 1 */
1693 }
1694
1695 f *= 8388608.0; /* 2**23 */
1696 fbits = (unsigned int)(f + 0.5); /* Round */
1697 assert(fbits <= 8388608);
1698 if (fbits >> 23) {
1699 /* The carry propagated out of a string of 23 1 bits. */
1700 fbits = 0;
1701 ++e;
1702 if (e >= 255)
1703 goto Overflow;
1704 }
1705
1706 /* First byte */
1707 *p = (sign << 7) | (e >> 1);
1708 p += incr;
1709
1710 /* Second byte */
1711 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1712 p += incr;
1713
1714 /* Third byte */
1715 *p = (fbits >> 8) & 0xFF;
1716 p += incr;
1717
1718 /* Fourth byte */
1719 *p = fbits & 0xFF;
1720
1721 /* Done */
1722 return 0;
1723
1724 Overflow:
1725 PyErr_SetString(PyExc_OverflowError,
1726 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001727 return -1;
1728 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001729 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001730 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731 const char *s = (char*)&y;
1732 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001733
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001734 if ((float_format == ieee_little_endian_format && !le)
1735 || (float_format == ieee_big_endian_format && le)) {
1736 p += 3;
1737 incr = -1;
1738 }
1739
1740 for (i = 0; i < 4; i++) {
1741 *p = *s++;
1742 p += incr;
1743 }
1744 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001745 }
Tim Peters9905b942003-03-20 20:53:32 +00001746}
1747
1748int
1749_PyFloat_Pack8(double x, unsigned char *p, int le)
1750{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001751 if (double_format == unknown_format) {
1752 unsigned char sign;
1753 int e;
1754 double f;
1755 unsigned int fhi, flo;
1756 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001757
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001758 if (le) {
1759 p += 7;
1760 incr = -1;
1761 }
Tim Peters9905b942003-03-20 20:53:32 +00001762
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001763 if (x < 0) {
1764 sign = 1;
1765 x = -x;
1766 }
1767 else
1768 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001769
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001770 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001771
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001772 /* Normalize f to be in the range [1.0, 2.0) */
1773 if (0.5 <= f && f < 1.0) {
1774 f *= 2.0;
1775 e--;
1776 }
1777 else if (f == 0.0)
1778 e = 0;
1779 else {
1780 PyErr_SetString(PyExc_SystemError,
1781 "frexp() result out of range");
1782 return -1;
1783 }
1784
1785 if (e >= 1024)
1786 goto Overflow;
1787 else if (e < -1022) {
1788 /* Gradual underflow */
1789 f = ldexp(f, 1022 + e);
1790 e = 0;
1791 }
1792 else if (!(e == 0 && f == 0.0)) {
1793 e += 1023;
1794 f -= 1.0; /* Get rid of leading 1 */
1795 }
1796
1797 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1798 f *= 268435456.0; /* 2**28 */
1799 fhi = (unsigned int)f; /* Truncate */
1800 assert(fhi < 268435456);
1801
1802 f -= (double)fhi;
1803 f *= 16777216.0; /* 2**24 */
1804 flo = (unsigned int)(f + 0.5); /* Round */
1805 assert(flo <= 16777216);
1806 if (flo >> 24) {
1807 /* The carry propagated out of a string of 24 1 bits. */
1808 flo = 0;
1809 ++fhi;
1810 if (fhi >> 28) {
1811 /* And it also progagated out of the next 28 bits. */
1812 fhi = 0;
1813 ++e;
1814 if (e >= 2047)
1815 goto Overflow;
1816 }
1817 }
1818
1819 /* First byte */
1820 *p = (sign << 7) | (e >> 4);
1821 p += incr;
1822
1823 /* Second byte */
1824 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1825 p += incr;
1826
1827 /* Third byte */
1828 *p = (fhi >> 16) & 0xFF;
1829 p += incr;
1830
1831 /* Fourth byte */
1832 *p = (fhi >> 8) & 0xFF;
1833 p += incr;
1834
1835 /* Fifth byte */
1836 *p = fhi & 0xFF;
1837 p += incr;
1838
1839 /* Sixth byte */
1840 *p = (flo >> 16) & 0xFF;
1841 p += incr;
1842
1843 /* Seventh byte */
1844 *p = (flo >> 8) & 0xFF;
1845 p += incr;
1846
1847 /* Eighth byte */
1848 *p = flo & 0xFF;
1849 p += incr;
1850
1851 /* Done */
1852 return 0;
1853
1854 Overflow:
1855 PyErr_SetString(PyExc_OverflowError,
1856 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001857 return -1;
1858 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001859 else {
1860 const char *s = (char*)&x;
1861 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001862
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001863 if ((double_format == ieee_little_endian_format && !le)
1864 || (double_format == ieee_big_endian_format && le)) {
1865 p += 7;
1866 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001867 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001868
1869 for (i = 0; i < 8; i++) {
1870 *p = *s++;
1871 p += incr;
1872 }
1873 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001874 }
Tim Peters9905b942003-03-20 20:53:32 +00001875}
1876
Neal Norwitz545686b2006-12-28 04:45:06 +00001877/* Should only be used by marshal. */
1878int
1879_PyFloat_Repr(double x, char *p, size_t len)
1880{
1881 format_double(p, len, x, PREC_REPR);
1882 return (int)strlen(p);
1883}
1884
Tim Peters9905b942003-03-20 20:53:32 +00001885double
1886_PyFloat_Unpack4(const unsigned char *p, int le)
1887{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001888 if (float_format == unknown_format) {
1889 unsigned char sign;
1890 int e;
1891 unsigned int f;
1892 double x;
1893 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001894
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001895 if (le) {
1896 p += 3;
1897 incr = -1;
1898 }
1899
1900 /* First byte */
1901 sign = (*p >> 7) & 1;
1902 e = (*p & 0x7F) << 1;
1903 p += incr;
1904
1905 /* Second byte */
1906 e |= (*p >> 7) & 1;
1907 f = (*p & 0x7F) << 16;
1908 p += incr;
1909
1910 if (e == 255) {
1911 PyErr_SetString(
1912 PyExc_ValueError,
1913 "can't unpack IEEE 754 special value "
1914 "on non-IEEE platform");
1915 return -1;
1916 }
1917
1918 /* Third byte */
1919 f |= *p << 8;
1920 p += incr;
1921
1922 /* Fourth byte */
1923 f |= *p;
1924
1925 x = (double)f / 8388608.0;
1926
1927 /* XXX This sadly ignores Inf/NaN issues */
1928 if (e == 0)
1929 e = -126;
1930 else {
1931 x += 1.0;
1932 e -= 127;
1933 }
1934 x = ldexp(x, e);
1935
1936 if (sign)
1937 x = -x;
1938
1939 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001940 }
Tim Peters9905b942003-03-20 20:53:32 +00001941 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001942 float x;
1943
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001944 if ((float_format == ieee_little_endian_format && !le)
1945 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001946 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001947 char *d = &buf[3];
1948 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001949
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001950 for (i = 0; i < 4; i++) {
1951 *d-- = *p++;
1952 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001953 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001954 }
1955 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001956 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001957 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001958
1959 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001960 }
Tim Peters9905b942003-03-20 20:53:32 +00001961}
1962
1963double
1964_PyFloat_Unpack8(const unsigned char *p, int le)
1965{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001966 if (double_format == unknown_format) {
1967 unsigned char sign;
1968 int e;
1969 unsigned int fhi, flo;
1970 double x;
1971 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001972
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001973 if (le) {
1974 p += 7;
1975 incr = -1;
1976 }
1977
1978 /* First byte */
1979 sign = (*p >> 7) & 1;
1980 e = (*p & 0x7F) << 4;
1981
1982 p += incr;
1983
1984 /* Second byte */
1985 e |= (*p >> 4) & 0xF;
1986 fhi = (*p & 0xF) << 24;
1987 p += incr;
1988
1989 if (e == 2047) {
1990 PyErr_SetString(
1991 PyExc_ValueError,
1992 "can't unpack IEEE 754 special value "
1993 "on non-IEEE platform");
1994 return -1.0;
1995 }
1996
1997 /* Third byte */
1998 fhi |= *p << 16;
1999 p += incr;
2000
2001 /* Fourth byte */
2002 fhi |= *p << 8;
2003 p += incr;
2004
2005 /* Fifth byte */
2006 fhi |= *p;
2007 p += incr;
2008
2009 /* Sixth byte */
2010 flo = *p << 16;
2011 p += incr;
2012
2013 /* Seventh byte */
2014 flo |= *p << 8;
2015 p += incr;
2016
2017 /* Eighth byte */
2018 flo |= *p;
2019
2020 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2021 x /= 268435456.0; /* 2**28 */
2022
2023 if (e == 0)
2024 e = -1022;
2025 else {
2026 x += 1.0;
2027 e -= 1023;
2028 }
2029 x = ldexp(x, e);
2030
2031 if (sign)
2032 x = -x;
2033
2034 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002035 }
Tim Peters9905b942003-03-20 20:53:32 +00002036 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002037 double x;
2038
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002039 if ((double_format == ieee_little_endian_format && !le)
2040 || (double_format == ieee_big_endian_format && le)) {
2041 char buf[8];
2042 char *d = &buf[7];
2043 int i;
2044
2045 for (i = 0; i < 8; i++) {
2046 *d-- = *p++;
2047 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002048 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002049 }
2050 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002051 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002052 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002053
2054 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002055 }
Tim Peters9905b942003-03-20 20:53:32 +00002056}