blob: 8ef3261c6ad07e1377425e8ab0ede65754cab586 [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 Heimesd32ed6f2008-01-14 18:49:24 +0000109 static PyObject* floatinfo;
110 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000111
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000112 if (floatinfo != NULL) {
113 Py_INCREF(floatinfo);
114 return floatinfo;
115 }
116 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
117
118 floatinfo = PyStructSequence_New(&FloatInfoType);
119 if (floatinfo == NULL) {
120 return NULL;
121 }
Christian Heimes93852662007-12-01 12:22:32 +0000122
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000123#define SetIntFlag(flag) \
124 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
125#define SetDblFlag(flag) \
126 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000127
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000128 SetDblFlag(DBL_MAX);
129 SetIntFlag(DBL_MAX_EXP);
130 SetIntFlag(DBL_MAX_10_EXP);
131 SetDblFlag(DBL_MIN);
132 SetIntFlag(DBL_MIN_EXP);
133 SetIntFlag(DBL_MIN_10_EXP);
134 SetIntFlag(DBL_DIG);
135 SetIntFlag(DBL_MANT_DIG);
136 SetDblFlag(DBL_EPSILON);
137 SetIntFlag(FLT_RADIX);
138 SetIntFlag(FLT_ROUNDS);
139#undef SetIntFlag
140#undef SetDblFlag
141
142 if (PyErr_Occurred()) {
143 Py_CLEAR(floatinfo);
144 return NULL;
145 }
Christian Heimes93852662007-12-01 12:22:32 +0000146
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000147 Py_INCREF(floatinfo);
148 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000149}
150
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 register PyFloatObject *op;
155 if (free_list == NULL) {
156 if ((free_list = fill_free_list()) == NULL)
157 return NULL;
158 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000159 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000160 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000161 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000162 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000163 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000168PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000169{
Christian Heimes99170a52007-12-19 02:07:34 +0000170 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000172 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000173 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000174 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000175 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000176
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000177 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000178 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
179 if (s_buffer == NULL)
180 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000181 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000182 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000183 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000184 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000185 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000186 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000188 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000189 else if (PyObject_AsCharBuffer(v, &s, &len)) {
190 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000191 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000193 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000194
Guido van Rossum4c08d552000-03-10 22:55:18 +0000195 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000196 while (*s && isspace(Py_CHARMASK(*s)))
197 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000198 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000199 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000200 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000201 }
Christian Heimes99170a52007-12-19 02:07:34 +0000202 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000203 /* We don't care about overflow or underflow. If the platform supports
204 * them, infinities and signed zeroes (on underflow) are fine.
205 * However, strtod can return 0 for denormalized numbers, where atof
206 * does not. So (alas!) we special-case a zero result. Note that
207 * whether strtod sets errno on underflow is not defined, so we can't
208 * key off errno.
209 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000210 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000211 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000212 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000215 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000216 if (end > last)
217 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000218 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000219 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000220 char *p = (char*)sp;
221 int sign = 1;
222
223 if (*p == '-') {
224 sign = -1;
225 p++;
226 }
227 if (*p == '+') {
228 p++;
229 }
230 if (PyOS_strnicmp(p, "inf", 4) == 0) {
231 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
232 }
233#ifdef Py_NAN
234 if(PyOS_strnicmp(p, "nan", 4) == 0) {
235 return PyFloat_FromDouble(Py_NAN);
236 }
237#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000238 PyOS_snprintf(buffer, sizeof(buffer),
239 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000240 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000241 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000242 }
243 /* Since end != s, the platform made *some* kind of sense out
244 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000245 while (*end && isspace(Py_CHARMASK(*end)))
246 end++;
247 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000248 PyOS_snprintf(buffer, sizeof(buffer),
249 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000250 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000251 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000252 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000253 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000254 PyErr_SetString(PyExc_ValueError,
255 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000256 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000257 }
Tim Petersef14d732000-09-23 03:39:17 +0000258 if (x == 0.0) {
259 /* See above -- may have been strtod being anal
260 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000261 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000262 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000263 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000264 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000265 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000266 result = PyFloat_FromDouble(x);
267 error:
268 if (s_buffer)
269 PyMem_FREE(s_buffer);
270 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000271}
272
Guido van Rossum234f9421993-06-17 12:35:49 +0000273static void
Fred Drakefd99de62000-07-09 05:02:18 +0000274float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000275{
Guido van Rossum9475a232001-10-05 20:51:39 +0000276 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000277 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000278 free_list = op;
279 }
280 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000281 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000282}
283
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284double
Fred Drakefd99de62000-07-09 05:02:18 +0000285PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287 PyNumberMethods *nb;
288 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000289 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000290
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000291 if (op && PyFloat_Check(op))
292 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000293
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000294 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 return -1;
297 }
Tim Petersd2364e82001-11-01 20:09:42 +0000298
Christian Heimes90aa7642007-12-19 02:45:37 +0000299 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000300 PyErr_SetString(PyExc_TypeError, "a float is required");
301 return -1;
302 }
303
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 if (fo == NULL)
306 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 if (!PyFloat_Check(fo)) {
308 PyErr_SetString(PyExc_TypeError,
309 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310 return -1;
311 }
Tim Petersd2364e82001-11-01 20:09:42 +0000312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313 val = PyFloat_AS_DOUBLE(fo);
314 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000315
Guido van Rossumb6775db1994-08-01 11:34:53 +0000316 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317}
318
319/* Methods */
320
Tim Peters97019e42001-11-28 22:43:45 +0000321static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000322format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323{
324 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000325 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000326 int i;
327
328 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329 We want float numbers to be recognizable as such,
330 i.e., they should contain a decimal point or an exponent.
331 However, %g may print the number as an integer;
332 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000333
Martin v. Löwis737ea822004-06-08 18:52:54 +0000334 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000335 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336 cp = buf;
337 if (*cp == '-')
338 cp++;
339 for (; *cp != '\0'; cp++) {
340 /* Any non-digit means it's not an integer;
341 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000342 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343 break;
344 }
345 if (*cp == '\0') {
346 *cp++ = '.';
347 *cp++ = '0';
348 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000349 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350 }
Christian Heimes99170a52007-12-19 02:07:34 +0000351 /* Checking the next three chars should be more than enough to
352 * detect inf or nan, even on Windows. We check for inf or nan
353 * at last because they are rare cases.
354 */
355 for (i=0; *cp != '\0' && i<3; cp++, i++) {
356 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
357 continue;
358 /* found something that is neither a digit nor point
359 * it might be a NaN or INF
360 */
361#ifdef Py_NAN
362 if (Py_IS_NAN(ob_fval)) {
363 strcpy(buf, "nan");
364 }
365 else
366#endif
367 if (Py_IS_INFINITY(ob_fval)) {
368 cp = buf;
369 if (*cp == '-')
370 cp++;
371 strcpy(cp, "inf");
372 }
373 break;
374 }
375
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376}
377
Neal Norwitz545686b2006-12-28 04:45:06 +0000378static void
379format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000380{
Neal Norwitz545686b2006-12-28 04:45:06 +0000381 assert(PyFloat_Check(v));
382 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000383}
384
Christian Heimesb76922a2007-12-11 01:06:40 +0000385#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000386/* The following function is based on Tcl_PrintDouble,
387 * from tclUtil.c.
388 */
389
390#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
391#define is_nan(d) ((d) != (d))
392
393static void
394format_double_repr(char *dst, double value)
395{
396 char *p, c;
397 int exp;
398 int signum;
399 char buffer[30];
400
401 /*
402 * Handle NaN.
403 */
404
405 if (is_nan(value)) {
406 strcpy(dst, "nan");
407 return;
408 }
409
410 /*
411 * Handle infinities.
412 */
413
414 if (is_infinite(value)) {
415 if (value < 0) {
416 strcpy(dst, "-inf");
417 } else {
418 strcpy(dst, "inf");
419 }
420 return;
421 }
422
423 /*
424 * Ordinary (normal and denormal) values.
425 */
426
427 exp = _PyFloat_Digits(buffer, value, &signum)+1;
428 if (signum) {
429 *dst++ = '-';
430 }
431 p = buffer;
432 if (exp < -3 || exp > 17) {
433 /*
434 * E format for numbers < 1e-3 or >= 1e17.
435 */
436
437 *dst++ = *p++;
438 c = *p;
439 if (c != '\0') {
440 *dst++ = '.';
441 while (c != '\0') {
442 *dst++ = c;
443 c = *++p;
444 }
445 }
446 sprintf(dst, "e%+d", exp-1);
447 } else {
448 /*
449 * F format for others.
450 */
451
452 if (exp <= 0) {
453 *dst++ = '0';
454 }
455 c = *p;
456 while (exp-- > 0) {
457 if (c != '\0') {
458 *dst++ = c;
459 c = *++p;
460 } else {
461 *dst++ = '0';
462 }
463 }
464 *dst++ = '.';
465 if (c == '\0') {
466 *dst++ = '0';
467 } else {
468 while (++exp < 0) {
469 *dst++ = '0';
470 }
471 while (c != '\0') {
472 *dst++ = c;
473 c = *++p;
474 }
475 }
476 *dst++ = '\0';
477 }
478}
479
480static void
481format_float_repr(char *buf, PyFloatObject *v)
482{
483 assert(PyFloat_Check(v));
484 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
485}
486
Christian Heimesb76922a2007-12-11 01:06:40 +0000487#endif /* Py_BROKEN_REPR */
488
Neil Schemenauer32117e52001-01-04 01:44:34 +0000489/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000490 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000491 set to NULL, and the function invoking this macro returns NULL. If
492 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
493 stored in obj, and returned from the function invoking this macro.
494*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000495#define CONVERT_TO_DOUBLE(obj, dbl) \
496 if (PyFloat_Check(obj)) \
497 dbl = PyFloat_AS_DOUBLE(obj); \
498 else if (convert_to_double(&(obj), &(dbl)) < 0) \
499 return obj;
500
501static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000502convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000503{
504 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000505
Guido van Rossumddefaf32007-01-14 03:31:43 +0000506 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000507 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000508 if (*dbl == -1.0 && PyErr_Occurred()) {
509 *v = NULL;
510 return -1;
511 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000512 }
513 else {
514 Py_INCREF(Py_NotImplemented);
515 *v = Py_NotImplemented;
516 return -1;
517 }
518 return 0;
519}
520
Guido van Rossum57072eb1999-12-23 19:00:28 +0000521/* Precisions used by repr() and str(), respectively.
522
523 The repr() precision (17 significant decimal digits) is the minimal number
524 that is guaranteed to have enough precision so that if the number is read
525 back in the exact same binary value is recreated. This is true for IEEE
526 floating point by design, and also happens to work for all other modern
527 hardware.
528
529 The str() precision is chosen so that in most cases, the rounding noise
530 created by various operations is suppressed, while giving plenty of
531 precision for practical use.
532
533*/
534
535#define PREC_REPR 17
536#define PREC_STR 12
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000539float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540{
Christian Heimesb76922a2007-12-11 01:06:40 +0000541#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000542 char buf[30];
543 format_float_repr(buf, v);
Christian Heimesb76922a2007-12-11 01:06:40 +0000544#else
545 char buf[100];
546 format_float(buf, sizeof(buf), v, PREC_REPR);
547#endif
548
Walter Dörwald1ab83302007-05-18 17:15:44 +0000549 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000550}
551
552static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000553float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000554{
555 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000556 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000557 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558}
559
Tim Peters307fa782004-09-23 08:06:40 +0000560/* Comparison is pretty much a nightmare. When comparing float to float,
561 * we do it as straightforwardly (and long-windedly) as conceivable, so
562 * that, e.g., Python x == y delivers the same result as the platform
563 * C x == y when x and/or y is a NaN.
564 * When mixing float with an integer type, there's no good *uniform* approach.
565 * Converting the double to an integer obviously doesn't work, since we
566 * may lose info from fractional bits. Converting the integer to a double
567 * also has two failure modes: (1) a long int may trigger overflow (too
568 * large to fit in the dynamic range of a C double); (2) even a C long may have
569 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
570 * 63 bits of precision, but a C double probably has only 53), and then
571 * we can falsely claim equality when low-order integer bits are lost by
572 * coercion to double. So this part is painful too.
573 */
574
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000575static PyObject*
576float_richcompare(PyObject *v, PyObject *w, int op)
577{
578 double i, j;
579 int r = 0;
580
Tim Peters307fa782004-09-23 08:06:40 +0000581 assert(PyFloat_Check(v));
582 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000583
Tim Peters307fa782004-09-23 08:06:40 +0000584 /* Switch on the type of w. Set i and j to doubles to be compared,
585 * and op to the richcomp to use.
586 */
587 if (PyFloat_Check(w))
588 j = PyFloat_AS_DOUBLE(w);
589
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000591 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000592 /* If i is an infinity, its magnitude exceeds any
593 * finite integer, so it doesn't matter which int we
594 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000595 */
596 j = 0.0;
597 else
598 goto Unimplemented;
599 }
600
Tim Peters307fa782004-09-23 08:06:40 +0000601 else if (PyLong_Check(w)) {
602 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
603 int wsign = _PyLong_Sign(w);
604 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000605 int exponent;
606
607 if (vsign != wsign) {
608 /* Magnitudes are irrelevant -- the signs alone
609 * determine the outcome.
610 */
611 i = (double)vsign;
612 j = (double)wsign;
613 goto Compare;
614 }
615 /* The signs are the same. */
616 /* Convert w to a double if it fits. In particular, 0 fits. */
617 nbits = _PyLong_NumBits(w);
618 if (nbits == (size_t)-1 && PyErr_Occurred()) {
619 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000620 * to hold the # of bits. Replace with little doubles
621 * that give the same outcome -- w is so large that
622 * its magnitude must exceed the magnitude of any
623 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000624 */
625 PyErr_Clear();
626 i = (double)vsign;
627 assert(wsign != 0);
628 j = wsign * 2.0;
629 goto Compare;
630 }
631 if (nbits <= 48) {
632 j = PyLong_AsDouble(w);
633 /* It's impossible that <= 48 bits overflowed. */
634 assert(j != -1.0 || ! PyErr_Occurred());
635 goto Compare;
636 }
637 assert(wsign != 0); /* else nbits was 0 */
638 assert(vsign != 0); /* if vsign were 0, then since wsign is
639 * not 0, we would have taken the
640 * vsign != wsign branch at the start */
641 /* We want to work with non-negative numbers. */
642 if (vsign < 0) {
643 /* "Multiply both sides" by -1; this also swaps the
644 * comparator.
645 */
646 i = -i;
647 op = _Py_SwappedOp[op];
648 }
649 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000650 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000651 /* exponent is the # of bits in v before the radix point;
652 * we know that nbits (the # of bits in w) > 48 at this point
653 */
654 if (exponent < 0 || (size_t)exponent < nbits) {
655 i = 1.0;
656 j = 2.0;
657 goto Compare;
658 }
659 if ((size_t)exponent > nbits) {
660 i = 2.0;
661 j = 1.0;
662 goto Compare;
663 }
664 /* v and w have the same number of bits before the radix
665 * point. Construct two longs that have the same comparison
666 * outcome.
667 */
668 {
669 double fracpart;
670 double intpart;
671 PyObject *result = NULL;
672 PyObject *one = NULL;
673 PyObject *vv = NULL;
674 PyObject *ww = w;
675
676 if (wsign < 0) {
677 ww = PyNumber_Negative(w);
678 if (ww == NULL)
679 goto Error;
680 }
681 else
682 Py_INCREF(ww);
683
684 fracpart = modf(i, &intpart);
685 vv = PyLong_FromDouble(intpart);
686 if (vv == NULL)
687 goto Error;
688
689 if (fracpart != 0.0) {
690 /* Shift left, and or a 1 bit into vv
691 * to represent the lost fraction.
692 */
693 PyObject *temp;
694
Christian Heimes217cfd12007-12-02 14:31:20 +0000695 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000696 if (one == NULL)
697 goto Error;
698
699 temp = PyNumber_Lshift(ww, one);
700 if (temp == NULL)
701 goto Error;
702 Py_DECREF(ww);
703 ww = temp;
704
705 temp = PyNumber_Lshift(vv, one);
706 if (temp == NULL)
707 goto Error;
708 Py_DECREF(vv);
709 vv = temp;
710
711 temp = PyNumber_Or(vv, one);
712 if (temp == NULL)
713 goto Error;
714 Py_DECREF(vv);
715 vv = temp;
716 }
717
718 r = PyObject_RichCompareBool(vv, ww, op);
719 if (r < 0)
720 goto Error;
721 result = PyBool_FromLong(r);
722 Error:
723 Py_XDECREF(vv);
724 Py_XDECREF(ww);
725 Py_XDECREF(one);
726 return result;
727 }
728 } /* else if (PyLong_Check(w)) */
729
730 else /* w isn't float, int, or long */
731 goto Unimplemented;
732
733 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000734 PyFPE_START_PROTECT("richcompare", return NULL)
735 switch (op) {
736 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000737 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000738 break;
739 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000740 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000741 break;
742 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000743 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000744 break;
745 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000746 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000747 break;
748 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000749 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000750 break;
751 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000752 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000753 break;
754 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000755 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000756 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000757
758 Unimplemented:
759 Py_INCREF(Py_NotImplemented);
760 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000761}
762
Guido van Rossum9bfef441993-03-29 10:43:31 +0000763static long
Fred Drakefd99de62000-07-09 05:02:18 +0000764float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000765{
Tim Peters39dce292000-08-15 03:34:48 +0000766 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000767}
768
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000770float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000772 double a,b;
773 CONVERT_TO_DOUBLE(v, a);
774 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000775 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000776 a = a + b;
777 PyFPE_END_PROTECT(a)
778 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779}
780
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000781static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000782float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000784 double a,b;
785 CONVERT_TO_DOUBLE(v, a);
786 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000787 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000788 a = a - b;
789 PyFPE_END_PROTECT(a)
790 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000791}
792
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000794float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000796 double a,b;
797 CONVERT_TO_DOUBLE(v, a);
798 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000799 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000800 a = a * b;
801 PyFPE_END_PROTECT(a)
802 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803}
804
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000805static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000806float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000808 double a,b;
809 CONVERT_TO_DOUBLE(v, a);
810 CONVERT_TO_DOUBLE(w, b);
811 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813 return NULL;
814 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000815 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000816 a = a / b;
817 PyFPE_END_PROTECT(a)
818 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819}
820
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000821static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000822float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000824 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000825 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000826 CONVERT_TO_DOUBLE(v, vx);
827 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000829 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830 return NULL;
831 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000832 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000833 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000834 /* note: checking mod*wx < 0 is incorrect -- underflows to
835 0 if wx < sqrt(smallest nonzero double) */
836 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000837 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000838 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000839 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000841}
842
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000844float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000845{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000846 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000847 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000848 CONVERT_TO_DOUBLE(v, vx);
849 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000850 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000851 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000852 return NULL;
853 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000854 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000855 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000856 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000857 exact multiple of wx. But this is fp arithmetic, and fp
858 vx - mod is an approximation; the result is that div may
859 not be an exact integral value after the division, although
860 it will always be very close to one.
861 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000862 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000863 if (mod) {
864 /* ensure the remainder has the same sign as the denominator */
865 if ((wx < 0) != (mod < 0)) {
866 mod += wx;
867 div -= 1.0;
868 }
869 }
870 else {
871 /* the remainder is zero, and in the presence of signed zeroes
872 fmod returns different results across platforms; ensure
873 it has the same sign as the denominator; we'd like to do
874 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000875 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000876 if (wx < 0.0)
877 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000878 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000879 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000880 if (div) {
881 floordiv = floor(div);
882 if (div - floordiv > 0.5)
883 floordiv += 1.0;
884 }
885 else {
886 /* div is zero - get the same sign as the true quotient */
887 div *= div; /* hide "div = +0" from optimizers */
888 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
889 }
890 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000891 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000892}
893
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000894static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000895float_floor_div(PyObject *v, PyObject *w)
896{
897 PyObject *t, *r;
898
899 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000900 if (t == NULL || t == Py_NotImplemented)
901 return t;
902 assert(PyTuple_CheckExact(t));
903 r = PyTuple_GET_ITEM(t, 0);
904 Py_INCREF(r);
905 Py_DECREF(t);
906 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000907}
908
909static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000910float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000911{
912 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000913
914 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000915 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000916 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000917 return NULL;
918 }
919
Neil Schemenauer32117e52001-01-04 01:44:34 +0000920 CONVERT_TO_DOUBLE(v, iv);
921 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000922
923 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000924 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000925 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000926 }
Tim Peters96685bf2001-08-23 22:31:37 +0000927 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000928 if (iw < 0.0) {
929 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000930 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000931 return NULL;
932 }
933 return PyFloat_FromDouble(0.0);
934 }
Tim Peterse87568d2003-05-24 20:18:24 +0000935 if (iv < 0.0) {
936 /* Whether this is an error is a mess, and bumps into libm
937 * bugs so we have to figure it out ourselves.
938 */
939 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000940 /* Negative numbers raised to fractional powers
941 * become complex.
942 */
943 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000944 }
945 /* iw is an exact integer, albeit perhaps a very large one.
946 * -1 raised to an exact integer should never be exceptional.
947 * Alas, some libms (chiefly glibc as of early 2003) return
948 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
949 * happen to be representable in a *C* integer. That's a
950 * bug; we let that slide in math.pow() (which currently
951 * reflects all platform accidents), but not for Python's **.
952 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000953 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000954 /* Return 1 if iw is even, -1 if iw is odd; there's
955 * no guarantee that any C integral type is big
956 * enough to hold iw, so we have to check this
957 * indirectly.
958 */
959 ix = floor(iw * 0.5) * 2.0;
960 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
961 }
962 /* Else iv != -1.0, and overflow or underflow are possible.
963 * Unless we're to write pow() ourselves, we have to trust
964 * the platform to do this correctly.
965 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000966 }
Tim Peters96685bf2001-08-23 22:31:37 +0000967 errno = 0;
968 PyFPE_START_PROTECT("pow", return NULL)
969 ix = pow(iv, iw);
970 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000971 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000972 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000973 /* We don't expect any errno value other than ERANGE, but
974 * the range of libm bugs appears unbounded.
975 */
976 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
977 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000978 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000979 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000980 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000981}
982
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000984float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000985{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000986 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000987}
988
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000990float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000991{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000992 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000993}
994
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000995static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000996float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000997{
998 return v->ob_fval != 0.0;
999}
1000
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001001static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001002float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001003{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001004 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001005 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001006
1007 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001008 /* Try to get out cheap if this fits in a Python int. The attempt
1009 * to cast to long must be protected, as C doesn't define what
1010 * happens if the double is too big to fit in a long. Some rare
1011 * systems raise an exception then (RISCOS was mentioned as one,
1012 * and someone using a non-default option on Sun also bumped into
1013 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1014 * still be vulnerable: if a long has more bits of precision than
1015 * a double, casting MIN/MAX to double may yield an approximation,
1016 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1017 * yield true from the C expression wholepart<=LONG_MAX, despite
1018 * that wholepart is actually greater than LONG_MAX.
1019 */
1020 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1021 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +00001022 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001023 }
1024 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001025}
1026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001027static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001028float_round(PyObject *v, PyObject *args)
1029{
1030#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1031 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001032 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001033 double flr, cil;
1034 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001035 int ndigits = UNDEF_NDIGITS;
1036
1037 if (!PyArg_ParseTuple(args, "|i", &ndigits))
1038 return NULL;
1039
1040 x = PyFloat_AsDouble(v);
1041
1042 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001043 f = pow(10.0, ndigits);
1044 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001045 }
1046
1047 flr = floor(x);
1048 cil = ceil(x);
1049
1050 if (x-flr > 0.5)
1051 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001052 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001053 rounded = fmod(flr, 2) == 0 ? flr : cil;
1054 else
1055 rounded = flr;
1056
1057 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001058 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001059 return PyFloat_FromDouble(rounded);
1060 }
1061
1062 return PyLong_FromDouble(rounded);
1063#undef UNDEF_NDIGITS
1064}
1065
1066static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001067float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001068{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001069 if (PyFloat_CheckExact(v))
1070 Py_INCREF(v);
1071 else
1072 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001073 return v;
1074}
1075
Christian Heimes26855632008-01-27 23:50:43 +00001076static PyObject *
1077float_as_integer_ratio(PyObject *v)
1078{
1079 double self;
1080 double float_part;
1081 int exponent;
1082 int is_negative;
1083 const int chunk_size = 28;
1084 PyObject *prev;
1085 PyObject *py_chunk = NULL;
1086 PyObject *py_exponent = NULL;
1087 PyObject *numerator = NULL;
1088 PyObject *denominator = NULL;
1089 PyObject *result_pair = NULL;
1090 PyNumberMethods *long_methods;
1091
1092#define INPLACE_UPDATE(obj, call) \
1093 prev = obj; \
1094 obj = call; \
1095 Py_DECREF(prev); \
1096
1097 CONVERT_TO_DOUBLE(v, self);
1098
1099 if (Py_IS_INFINITY(self)) {
1100 PyErr_SetString(PyExc_OverflowError,
1101 "Cannot pass infinity to float.as_integer_ratio.");
1102 return NULL;
1103 }
1104#ifdef Py_NAN
1105 if (Py_IS_NAN(self)) {
1106 PyErr_SetString(PyExc_ValueError,
1107 "Cannot pass nan to float.as_integer_ratio.");
1108 return NULL;
1109 }
1110#endif
1111
1112 if (self == 0) {
1113 numerator = PyLong_FromLong(0);
1114 if (numerator == NULL) goto error;
1115 denominator = PyLong_FromLong(1);
1116 if (denominator == NULL) goto error;
1117 result_pair = PyTuple_Pack(2, numerator, denominator);
1118 /* Hand ownership over to the tuple. If the tuple
1119 wasn't created successfully, we want to delete the
1120 ints anyway. */
1121 Py_DECREF(numerator);
1122 Py_DECREF(denominator);
1123 return result_pair;
1124 }
1125
1126 /* XXX: Could perhaps handle FLT_RADIX!=2 by using ilogb and
1127 scalbn, but those may not be in C89. */
1128 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1129 float_part = frexp(self, &exponent);
1130 is_negative = 0;
1131 if (float_part < 0) {
1132 float_part = -float_part;
1133 is_negative = 1;
1134 /* 0.5 <= float_part < 1.0 */
1135 }
1136 PyFPE_END_PROTECT(float_part);
1137 /* abs(self) == float_part * 2**exponent exactly */
1138
1139 /* Suck up chunk_size bits at a time; 28 is enough so that we
1140 suck up all bits in 2 iterations for all known binary
1141 double-precision formats, and small enough to fit in a
1142 long. */
1143 numerator = PyLong_FromLong(0);
1144 if (numerator == NULL) goto error;
1145
1146 long_methods = PyLong_Type.tp_as_number;
1147
1148 py_chunk = PyLong_FromLong(chunk_size);
1149 if (py_chunk == NULL) goto error;
1150
1151 while (float_part != 0) {
1152 /* invariant: abs(self) ==
1153 (numerator + float_part) * 2**exponent exactly */
1154 long digit;
1155 PyObject *py_digit;
1156
1157 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1158 /* Pull chunk_size bits out of float_part, into digits. */
1159 float_part = ldexp(float_part, chunk_size);
1160 digit = (long)float_part;
1161 float_part -= digit;
1162 /* 0 <= float_part < 1 */
1163 exponent -= chunk_size;
1164 PyFPE_END_PROTECT(float_part);
1165
1166 /* Shift digits into numerator. */
1167 // numerator <<= chunk_size
1168 INPLACE_UPDATE(numerator,
1169 long_methods->nb_lshift(numerator, py_chunk));
1170 if (numerator == NULL) goto error;
1171
1172 // numerator |= digit
1173 py_digit = PyLong_FromLong(digit);
1174 if (py_digit == NULL) goto error;
1175 INPLACE_UPDATE(numerator,
1176 long_methods->nb_or(numerator, py_digit));
1177 Py_DECREF(py_digit);
1178 if (numerator == NULL) goto error;
1179 }
1180
1181 /* Add in the sign bit. */
1182 if (is_negative) {
1183 INPLACE_UPDATE(numerator,
1184 long_methods->nb_negative(numerator));
1185 if (numerator == NULL) goto error;
1186 }
1187
1188 /* now self = numerator * 2**exponent exactly; fold in 2**exponent */
1189 denominator = PyLong_FromLong(1);
1190 py_exponent = PyLong_FromLong(labs(exponent));
1191 if (py_exponent == NULL) goto error;
1192 INPLACE_UPDATE(py_exponent,
1193 long_methods->nb_lshift(denominator, py_exponent));
1194 if (py_exponent == NULL) goto error;
1195 if (exponent > 0) {
1196 INPLACE_UPDATE(numerator,
1197 long_methods->nb_multiply(numerator,
1198 py_exponent));
1199 if (numerator == NULL) goto error;
1200 }
1201 else {
1202 Py_DECREF(denominator);
1203 denominator = py_exponent;
1204 py_exponent = NULL;
1205 }
1206
1207 result_pair = PyTuple_Pack(2, numerator, denominator);
1208
1209#undef INPLACE_UPDATE
1210error:
1211 Py_XDECREF(py_exponent);
1212 Py_XDECREF(py_chunk);
1213 Py_XDECREF(denominator);
1214 Py_XDECREF(numerator);
1215 return result_pair;
1216}
1217
1218PyDoc_STRVAR(float_as_integer_ratio_doc,
1219"float.as_integer_ratio() -> (int, int)\n"
1220"\n"
1221"Returns a pair of integers, not necessarily in lowest terms, whose\n"
1222"ratio is exactly equal to the original float. This method raises an\n"
1223"OverflowError on infinities and a ValueError on nans. The resulting\n"
1224"denominator will be positive.\n"
1225"\n"
1226">>> (10.0).as_integer_ratio()\n"
1227"(167772160L, 16777216L)\n"
1228">>> (0.0).as_integer_ratio()\n"
1229"(0, 1)\n"
1230">>> (-.25).as_integer_ratio()\n"
1231"(-134217728L, 536870912L)");
1232
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001233
Jeremy Hylton938ace62002-07-17 16:30:39 +00001234static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001235float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237static PyObject *
1238float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1239{
1240 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001241 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242
Guido van Rossumbef14172001-08-29 15:47:46 +00001243 if (type != &PyFloat_Type)
1244 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1246 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001247 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001248 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 return PyNumber_Float(x);
1250}
1251
Guido van Rossumbef14172001-08-29 15:47:46 +00001252/* Wimpy, slow approach to tp_new calls for subtypes of float:
1253 first create a regular float from whatever arguments we got,
1254 then allocate a subtype instance and initialize its ob_fval
1255 from the regular float. The regular float is then thrown away.
1256*/
1257static PyObject *
1258float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1259{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001260 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001261
1262 assert(PyType_IsSubtype(type, &PyFloat_Type));
1263 tmp = float_new(&PyFloat_Type, args, kwds);
1264 if (tmp == NULL)
1265 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001266 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001267 newobj = type->tp_alloc(type, 0);
1268 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001269 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001270 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001271 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001272 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001273 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001274 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001275}
1276
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001277static PyObject *
1278float_getnewargs(PyFloatObject *v)
1279{
1280 return Py_BuildValue("(d)", v->ob_fval);
1281}
1282
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001283/* this is for the benefit of the pack/unpack routines below */
1284
1285typedef enum {
1286 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1287} float_format_type;
1288
1289static float_format_type double_format, float_format;
1290static float_format_type detected_double_format, detected_float_format;
1291
1292static PyObject *
1293float_getformat(PyTypeObject *v, PyObject* arg)
1294{
1295 char* s;
1296 float_format_type r;
1297
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001298 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001299 PyErr_Format(PyExc_TypeError,
1300 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001301 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001302 return NULL;
1303 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001304 s = PyUnicode_AsString(arg);
1305 if (s == NULL)
1306 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001307 if (strcmp(s, "double") == 0) {
1308 r = double_format;
1309 }
1310 else if (strcmp(s, "float") == 0) {
1311 r = float_format;
1312 }
1313 else {
1314 PyErr_SetString(PyExc_ValueError,
1315 "__getformat__() argument 1 must be "
1316 "'double' or 'float'");
1317 return NULL;
1318 }
1319
1320 switch (r) {
1321 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001322 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001323 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001324 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001325 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001326 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001327 default:
1328 Py_FatalError("insane float_format or double_format");
1329 return NULL;
1330 }
1331}
1332
1333PyDoc_STRVAR(float_getformat_doc,
1334"float.__getformat__(typestr) -> string\n"
1335"\n"
1336"You probably don't want to use this function. It exists mainly to be\n"
1337"used in Python's test suite.\n"
1338"\n"
1339"typestr must be 'double' or 'float'. This function returns whichever of\n"
1340"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1341"format of floating point numbers used by the C type named by typestr.");
1342
1343static PyObject *
1344float_setformat(PyTypeObject *v, PyObject* args)
1345{
1346 char* typestr;
1347 char* format;
1348 float_format_type f;
1349 float_format_type detected;
1350 float_format_type *p;
1351
1352 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1353 return NULL;
1354
1355 if (strcmp(typestr, "double") == 0) {
1356 p = &double_format;
1357 detected = detected_double_format;
1358 }
1359 else if (strcmp(typestr, "float") == 0) {
1360 p = &float_format;
1361 detected = detected_float_format;
1362 }
1363 else {
1364 PyErr_SetString(PyExc_ValueError,
1365 "__setformat__() argument 1 must "
1366 "be 'double' or 'float'");
1367 return NULL;
1368 }
1369
1370 if (strcmp(format, "unknown") == 0) {
1371 f = unknown_format;
1372 }
1373 else if (strcmp(format, "IEEE, little-endian") == 0) {
1374 f = ieee_little_endian_format;
1375 }
1376 else if (strcmp(format, "IEEE, big-endian") == 0) {
1377 f = ieee_big_endian_format;
1378 }
1379 else {
1380 PyErr_SetString(PyExc_ValueError,
1381 "__setformat__() argument 2 must be "
1382 "'unknown', 'IEEE, little-endian' or "
1383 "'IEEE, big-endian'");
1384 return NULL;
1385
1386 }
1387
1388 if (f != unknown_format && f != detected) {
1389 PyErr_Format(PyExc_ValueError,
1390 "can only set %s format to 'unknown' or the "
1391 "detected platform value", typestr);
1392 return NULL;
1393 }
1394
1395 *p = f;
1396 Py_RETURN_NONE;
1397}
1398
1399PyDoc_STRVAR(float_setformat_doc,
1400"float.__setformat__(typestr, fmt) -> None\n"
1401"\n"
1402"You probably don't want to use this function. It exists mainly to be\n"
1403"used in Python's test suite.\n"
1404"\n"
1405"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1406"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1407"one of the latter two if it appears to match the underlying C reality.\n"
1408"\n"
1409"Overrides the automatic determination of C-level floating point type.\n"
1410"This affects how floats are converted to and from binary strings.");
1411
Guido van Rossumb43daf72007-08-01 18:08:08 +00001412static PyObject *
1413float_getzero(PyObject *v, void *closure)
1414{
1415 return PyFloat_FromDouble(0.0);
1416}
1417
Eric Smith8c663262007-08-25 02:26:07 +00001418static PyObject *
1419float__format__(PyObject *self, PyObject *args)
1420{
1421 /* when back porting this to 2.6, check type of the format_spec
1422 and call either unicode_long__format__ or
1423 string_long__format__ */
1424 return unicode_float__format__(self, args);
1425}
1426
1427PyDoc_STRVAR(float__format__doc,
1428"float.__format__(format_spec) -> string\n"
1429"\n"
1430"Formats the float according to format_spec.");
1431
1432
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001433static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001434 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1435 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001436 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1437 "Returns the Integral closest to x between 0 and x."},
1438 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1439 "Returns the Integral closest to x, rounding half toward even.\n"
1440 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001441 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1442 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001443 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001444 {"__getformat__", (PyCFunction)float_getformat,
1445 METH_O|METH_CLASS, float_getformat_doc},
1446 {"__setformat__", (PyCFunction)float_setformat,
1447 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001448 {"__format__", (PyCFunction)float__format__,
1449 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001450 {NULL, NULL} /* sentinel */
1451};
1452
Guido van Rossumb43daf72007-08-01 18:08:08 +00001453static PyGetSetDef float_getset[] = {
1454 {"real",
1455 (getter)float_float, (setter)NULL,
1456 "the real part of a complex number",
1457 NULL},
1458 {"imag",
1459 (getter)float_getzero, (setter)NULL,
1460 "the imaginary part of a complex number",
1461 NULL},
1462 {NULL} /* Sentinel */
1463};
1464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001465PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466"float(x) -> floating point number\n\
1467\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001468Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001469
1470
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001471static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001472 float_add, /*nb_add*/
1473 float_sub, /*nb_subtract*/
1474 float_mul, /*nb_multiply*/
1475 float_rem, /*nb_remainder*/
1476 float_divmod, /*nb_divmod*/
1477 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001478 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001479 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001480 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001481 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001482 0, /*nb_invert*/
1483 0, /*nb_lshift*/
1484 0, /*nb_rshift*/
1485 0, /*nb_and*/
1486 0, /*nb_xor*/
1487 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001488 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001489 float_trunc, /*nb_int*/
1490 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001491 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001492 0, /* nb_oct */
1493 0, /* nb_hex */
1494 0, /* nb_inplace_add */
1495 0, /* nb_inplace_subtract */
1496 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001497 0, /* nb_inplace_remainder */
1498 0, /* nb_inplace_power */
1499 0, /* nb_inplace_lshift */
1500 0, /* nb_inplace_rshift */
1501 0, /* nb_inplace_and */
1502 0, /* nb_inplace_xor */
1503 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001504 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001505 float_div, /* nb_true_divide */
1506 0, /* nb_inplace_floor_divide */
1507 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001508};
1509
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001510PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001511 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001512 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001514 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001516 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517 0, /* tp_getattr */
1518 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001519 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 (reprfunc)float_repr, /* tp_repr */
1521 &float_as_number, /* tp_as_number */
1522 0, /* tp_as_sequence */
1523 0, /* tp_as_mapping */
1524 (hashfunc)float_hash, /* tp_hash */
1525 0, /* tp_call */
1526 (reprfunc)float_str, /* tp_str */
1527 PyObject_GenericGetAttr, /* tp_getattro */
1528 0, /* tp_setattro */
1529 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001530 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531 float_doc, /* tp_doc */
1532 0, /* tp_traverse */
1533 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001534 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 0, /* tp_weaklistoffset */
1536 0, /* tp_iter */
1537 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001538 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001540 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 0, /* tp_base */
1542 0, /* tp_dict */
1543 0, /* tp_descr_get */
1544 0, /* tp_descr_set */
1545 0, /* tp_dictoffset */
1546 0, /* tp_init */
1547 0, /* tp_alloc */
1548 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001549};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001550
1551void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001552_PyFloat_Init(void)
1553{
1554 /* We attempt to determine if this machine is using IEEE
1555 floating point formats by peering at the bits of some
1556 carefully chosen values. If it looks like we are on an
1557 IEEE platform, the float packing/unpacking routines can
1558 just copy bits, if not they resort to arithmetic & shifts
1559 and masks. The shifts & masks approach works on all finite
1560 values, but what happens to infinities, NaNs and signed
1561 zeroes on packing is an accident, and attempting to unpack
1562 a NaN or an infinity will raise an exception.
1563
1564 Note that if we're on some whacked-out platform which uses
1565 IEEE formats but isn't strictly little-endian or big-
1566 endian, we will fall back to the portable shifts & masks
1567 method. */
1568
1569#if SIZEOF_DOUBLE == 8
1570 {
1571 double x = 9006104071832581.0;
1572 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1573 detected_double_format = ieee_big_endian_format;
1574 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1575 detected_double_format = ieee_little_endian_format;
1576 else
1577 detected_double_format = unknown_format;
1578 }
1579#else
1580 detected_double_format = unknown_format;
1581#endif
1582
1583#if SIZEOF_FLOAT == 4
1584 {
1585 float y = 16711938.0;
1586 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1587 detected_float_format = ieee_big_endian_format;
1588 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1589 detected_float_format = ieee_little_endian_format;
1590 else
1591 detected_float_format = unknown_format;
1592 }
1593#else
1594 detected_float_format = unknown_format;
1595#endif
1596
1597 double_format = detected_double_format;
1598 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001599
1600#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001601 /* Initialize floating point repr */
1602 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001603#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001604}
1605
1606void
Fred Drakefd99de62000-07-09 05:02:18 +00001607PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001608{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001609 PyFloatObject *p;
1610 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001611 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001612 int bc, bf; /* block count, number of freed blocks */
1613 int frem, fsum; /* remaining unfreed floats per block, total */
1614
1615 bc = 0;
1616 bf = 0;
1617 fsum = 0;
1618 list = block_list;
1619 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001620 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001621 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001622 bc++;
1623 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001624 for (i = 0, p = &list->objects[0];
1625 i < N_FLOATOBJECTS;
1626 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001627 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001628 frem++;
1629 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001630 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001631 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001632 list->next = block_list;
1633 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001634 for (i = 0, p = &list->objects[0];
1635 i < N_FLOATOBJECTS;
1636 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001637 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001638 Py_REFCNT(p) == 0) {
1639 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001640 free_list;
1641 free_list = p;
1642 }
1643 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001644 }
1645 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001646 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001647 bf++;
1648 }
1649 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001650 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001651 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001652 if (!Py_VerboseFlag)
1653 return;
1654 fprintf(stderr, "# cleanup floats");
1655 if (!fsum) {
1656 fprintf(stderr, "\n");
1657 }
1658 else {
1659 fprintf(stderr,
1660 ": %d unfreed float%s in %d out of %d block%s\n",
1661 fsum, fsum == 1 ? "" : "s",
1662 bc - bf, bc, bc == 1 ? "" : "s");
1663 }
1664 if (Py_VerboseFlag > 1) {
1665 list = block_list;
1666 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001667 for (i = 0, p = &list->objects[0];
1668 i < N_FLOATOBJECTS;
1669 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001670 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001671 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001672 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001673 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001674 /* XXX(twouters) cast refcount to
1675 long until %zd is universally
1676 available
1677 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001678 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001679 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001680 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001681 }
1682 }
1683 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001684 }
1685 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001686}
Tim Peters9905b942003-03-20 20:53:32 +00001687
1688/*----------------------------------------------------------------------------
1689 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1690 *
1691 * TODO: On platforms that use the standard IEEE-754 single and double
1692 * formats natively, these routines could simply copy the bytes.
1693 */
1694int
1695_PyFloat_Pack4(double x, unsigned char *p, int le)
1696{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001697 if (float_format == unknown_format) {
1698 unsigned char sign;
1699 int e;
1700 double f;
1701 unsigned int fbits;
1702 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001703
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001704 if (le) {
1705 p += 3;
1706 incr = -1;
1707 }
Tim Peters9905b942003-03-20 20:53:32 +00001708
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001709 if (x < 0) {
1710 sign = 1;
1711 x = -x;
1712 }
1713 else
1714 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001715
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001717
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001718 /* Normalize f to be in the range [1.0, 2.0) */
1719 if (0.5 <= f && f < 1.0) {
1720 f *= 2.0;
1721 e--;
1722 }
1723 else if (f == 0.0)
1724 e = 0;
1725 else {
1726 PyErr_SetString(PyExc_SystemError,
1727 "frexp() result out of range");
1728 return -1;
1729 }
1730
1731 if (e >= 128)
1732 goto Overflow;
1733 else if (e < -126) {
1734 /* Gradual underflow */
1735 f = ldexp(f, 126 + e);
1736 e = 0;
1737 }
1738 else if (!(e == 0 && f == 0.0)) {
1739 e += 127;
1740 f -= 1.0; /* Get rid of leading 1 */
1741 }
1742
1743 f *= 8388608.0; /* 2**23 */
1744 fbits = (unsigned int)(f + 0.5); /* Round */
1745 assert(fbits <= 8388608);
1746 if (fbits >> 23) {
1747 /* The carry propagated out of a string of 23 1 bits. */
1748 fbits = 0;
1749 ++e;
1750 if (e >= 255)
1751 goto Overflow;
1752 }
1753
1754 /* First byte */
1755 *p = (sign << 7) | (e >> 1);
1756 p += incr;
1757
1758 /* Second byte */
1759 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1760 p += incr;
1761
1762 /* Third byte */
1763 *p = (fbits >> 8) & 0xFF;
1764 p += incr;
1765
1766 /* Fourth byte */
1767 *p = fbits & 0xFF;
1768
1769 /* Done */
1770 return 0;
1771
1772 Overflow:
1773 PyErr_SetString(PyExc_OverflowError,
1774 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001775 return -1;
1776 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001778 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001779 const char *s = (char*)&y;
1780 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001781
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001782 if ((float_format == ieee_little_endian_format && !le)
1783 || (float_format == ieee_big_endian_format && le)) {
1784 p += 3;
1785 incr = -1;
1786 }
1787
1788 for (i = 0; i < 4; i++) {
1789 *p = *s++;
1790 p += incr;
1791 }
1792 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001793 }
Tim Peters9905b942003-03-20 20:53:32 +00001794}
1795
1796int
1797_PyFloat_Pack8(double x, unsigned char *p, int le)
1798{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001799 if (double_format == unknown_format) {
1800 unsigned char sign;
1801 int e;
1802 double f;
1803 unsigned int fhi, flo;
1804 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001805
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001806 if (le) {
1807 p += 7;
1808 incr = -1;
1809 }
Tim Peters9905b942003-03-20 20:53:32 +00001810
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001811 if (x < 0) {
1812 sign = 1;
1813 x = -x;
1814 }
1815 else
1816 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001817
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001818 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001819
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001820 /* Normalize f to be in the range [1.0, 2.0) */
1821 if (0.5 <= f && f < 1.0) {
1822 f *= 2.0;
1823 e--;
1824 }
1825 else if (f == 0.0)
1826 e = 0;
1827 else {
1828 PyErr_SetString(PyExc_SystemError,
1829 "frexp() result out of range");
1830 return -1;
1831 }
1832
1833 if (e >= 1024)
1834 goto Overflow;
1835 else if (e < -1022) {
1836 /* Gradual underflow */
1837 f = ldexp(f, 1022 + e);
1838 e = 0;
1839 }
1840 else if (!(e == 0 && f == 0.0)) {
1841 e += 1023;
1842 f -= 1.0; /* Get rid of leading 1 */
1843 }
1844
1845 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1846 f *= 268435456.0; /* 2**28 */
1847 fhi = (unsigned int)f; /* Truncate */
1848 assert(fhi < 268435456);
1849
1850 f -= (double)fhi;
1851 f *= 16777216.0; /* 2**24 */
1852 flo = (unsigned int)(f + 0.5); /* Round */
1853 assert(flo <= 16777216);
1854 if (flo >> 24) {
1855 /* The carry propagated out of a string of 24 1 bits. */
1856 flo = 0;
1857 ++fhi;
1858 if (fhi >> 28) {
1859 /* And it also progagated out of the next 28 bits. */
1860 fhi = 0;
1861 ++e;
1862 if (e >= 2047)
1863 goto Overflow;
1864 }
1865 }
1866
1867 /* First byte */
1868 *p = (sign << 7) | (e >> 4);
1869 p += incr;
1870
1871 /* Second byte */
1872 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1873 p += incr;
1874
1875 /* Third byte */
1876 *p = (fhi >> 16) & 0xFF;
1877 p += incr;
1878
1879 /* Fourth byte */
1880 *p = (fhi >> 8) & 0xFF;
1881 p += incr;
1882
1883 /* Fifth byte */
1884 *p = fhi & 0xFF;
1885 p += incr;
1886
1887 /* Sixth byte */
1888 *p = (flo >> 16) & 0xFF;
1889 p += incr;
1890
1891 /* Seventh byte */
1892 *p = (flo >> 8) & 0xFF;
1893 p += incr;
1894
1895 /* Eighth byte */
1896 *p = flo & 0xFF;
1897 p += incr;
1898
1899 /* Done */
1900 return 0;
1901
1902 Overflow:
1903 PyErr_SetString(PyExc_OverflowError,
1904 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001905 return -1;
1906 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001907 else {
1908 const char *s = (char*)&x;
1909 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001910
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001911 if ((double_format == ieee_little_endian_format && !le)
1912 || (double_format == ieee_big_endian_format && le)) {
1913 p += 7;
1914 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001915 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001916
1917 for (i = 0; i < 8; i++) {
1918 *p = *s++;
1919 p += incr;
1920 }
1921 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001922 }
Tim Peters9905b942003-03-20 20:53:32 +00001923}
1924
Neal Norwitz545686b2006-12-28 04:45:06 +00001925/* Should only be used by marshal. */
1926int
1927_PyFloat_Repr(double x, char *p, size_t len)
1928{
1929 format_double(p, len, x, PREC_REPR);
1930 return (int)strlen(p);
1931}
1932
Tim Peters9905b942003-03-20 20:53:32 +00001933double
1934_PyFloat_Unpack4(const unsigned char *p, int le)
1935{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936 if (float_format == unknown_format) {
1937 unsigned char sign;
1938 int e;
1939 unsigned int f;
1940 double x;
1941 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001942
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943 if (le) {
1944 p += 3;
1945 incr = -1;
1946 }
1947
1948 /* First byte */
1949 sign = (*p >> 7) & 1;
1950 e = (*p & 0x7F) << 1;
1951 p += incr;
1952
1953 /* Second byte */
1954 e |= (*p >> 7) & 1;
1955 f = (*p & 0x7F) << 16;
1956 p += incr;
1957
1958 if (e == 255) {
1959 PyErr_SetString(
1960 PyExc_ValueError,
1961 "can't unpack IEEE 754 special value "
1962 "on non-IEEE platform");
1963 return -1;
1964 }
1965
1966 /* Third byte */
1967 f |= *p << 8;
1968 p += incr;
1969
1970 /* Fourth byte */
1971 f |= *p;
1972
1973 x = (double)f / 8388608.0;
1974
1975 /* XXX This sadly ignores Inf/NaN issues */
1976 if (e == 0)
1977 e = -126;
1978 else {
1979 x += 1.0;
1980 e -= 127;
1981 }
1982 x = ldexp(x, e);
1983
1984 if (sign)
1985 x = -x;
1986
1987 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001988 }
Tim Peters9905b942003-03-20 20:53:32 +00001989 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001990 float x;
1991
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001992 if ((float_format == ieee_little_endian_format && !le)
1993 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001994 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001995 char *d = &buf[3];
1996 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001997
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001998 for (i = 0; i < 4; i++) {
1999 *d-- = *p++;
2000 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002001 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002002 }
2003 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002004 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002005 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002006
2007 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002008 }
Tim Peters9905b942003-03-20 20:53:32 +00002009}
2010
2011double
2012_PyFloat_Unpack8(const unsigned char *p, int le)
2013{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002014 if (double_format == unknown_format) {
2015 unsigned char sign;
2016 int e;
2017 unsigned int fhi, flo;
2018 double x;
2019 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002020
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002021 if (le) {
2022 p += 7;
2023 incr = -1;
2024 }
2025
2026 /* First byte */
2027 sign = (*p >> 7) & 1;
2028 e = (*p & 0x7F) << 4;
2029
2030 p += incr;
2031
2032 /* Second byte */
2033 e |= (*p >> 4) & 0xF;
2034 fhi = (*p & 0xF) << 24;
2035 p += incr;
2036
2037 if (e == 2047) {
2038 PyErr_SetString(
2039 PyExc_ValueError,
2040 "can't unpack IEEE 754 special value "
2041 "on non-IEEE platform");
2042 return -1.0;
2043 }
2044
2045 /* Third byte */
2046 fhi |= *p << 16;
2047 p += incr;
2048
2049 /* Fourth byte */
2050 fhi |= *p << 8;
2051 p += incr;
2052
2053 /* Fifth byte */
2054 fhi |= *p;
2055 p += incr;
2056
2057 /* Sixth byte */
2058 flo = *p << 16;
2059 p += incr;
2060
2061 /* Seventh byte */
2062 flo |= *p << 8;
2063 p += incr;
2064
2065 /* Eighth byte */
2066 flo |= *p;
2067
2068 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2069 x /= 268435456.0; /* 2**28 */
2070
2071 if (e == 0)
2072 e = -1022;
2073 else {
2074 x += 1.0;
2075 e -= 1023;
2076 }
2077 x = ldexp(x, e);
2078
2079 if (sign)
2080 x = -x;
2081
2082 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002083 }
Tim Peters9905b942003-03-20 20:53:32 +00002084 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002085 double x;
2086
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002087 if ((double_format == ieee_little_endian_format && !le)
2088 || (double_format == ieee_big_endian_format && le)) {
2089 char buf[8];
2090 char *d = &buf[7];
2091 int i;
2092
2093 for (i = 0; i < 8; i++) {
2094 *d-- = *p++;
2095 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002096 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002097 }
2098 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002099 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002100 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002101
2102 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002103 }
Tim Peters9905b942003-03-20 20:53:32 +00002104}