blob: 2465fa959a3cfbb482b3551db8b11b588fa076f1 [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
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Christian Heimesbbe741d2008-03-28 10:53:29 +000013#ifdef HAVE_IEEEFP_H
14#include <ieeefp.h>
15#endif
16
Guido van Rossum6923e131990-11-02 17:50:43 +000017
Christian Heimes969fe572008-01-25 11:23:10 +000018#ifdef _OSF_SOURCE
19/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20extern int finite(double);
21#endif
22
Guido van Rossum93ad0df1997-05-13 21:00:42 +000023/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000025#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000026#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000027
Guido van Rossum3fce8831999-03-12 19:43:17 +000028struct _floatblock {
29 struct _floatblock *next;
30 PyFloatObject objects[N_FLOATOBJECTS];
31};
32
33typedef struct _floatblock PyFloatBlock;
34
35static PyFloatBlock *block_list = NULL;
36static PyFloatObject *free_list = NULL;
37
Guido van Rossum93ad0df1997-05-13 21:00:42 +000038static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000039fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040{
41 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000042 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
43 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000045 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000046 ((PyFloatBlock *)p)->next = block_list;
47 block_list = (PyFloatBlock *)p;
48 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000049 q = p + N_FLOATOBJECTS;
50 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000051 Py_TYPE(q) = (struct _typeobject *)(q-1);
52 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053 return p + N_FLOATOBJECTS - 1;
54}
55
Christian Heimes93852662007-12-01 12:22:32 +000056double
57PyFloat_GetMax(void)
58{
59 return DBL_MAX;
60}
61
62double
63PyFloat_GetMin(void)
64{
65 return DBL_MIN;
66}
67
Christian Heimesd32ed6f2008-01-14 18:49:24 +000068static PyTypeObject FloatInfoType;
69
70PyDoc_STRVAR(floatinfo__doc__,
71"sys.floatinfo\n\
72\n\
73A structseq holding information about the float type. It contains low level\n\
74information about the precision and internal representation. Please study\n\
75your system's :file:`float.h` for more information.");
76
77static PyStructSequence_Field floatinfo_fields[] = {
78 {"max", "DBL_MAX -- maximum representable finite float"},
79 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
80 "is representable"},
81 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
82 "is representable"},
83 {"min", "DBL_MIN -- Minimum positive normalizer float"},
84 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
85 "is a normalized float"},
86 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
87 "a normalized"},
88 {"dig", "DBL_DIG -- digits"},
89 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
90 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
91 "representable float"},
92 {"radix", "FLT_RADIX -- radix of exponent"},
93 {"rounds", "FLT_ROUNDS -- addition rounds"},
94 {0}
95};
96
97static PyStructSequence_Desc floatinfo_desc = {
98 "sys.floatinfo", /* name */
99 floatinfo__doc__, /* doc */
100 floatinfo_fields, /* fields */
101 11
102};
103
Christian Heimes93852662007-12-01 12:22:32 +0000104PyObject *
105PyFloat_GetInfo(void)
106{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000107 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000108 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000109
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000110 floatinfo = PyStructSequence_New(&FloatInfoType);
111 if (floatinfo == NULL) {
112 return NULL;
113 }
Christian Heimes93852662007-12-01 12:22:32 +0000114
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000115#define SetIntFlag(flag) \
116 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
117#define SetDblFlag(flag) \
118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000119
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000120 SetDblFlag(DBL_MAX);
121 SetIntFlag(DBL_MAX_EXP);
122 SetIntFlag(DBL_MAX_10_EXP);
123 SetDblFlag(DBL_MIN);
124 SetIntFlag(DBL_MIN_EXP);
125 SetIntFlag(DBL_MIN_10_EXP);
126 SetIntFlag(DBL_DIG);
127 SetIntFlag(DBL_MANT_DIG);
128 SetDblFlag(DBL_EPSILON);
129 SetIntFlag(FLT_RADIX);
130 SetIntFlag(FLT_ROUNDS);
131#undef SetIntFlag
132#undef SetDblFlag
133
134 if (PyErr_Occurred()) {
135 Py_CLEAR(floatinfo);
136 return NULL;
137 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000138 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000139}
140
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000144 register PyFloatObject *op;
145 if (free_list == NULL) {
146 if ((free_list = fill_free_list()) == NULL)
147 return NULL;
148 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000149 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000150 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000151 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000152 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000153 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000154 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
156
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000157PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000158PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159{
Christian Heimes99170a52007-12-19 02:07:34 +0000160 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000161 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000162 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000163 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000164 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000165 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000167 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000168 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
169 if (s_buffer == NULL)
170 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000171 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000172 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000173 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000174 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000175 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000176 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000177 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000178 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000179 else if (PyObject_AsCharBuffer(v, &s, &len)) {
180 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000181 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000183 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184
Guido van Rossum4c08d552000-03-10 22:55:18 +0000185 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000186 while (*s && isspace(Py_CHARMASK(*s)))
187 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000188 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000189 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000190 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191 }
Christian Heimes99170a52007-12-19 02:07:34 +0000192 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000193 /* We don't care about overflow or underflow. If the platform supports
194 * them, infinities and signed zeroes (on underflow) are fine.
195 * However, strtod can return 0 for denormalized numbers, where atof
196 * does not. So (alas!) we special-case a zero result. Note that
197 * whether strtod sets errno on underflow is not defined, so we can't
198 * key off errno.
199 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000200 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000201 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000202 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000203 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000204 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000205 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000206 if (end > last)
207 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000208 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000209 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000210 char *p = (char*)sp;
211 int sign = 1;
212
213 if (*p == '-') {
214 sign = -1;
215 p++;
216 }
217 if (*p == '+') {
218 p++;
219 }
220 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000221 Py_RETURN_INF(sign);
Christian Heimes99170a52007-12-19 02:07:34 +0000222 }
223#ifdef Py_NAN
224 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000225 Py_RETURN_NAN;
Christian Heimes99170a52007-12-19 02:07:34 +0000226 }
227#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000228 PyOS_snprintf(buffer, sizeof(buffer),
229 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000230 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000231 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000232 }
233 /* Since end != s, the platform made *some* kind of sense out
234 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000235 while (*end && isspace(Py_CHARMASK(*end)))
236 end++;
237 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000238 PyOS_snprintf(buffer, sizeof(buffer),
239 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000240 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000241 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000242 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000243 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000244 PyErr_SetString(PyExc_ValueError,
245 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000246 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000247 }
Tim Petersef14d732000-09-23 03:39:17 +0000248 if (x == 0.0) {
249 /* See above -- may have been strtod being anal
250 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000251 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000252 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000253 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000254 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000255 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000256 result = PyFloat_FromDouble(x);
257 error:
258 if (s_buffer)
259 PyMem_FREE(s_buffer);
260 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000261}
262
Guido van Rossum234f9421993-06-17 12:35:49 +0000263static void
Fred Drakefd99de62000-07-09 05:02:18 +0000264float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000265{
Guido van Rossum9475a232001-10-05 20:51:39 +0000266 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000267 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000268 free_list = op;
269 }
270 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000271 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000272}
273
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000274double
Fred Drakefd99de62000-07-09 05:02:18 +0000275PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 PyNumberMethods *nb;
278 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000280
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 if (op && PyFloat_Check(op))
282 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000283
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000284 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286 return -1;
287 }
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Christian Heimes90aa7642007-12-19 02:45:37 +0000289 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000290 PyErr_SetString(PyExc_TypeError, "a float is required");
291 return -1;
292 }
293
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000295 if (fo == NULL)
296 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000297 if (!PyFloat_Check(fo)) {
298 PyErr_SetString(PyExc_TypeError,
299 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300 return -1;
301 }
Tim Petersd2364e82001-11-01 20:09:42 +0000302
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303 val = PyFloat_AS_DOUBLE(fo);
304 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000305
Guido van Rossumb6775db1994-08-01 11:34:53 +0000306 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307}
308
309/* Methods */
310
Tim Peters97019e42001-11-28 22:43:45 +0000311static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000312format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
314 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000315 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000316 int i;
317
318 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319 We want float numbers to be recognizable as such,
320 i.e., they should contain a decimal point or an exponent.
321 However, %g may print the number as an integer;
322 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000323
Martin v. Löwis737ea822004-06-08 18:52:54 +0000324 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000325 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326 cp = buf;
327 if (*cp == '-')
328 cp++;
329 for (; *cp != '\0'; cp++) {
330 /* Any non-digit means it's not an integer;
331 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000332 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333 break;
334 }
335 if (*cp == '\0') {
336 *cp++ = '.';
337 *cp++ = '0';
338 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000339 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340 }
Christian Heimes99170a52007-12-19 02:07:34 +0000341 /* Checking the next three chars should be more than enough to
342 * detect inf or nan, even on Windows. We check for inf or nan
343 * at last because they are rare cases.
344 */
345 for (i=0; *cp != '\0' && i<3; cp++, i++) {
346 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
347 continue;
348 /* found something that is neither a digit nor point
349 * it might be a NaN or INF
350 */
351#ifdef Py_NAN
352 if (Py_IS_NAN(ob_fval)) {
353 strcpy(buf, "nan");
354 }
355 else
356#endif
357 if (Py_IS_INFINITY(ob_fval)) {
358 cp = buf;
359 if (*cp == '-')
360 cp++;
361 strcpy(cp, "inf");
362 }
363 break;
364 }
365
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366}
367
Neal Norwitz545686b2006-12-28 04:45:06 +0000368static void
369format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000370{
Neal Norwitz545686b2006-12-28 04:45:06 +0000371 assert(PyFloat_Check(v));
372 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000373}
374
Neil Schemenauer32117e52001-01-04 01:44:34 +0000375/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000376 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000377 set to NULL, and the function invoking this macro returns NULL. If
378 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
379 stored in obj, and returned from the function invoking this macro.
380*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000381#define CONVERT_TO_DOUBLE(obj, dbl) \
382 if (PyFloat_Check(obj)) \
383 dbl = PyFloat_AS_DOUBLE(obj); \
384 else if (convert_to_double(&(obj), &(dbl)) < 0) \
385 return obj;
386
387static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000388convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000389{
390 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000391
Guido van Rossumddefaf32007-01-14 03:31:43 +0000392 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000393 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000394 if (*dbl == -1.0 && PyErr_Occurred()) {
395 *v = NULL;
396 return -1;
397 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000398 }
399 else {
400 Py_INCREF(Py_NotImplemented);
401 *v = Py_NotImplemented;
402 return -1;
403 }
404 return 0;
405}
406
Guido van Rossum57072eb1999-12-23 19:00:28 +0000407/* Precisions used by repr() and str(), respectively.
408
409 The repr() precision (17 significant decimal digits) is the minimal number
410 that is guaranteed to have enough precision so that if the number is read
411 back in the exact same binary value is recreated. This is true for IEEE
412 floating point by design, and also happens to work for all other modern
413 hardware.
414
415 The str() precision is chosen so that in most cases, the rounding noise
416 created by various operations is suppressed, while giving plenty of
417 precision for practical use.
418
419*/
420
421#define PREC_REPR 17
422#define PREC_STR 12
423
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000425float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426{
Christian Heimesb76922a2007-12-11 01:06:40 +0000427 char buf[100];
428 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesb76922a2007-12-11 01:06:40 +0000429
Walter Dörwald1ab83302007-05-18 17:15:44 +0000430 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000431}
432
433static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000434float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000435{
436 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000437 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000438 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439}
440
Tim Peters307fa782004-09-23 08:06:40 +0000441/* Comparison is pretty much a nightmare. When comparing float to float,
442 * we do it as straightforwardly (and long-windedly) as conceivable, so
443 * that, e.g., Python x == y delivers the same result as the platform
444 * C x == y when x and/or y is a NaN.
445 * When mixing float with an integer type, there's no good *uniform* approach.
446 * Converting the double to an integer obviously doesn't work, since we
447 * may lose info from fractional bits. Converting the integer to a double
448 * also has two failure modes: (1) a long int may trigger overflow (too
449 * large to fit in the dynamic range of a C double); (2) even a C long may have
450 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
451 * 63 bits of precision, but a C double probably has only 53), and then
452 * we can falsely claim equality when low-order integer bits are lost by
453 * coercion to double. So this part is painful too.
454 */
455
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000456static PyObject*
457float_richcompare(PyObject *v, PyObject *w, int op)
458{
459 double i, j;
460 int r = 0;
461
Tim Peters307fa782004-09-23 08:06:40 +0000462 assert(PyFloat_Check(v));
463 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000464
Tim Peters307fa782004-09-23 08:06:40 +0000465 /* Switch on the type of w. Set i and j to doubles to be compared,
466 * and op to the richcomp to use.
467 */
468 if (PyFloat_Check(w))
469 j = PyFloat_AS_DOUBLE(w);
470
Thomas Wouters477c8d52006-05-27 19:21:47 +0000471 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000472 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000473 /* If i is an infinity, its magnitude exceeds any
474 * finite integer, so it doesn't matter which int we
475 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000476 */
477 j = 0.0;
478 else
479 goto Unimplemented;
480 }
481
Tim Peters307fa782004-09-23 08:06:40 +0000482 else if (PyLong_Check(w)) {
483 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
484 int wsign = _PyLong_Sign(w);
485 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000486 int exponent;
487
488 if (vsign != wsign) {
489 /* Magnitudes are irrelevant -- the signs alone
490 * determine the outcome.
491 */
492 i = (double)vsign;
493 j = (double)wsign;
494 goto Compare;
495 }
496 /* The signs are the same. */
497 /* Convert w to a double if it fits. In particular, 0 fits. */
498 nbits = _PyLong_NumBits(w);
499 if (nbits == (size_t)-1 && PyErr_Occurred()) {
500 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000501 * to hold the # of bits. Replace with little doubles
502 * that give the same outcome -- w is so large that
503 * its magnitude must exceed the magnitude of any
504 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000505 */
506 PyErr_Clear();
507 i = (double)vsign;
508 assert(wsign != 0);
509 j = wsign * 2.0;
510 goto Compare;
511 }
512 if (nbits <= 48) {
513 j = PyLong_AsDouble(w);
514 /* It's impossible that <= 48 bits overflowed. */
515 assert(j != -1.0 || ! PyErr_Occurred());
516 goto Compare;
517 }
518 assert(wsign != 0); /* else nbits was 0 */
519 assert(vsign != 0); /* if vsign were 0, then since wsign is
520 * not 0, we would have taken the
521 * vsign != wsign branch at the start */
522 /* We want to work with non-negative numbers. */
523 if (vsign < 0) {
524 /* "Multiply both sides" by -1; this also swaps the
525 * comparator.
526 */
527 i = -i;
528 op = _Py_SwappedOp[op];
529 }
530 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000531 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000532 /* exponent is the # of bits in v before the radix point;
533 * we know that nbits (the # of bits in w) > 48 at this point
534 */
535 if (exponent < 0 || (size_t)exponent < nbits) {
536 i = 1.0;
537 j = 2.0;
538 goto Compare;
539 }
540 if ((size_t)exponent > nbits) {
541 i = 2.0;
542 j = 1.0;
543 goto Compare;
544 }
545 /* v and w have the same number of bits before the radix
546 * point. Construct two longs that have the same comparison
547 * outcome.
548 */
549 {
550 double fracpart;
551 double intpart;
552 PyObject *result = NULL;
553 PyObject *one = NULL;
554 PyObject *vv = NULL;
555 PyObject *ww = w;
556
557 if (wsign < 0) {
558 ww = PyNumber_Negative(w);
559 if (ww == NULL)
560 goto Error;
561 }
562 else
563 Py_INCREF(ww);
564
565 fracpart = modf(i, &intpart);
566 vv = PyLong_FromDouble(intpart);
567 if (vv == NULL)
568 goto Error;
569
570 if (fracpart != 0.0) {
571 /* Shift left, and or a 1 bit into vv
572 * to represent the lost fraction.
573 */
574 PyObject *temp;
575
Christian Heimes217cfd12007-12-02 14:31:20 +0000576 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000577 if (one == NULL)
578 goto Error;
579
580 temp = PyNumber_Lshift(ww, one);
581 if (temp == NULL)
582 goto Error;
583 Py_DECREF(ww);
584 ww = temp;
585
586 temp = PyNumber_Lshift(vv, one);
587 if (temp == NULL)
588 goto Error;
589 Py_DECREF(vv);
590 vv = temp;
591
592 temp = PyNumber_Or(vv, one);
593 if (temp == NULL)
594 goto Error;
595 Py_DECREF(vv);
596 vv = temp;
597 }
598
599 r = PyObject_RichCompareBool(vv, ww, op);
600 if (r < 0)
601 goto Error;
602 result = PyBool_FromLong(r);
603 Error:
604 Py_XDECREF(vv);
605 Py_XDECREF(ww);
606 Py_XDECREF(one);
607 return result;
608 }
609 } /* else if (PyLong_Check(w)) */
610
611 else /* w isn't float, int, or long */
612 goto Unimplemented;
613
614 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000615 PyFPE_START_PROTECT("richcompare", return NULL)
616 switch (op) {
617 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000618 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000619 break;
620 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000621 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000622 break;
623 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000624 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000625 break;
626 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000627 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000628 break;
629 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000630 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000631 break;
632 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000633 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000634 break;
635 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000636 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000637 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000638
639 Unimplemented:
640 Py_INCREF(Py_NotImplemented);
641 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000642}
643
Guido van Rossum9bfef441993-03-29 10:43:31 +0000644static long
Fred Drakefd99de62000-07-09 05:02:18 +0000645float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000646{
Tim Peters39dce292000-08-15 03:34:48 +0000647 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000648}
649
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000651float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000652{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000653 double a,b;
654 CONVERT_TO_DOUBLE(v, a);
655 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000656 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000657 a = a + b;
658 PyFPE_END_PROTECT(a)
659 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660}
661
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000663float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000665 double a,b;
666 CONVERT_TO_DOUBLE(v, a);
667 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000668 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000669 a = a - b;
670 PyFPE_END_PROTECT(a)
671 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672}
673
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000675float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000677 double a,b;
678 CONVERT_TO_DOUBLE(v, a);
679 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000680 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000681 a = a * b;
682 PyFPE_END_PROTECT(a)
683 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000684}
685
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000687float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000689 double a,b;
690 CONVERT_TO_DOUBLE(v, a);
691 CONVERT_TO_DOUBLE(w, b);
Christian Heimes53876d92008-04-19 00:31:39 +0000692#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000693 if (b == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000694 PyErr_SetString(PyExc_ZeroDivisionError,
695 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696 return NULL;
697 }
Christian Heimes53876d92008-04-19 00:31:39 +0000698#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000699 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000700 a = a / b;
701 PyFPE_END_PROTECT(a)
702 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000703}
704
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000706float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000707{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000708 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000709 double mod;
Christian Heimes53876d92008-04-19 00:31:39 +0000710 CONVERT_TO_DOUBLE(v, vx);
711 CONVERT_TO_DOUBLE(w, wx);
712#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000713 if (wx == 0.0) {
Christian Heimes53876d92008-04-19 00:31:39 +0000714 PyErr_SetString(PyExc_ZeroDivisionError,
715 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000716 return NULL;
717 }
Christian Heimes53876d92008-04-19 00:31:39 +0000718#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000719 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000720 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000721 /* note: checking mod*wx < 0 is incorrect -- underflows to
722 0 if wx < sqrt(smallest nonzero double) */
723 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000724 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000725 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000726 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728}
729
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000730static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000731float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000732{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000733 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000734 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000735 CONVERT_TO_DOUBLE(v, vx);
736 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000737 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000739 return NULL;
740 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000741 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000742 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000743 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000744 exact multiple of wx. But this is fp arithmetic, and fp
745 vx - mod is an approximation; the result is that div may
746 not be an exact integral value after the division, although
747 it will always be very close to one.
748 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000749 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000750 if (mod) {
751 /* ensure the remainder has the same sign as the denominator */
752 if ((wx < 0) != (mod < 0)) {
753 mod += wx;
754 div -= 1.0;
755 }
756 }
757 else {
758 /* the remainder is zero, and in the presence of signed zeroes
759 fmod returns different results across platforms; ensure
760 it has the same sign as the denominator; we'd like to do
761 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000762 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000763 if (wx < 0.0)
764 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000765 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000766 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000767 if (div) {
768 floordiv = floor(div);
769 if (div - floordiv > 0.5)
770 floordiv += 1.0;
771 }
772 else {
773 /* div is zero - get the same sign as the true quotient */
774 div *= div; /* hide "div = +0" from optimizers */
775 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
776 }
777 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000778 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000779}
780
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000781static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000782float_floor_div(PyObject *v, PyObject *w)
783{
784 PyObject *t, *r;
785
786 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000787 if (t == NULL || t == Py_NotImplemented)
788 return t;
789 assert(PyTuple_CheckExact(t));
790 r = PyTuple_GET_ITEM(t, 0);
791 Py_INCREF(r);
792 Py_DECREF(t);
793 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000794}
795
796static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000797float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798{
799 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000800
801 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000802 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000803 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000804 return NULL;
805 }
806
Neil Schemenauer32117e52001-01-04 01:44:34 +0000807 CONVERT_TO_DOUBLE(v, iv);
808 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000809
810 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000811 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000812 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000813 }
Tim Peters96685bf2001-08-23 22:31:37 +0000814 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000815 if (iw < 0.0) {
816 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000817 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000818 return NULL;
819 }
820 return PyFloat_FromDouble(0.0);
821 }
Christian Heimes53876d92008-04-19 00:31:39 +0000822 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
823 return PyFloat_FromDouble(1.0);
824 }
Tim Peterse87568d2003-05-24 20:18:24 +0000825 if (iv < 0.0) {
826 /* Whether this is an error is a mess, and bumps into libm
827 * bugs so we have to figure it out ourselves.
828 */
829 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000830 /* Negative numbers raised to fractional powers
831 * become complex.
832 */
833 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000834 }
835 /* iw is an exact integer, albeit perhaps a very large one.
836 * -1 raised to an exact integer should never be exceptional.
837 * Alas, some libms (chiefly glibc as of early 2003) return
838 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
839 * happen to be representable in a *C* integer. That's a
840 * bug; we let that slide in math.pow() (which currently
841 * reflects all platform accidents), but not for Python's **.
842 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000843 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000844 /* Return 1 if iw is even, -1 if iw is odd; there's
845 * no guarantee that any C integral type is big
846 * enough to hold iw, so we have to check this
847 * indirectly.
848 */
849 ix = floor(iw * 0.5) * 2.0;
850 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
851 }
852 /* Else iv != -1.0, and overflow or underflow are possible.
853 * Unless we're to write pow() ourselves, we have to trust
854 * the platform to do this correctly.
855 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000856 }
Tim Peters96685bf2001-08-23 22:31:37 +0000857 errno = 0;
858 PyFPE_START_PROTECT("pow", return NULL)
859 ix = pow(iv, iw);
860 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000861 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000862 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000863 /* We don't expect any errno value other than ERANGE, but
864 * the range of libm bugs appears unbounded.
865 */
866 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
867 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000868 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000869 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000870 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000871}
872
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000873static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000874float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877}
878
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000880float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000881{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000882 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000883}
884
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000885static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000886float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000887{
888 return v->ob_fval != 0.0;
889}
890
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000891static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000892float_is_integer(PyObject *v)
893{
894 double x = PyFloat_AsDouble(v);
895 PyObject *o;
896
897 if (x == -1.0 && PyErr_Occurred())
898 return NULL;
899 if (!Py_IS_FINITE(x))
900 Py_RETURN_FALSE;
Mark Dickinsonc4352b02008-05-09 13:55:01 +0000901 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000902 PyFPE_START_PROTECT("is_integer", return NULL)
903 o = (floor(x) == x) ? Py_True : Py_False;
904 PyFPE_END_PROTECT(x)
905 if (errno != 0) {
906 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
907 PyExc_ValueError);
908 return NULL;
909 }
910 Py_INCREF(o);
911 return o;
912}
913
914#if 0
915static PyObject *
916float_is_inf(PyObject *v)
917{
918 double x = PyFloat_AsDouble(v);
919 if (x == -1.0 && PyErr_Occurred())
920 return NULL;
921 return PyBool_FromLong((long)Py_IS_INFINITY(x));
922}
923
924static PyObject *
925float_is_nan(PyObject *v)
926{
927 double x = PyFloat_AsDouble(v);
928 if (x == -1.0 && PyErr_Occurred())
929 return NULL;
930 return PyBool_FromLong((long)Py_IS_NAN(x));
931}
932
933static PyObject *
934float_is_finite(PyObject *v)
935{
936 double x = PyFloat_AsDouble(v);
937 if (x == -1.0 && PyErr_Occurred())
938 return NULL;
939 return PyBool_FromLong((long)Py_IS_FINITE(x));
940}
941#endif
942
943static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000944float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000945{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000947 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000948
949 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000950 /* Try to get out cheap if this fits in a Python int. The attempt
951 * to cast to long must be protected, as C doesn't define what
952 * happens if the double is too big to fit in a long. Some rare
953 * systems raise an exception then (RISCOS was mentioned as one,
954 * and someone using a non-default option on Sun also bumped into
955 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
956 * still be vulnerable: if a long has more bits of precision than
957 * a double, casting MIN/MAX to double may yield an approximation,
958 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
959 * yield true from the C expression wholepart<=LONG_MAX, despite
960 * that wholepart is actually greater than LONG_MAX.
961 */
962 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
963 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +0000964 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000965 }
966 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000967}
968
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000969static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000970float_round(PyObject *v, PyObject *args)
971{
972#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
973 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000974 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000975 double flr, cil;
976 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000977 int ndigits = UNDEF_NDIGITS;
978
979 if (!PyArg_ParseTuple(args, "|i", &ndigits))
980 return NULL;
981
982 x = PyFloat_AsDouble(v);
983
984 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000985 f = pow(10.0, ndigits);
986 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000987 }
988
989 flr = floor(x);
990 cil = ceil(x);
991
992 if (x-flr > 0.5)
993 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +0000994 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000995 rounded = fmod(flr, 2) == 0 ? flr : cil;
996 else
997 rounded = flr;
998
999 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001000 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001001 return PyFloat_FromDouble(rounded);
1002 }
1003
1004 return PyLong_FromDouble(rounded);
1005#undef UNDEF_NDIGITS
1006}
1007
1008static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001009float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001010{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001011 if (PyFloat_CheckExact(v))
1012 Py_INCREF(v);
1013 else
1014 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001015 return v;
1016}
1017
Christian Heimes26855632008-01-27 23:50:43 +00001018static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001019float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001020{
1021 double self;
1022 double float_part;
1023 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001024 int i;
1025
Christian Heimes26855632008-01-27 23:50:43 +00001026 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001027 PyObject *py_exponent = NULL;
1028 PyObject *numerator = NULL;
1029 PyObject *denominator = NULL;
1030 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001031 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001032
1033#define INPLACE_UPDATE(obj, call) \
1034 prev = obj; \
1035 obj = call; \
1036 Py_DECREF(prev); \
1037
1038 CONVERT_TO_DOUBLE(v, self);
1039
1040 if (Py_IS_INFINITY(self)) {
1041 PyErr_SetString(PyExc_OverflowError,
1042 "Cannot pass infinity to float.as_integer_ratio.");
1043 return NULL;
1044 }
1045#ifdef Py_NAN
1046 if (Py_IS_NAN(self)) {
1047 PyErr_SetString(PyExc_ValueError,
1048 "Cannot pass nan to float.as_integer_ratio.");
1049 return NULL;
1050 }
1051#endif
1052
Christian Heimes26855632008-01-27 23:50:43 +00001053 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001054 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001055 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001056
1057 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1058 float_part *= 2.0;
1059 exponent--;
1060 }
1061 /* self == float_part * 2**exponent exactly and float_part is integral.
1062 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1063 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001064
Christian Heimes292d3512008-02-03 16:51:08 +00001065 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001066 if (numerator == NULL) goto error;
1067
Christian Heimes292d3512008-02-03 16:51:08 +00001068 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001069 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001070 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001071 if (py_exponent == NULL) goto error;
1072 INPLACE_UPDATE(py_exponent,
1073 long_methods->nb_lshift(denominator, py_exponent));
1074 if (py_exponent == NULL) goto error;
1075 if (exponent > 0) {
1076 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001077 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001078 if (numerator == NULL) goto error;
1079 }
1080 else {
1081 Py_DECREF(denominator);
1082 denominator = py_exponent;
1083 py_exponent = NULL;
1084 }
1085
Christian Heimes292d3512008-02-03 16:51:08 +00001086 /* Returns ints instead of longs where possible */
1087 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1088 if (numerator == NULL) goto error;
1089 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1090 if (denominator == NULL) goto error;
1091
Christian Heimes26855632008-01-27 23:50:43 +00001092 result_pair = PyTuple_Pack(2, numerator, denominator);
1093
1094#undef INPLACE_UPDATE
1095error:
1096 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001097 Py_XDECREF(denominator);
1098 Py_XDECREF(numerator);
1099 return result_pair;
1100}
1101
1102PyDoc_STRVAR(float_as_integer_ratio_doc,
1103"float.as_integer_ratio() -> (int, int)\n"
1104"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001105"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1106"float and with a positive denominator.\n"
1107"Raises OverflowError on infinities and a ValueError on nans.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001108"\n"
1109">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001110"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001111">>> (0.0).as_integer_ratio()\n"
1112"(0, 1)\n"
1113">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001114"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001115
Raymond Hettingerd11a4432008-06-22 11:39:13 +00001116PyObject *
1117_float_to_base(PyObject *v, int base)
1118{
1119 PyObject *mant, *conv, *result;
1120 double x, fr;
1121 int i, exp;
1122
1123 if (!PyFloat_Check(v)) {
1124 PyErr_BadInternalCall();
1125 return NULL;
1126 }
1127 CONVERT_TO_DOUBLE(v, x);
1128 if (!Py_IS_FINITE(x))
1129 return PyObject_Repr(v);
1130 fr = frexp(x, &exp);
1131 for (i=0; i<300 && fr != floor(fr) ; i++) {
1132 fr *= 2.0;
1133 exp--;
1134 }
1135 mant = PyLong_FromDouble(floor(fr));
1136 if (mant == NULL)
1137 return NULL;
1138 conv = PyNumber_ToBase(mant, base);
1139 Py_DECREF(mant);
1140 if (conv == NULL)
1141 return NULL;
1142 result = PyUnicode_FromFormat("%U * 2.0 ** %d", conv, exp);
1143 Py_DECREF(conv);
1144 return result;
1145}
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001146
Jeremy Hylton938ace62002-07-17 16:30:39 +00001147static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001148float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1149
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150static PyObject *
1151float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1152{
1153 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001154 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155
Guido van Rossumbef14172001-08-29 15:47:46 +00001156 if (type != &PyFloat_Type)
1157 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001158 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1159 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001160 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001161 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162 return PyNumber_Float(x);
1163}
1164
Guido van Rossumbef14172001-08-29 15:47:46 +00001165/* Wimpy, slow approach to tp_new calls for subtypes of float:
1166 first create a regular float from whatever arguments we got,
1167 then allocate a subtype instance and initialize its ob_fval
1168 from the regular float. The regular float is then thrown away.
1169*/
1170static PyObject *
1171float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1172{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001173 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001174
1175 assert(PyType_IsSubtype(type, &PyFloat_Type));
1176 tmp = float_new(&PyFloat_Type, args, kwds);
1177 if (tmp == NULL)
1178 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001179 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180 newobj = type->tp_alloc(type, 0);
1181 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001182 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001183 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001184 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001185 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001186 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001187 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001188}
1189
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001190static PyObject *
1191float_getnewargs(PyFloatObject *v)
1192{
1193 return Py_BuildValue("(d)", v->ob_fval);
1194}
1195
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001196/* this is for the benefit of the pack/unpack routines below */
1197
1198typedef enum {
1199 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1200} float_format_type;
1201
1202static float_format_type double_format, float_format;
1203static float_format_type detected_double_format, detected_float_format;
1204
1205static PyObject *
1206float_getformat(PyTypeObject *v, PyObject* arg)
1207{
1208 char* s;
1209 float_format_type r;
1210
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001211 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001212 PyErr_Format(PyExc_TypeError,
1213 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001214 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001215 return NULL;
1216 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001217 s = PyUnicode_AsString(arg);
1218 if (s == NULL)
1219 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001220 if (strcmp(s, "double") == 0) {
1221 r = double_format;
1222 }
1223 else if (strcmp(s, "float") == 0) {
1224 r = float_format;
1225 }
1226 else {
1227 PyErr_SetString(PyExc_ValueError,
1228 "__getformat__() argument 1 must be "
1229 "'double' or 'float'");
1230 return NULL;
1231 }
1232
1233 switch (r) {
1234 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001235 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001236 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001237 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001238 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001239 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001240 default:
1241 Py_FatalError("insane float_format or double_format");
1242 return NULL;
1243 }
1244}
1245
1246PyDoc_STRVAR(float_getformat_doc,
1247"float.__getformat__(typestr) -> string\n"
1248"\n"
1249"You probably don't want to use this function. It exists mainly to be\n"
1250"used in Python's test suite.\n"
1251"\n"
1252"typestr must be 'double' or 'float'. This function returns whichever of\n"
1253"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1254"format of floating point numbers used by the C type named by typestr.");
1255
1256static PyObject *
1257float_setformat(PyTypeObject *v, PyObject* args)
1258{
1259 char* typestr;
1260 char* format;
1261 float_format_type f;
1262 float_format_type detected;
1263 float_format_type *p;
1264
1265 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1266 return NULL;
1267
1268 if (strcmp(typestr, "double") == 0) {
1269 p = &double_format;
1270 detected = detected_double_format;
1271 }
1272 else if (strcmp(typestr, "float") == 0) {
1273 p = &float_format;
1274 detected = detected_float_format;
1275 }
1276 else {
1277 PyErr_SetString(PyExc_ValueError,
1278 "__setformat__() argument 1 must "
1279 "be 'double' or 'float'");
1280 return NULL;
1281 }
1282
1283 if (strcmp(format, "unknown") == 0) {
1284 f = unknown_format;
1285 }
1286 else if (strcmp(format, "IEEE, little-endian") == 0) {
1287 f = ieee_little_endian_format;
1288 }
1289 else if (strcmp(format, "IEEE, big-endian") == 0) {
1290 f = ieee_big_endian_format;
1291 }
1292 else {
1293 PyErr_SetString(PyExc_ValueError,
1294 "__setformat__() argument 2 must be "
1295 "'unknown', 'IEEE, little-endian' or "
1296 "'IEEE, big-endian'");
1297 return NULL;
1298
1299 }
1300
1301 if (f != unknown_format && f != detected) {
1302 PyErr_Format(PyExc_ValueError,
1303 "can only set %s format to 'unknown' or the "
1304 "detected platform value", typestr);
1305 return NULL;
1306 }
1307
1308 *p = f;
1309 Py_RETURN_NONE;
1310}
1311
1312PyDoc_STRVAR(float_setformat_doc,
1313"float.__setformat__(typestr, fmt) -> None\n"
1314"\n"
1315"You probably don't want to use this function. It exists mainly to be\n"
1316"used in Python's test suite.\n"
1317"\n"
1318"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1319"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1320"one of the latter two if it appears to match the underlying C reality.\n"
1321"\n"
1322"Overrides the automatic determination of C-level floating point type.\n"
1323"This affects how floats are converted to and from binary strings.");
1324
Guido van Rossumb43daf72007-08-01 18:08:08 +00001325static PyObject *
1326float_getzero(PyObject *v, void *closure)
1327{
1328 return PyFloat_FromDouble(0.0);
1329}
1330
Eric Smith8c663262007-08-25 02:26:07 +00001331static PyObject *
1332float__format__(PyObject *self, PyObject *args)
1333{
Eric Smith4a7d76d2008-05-30 18:10:19 +00001334 PyObject *format_spec;
1335
1336 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1337 return NULL;
1338 return _PyFloat_FormatAdvanced(self,
1339 PyUnicode_AS_UNICODE(format_spec),
1340 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001341}
1342
1343PyDoc_STRVAR(float__format__doc,
1344"float.__format__(format_spec) -> string\n"
1345"\n"
1346"Formats the float according to format_spec.");
1347
1348
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001349static PyMethodDef float_methods[] = {
Christian Heimes53876d92008-04-19 00:31:39 +00001350 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Guido van Rossumb43daf72007-08-01 18:08:08 +00001351 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001352 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1353 "Returns the Integral closest to x between 0 and x."},
1354 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1355 "Returns the Integral closest to x, rounding half toward even.\n"
1356 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001357 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1358 float_as_integer_ratio_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001359 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1360 "Returns True if the float is an integer."},
1361#if 0
1362 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1363 "Returns True if the float is positive or negative infinite."},
1364 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1365 "Returns True if the float is finite, neither infinite nor NaN."},
1366 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1367 "Returns True if the float is not a number (NaN)."},
1368#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001369 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001370 {"__getformat__", (PyCFunction)float_getformat,
1371 METH_O|METH_CLASS, float_getformat_doc},
1372 {"__setformat__", (PyCFunction)float_setformat,
1373 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001374 {"__format__", (PyCFunction)float__format__,
1375 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001376 {NULL, NULL} /* sentinel */
1377};
1378
Guido van Rossumb43daf72007-08-01 18:08:08 +00001379static PyGetSetDef float_getset[] = {
1380 {"real",
1381 (getter)float_float, (setter)NULL,
1382 "the real part of a complex number",
1383 NULL},
1384 {"imag",
1385 (getter)float_getzero, (setter)NULL,
1386 "the imaginary part of a complex number",
1387 NULL},
1388 {NULL} /* Sentinel */
1389};
1390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001391PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392"float(x) -> floating point number\n\
1393\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001394Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395
1396
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001398 float_add, /*nb_add*/
1399 float_sub, /*nb_subtract*/
1400 float_mul, /*nb_multiply*/
1401 float_rem, /*nb_remainder*/
1402 float_divmod, /*nb_divmod*/
1403 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001404 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001405 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001406 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001407 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001408 0, /*nb_invert*/
1409 0, /*nb_lshift*/
1410 0, /*nb_rshift*/
1411 0, /*nb_and*/
1412 0, /*nb_xor*/
1413 0, /*nb_or*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001414 float_trunc, /*nb_int*/
1415 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001416 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001417 0, /* nb_inplace_add */
1418 0, /* nb_inplace_subtract */
1419 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001420 0, /* nb_inplace_remainder */
1421 0, /* nb_inplace_power */
1422 0, /* nb_inplace_lshift */
1423 0, /* nb_inplace_rshift */
1424 0, /* nb_inplace_and */
1425 0, /* nb_inplace_xor */
1426 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001427 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001428 float_div, /* nb_true_divide */
1429 0, /* nb_inplace_floor_divide */
1430 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001431};
1432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001433PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001435 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001436 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001437 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001439 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 0, /* tp_getattr */
1441 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001442 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443 (reprfunc)float_repr, /* tp_repr */
1444 &float_as_number, /* tp_as_number */
1445 0, /* tp_as_sequence */
1446 0, /* tp_as_mapping */
1447 (hashfunc)float_hash, /* tp_hash */
1448 0, /* tp_call */
1449 (reprfunc)float_str, /* tp_str */
1450 PyObject_GenericGetAttr, /* tp_getattro */
1451 0, /* tp_setattro */
1452 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001453 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 float_doc, /* tp_doc */
1455 0, /* tp_traverse */
1456 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001457 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 0, /* tp_weaklistoffset */
1459 0, /* tp_iter */
1460 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001461 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001463 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 0, /* tp_base */
1465 0, /* tp_dict */
1466 0, /* tp_descr_get */
1467 0, /* tp_descr_set */
1468 0, /* tp_dictoffset */
1469 0, /* tp_init */
1470 0, /* tp_alloc */
1471 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001472};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001473
1474void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001475_PyFloat_Init(void)
1476{
1477 /* We attempt to determine if this machine is using IEEE
1478 floating point formats by peering at the bits of some
1479 carefully chosen values. If it looks like we are on an
1480 IEEE platform, the float packing/unpacking routines can
1481 just copy bits, if not they resort to arithmetic & shifts
1482 and masks. The shifts & masks approach works on all finite
1483 values, but what happens to infinities, NaNs and signed
1484 zeroes on packing is an accident, and attempting to unpack
1485 a NaN or an infinity will raise an exception.
1486
1487 Note that if we're on some whacked-out platform which uses
1488 IEEE formats but isn't strictly little-endian or big-
1489 endian, we will fall back to the portable shifts & masks
1490 method. */
1491
1492#if SIZEOF_DOUBLE == 8
1493 {
1494 double x = 9006104071832581.0;
1495 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1496 detected_double_format = ieee_big_endian_format;
1497 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1498 detected_double_format = ieee_little_endian_format;
1499 else
1500 detected_double_format = unknown_format;
1501 }
1502#else
1503 detected_double_format = unknown_format;
1504#endif
1505
1506#if SIZEOF_FLOAT == 4
1507 {
1508 float y = 16711938.0;
1509 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1510 detected_float_format = ieee_big_endian_format;
1511 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1512 detected_float_format = ieee_little_endian_format;
1513 else
1514 detected_float_format = unknown_format;
1515 }
1516#else
1517 detected_float_format = unknown_format;
1518#endif
1519
1520 double_format = detected_double_format;
1521 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001522
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001523 /* Init float info */
1524 if (FloatInfoType.tp_name == 0)
1525 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001526}
1527
1528void
Christian Heimes15ebc882008-02-04 18:48:49 +00001529PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001530{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001531 PyFloatObject *p;
1532 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001533 unsigned i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001534 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1535 size_t fsum = 0; /* total unfreed ints */
1536 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001537
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001538 list = block_list;
1539 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001540 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001541 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001542 bc++;
1543 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001544 for (i = 0, p = &list->objects[0];
1545 i < N_FLOATOBJECTS;
1546 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001547 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001548 frem++;
1549 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001550 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001551 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001552 list->next = block_list;
1553 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001554 for (i = 0, p = &list->objects[0];
1555 i < N_FLOATOBJECTS;
1556 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001557 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001558 Py_REFCNT(p) == 0) {
1559 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001560 free_list;
1561 free_list = p;
1562 }
1563 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001564 }
1565 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001566 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001567 bf++;
1568 }
1569 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001570 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001571 }
Christian Heimes15ebc882008-02-04 18:48:49 +00001572 *pbc = bc;
1573 *pbf = bf;
1574 *bsum = fsum;
1575}
1576
1577void
1578PyFloat_Fini(void)
1579{
1580 PyFloatObject *p;
1581 PyFloatBlock *list;
1582 unsigned i;
1583 size_t bc, bf; /* block count, number of freed blocks */
1584 size_t fsum; /* total unfreed floats per block */
1585
1586 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1587
Guido van Rossum3fce8831999-03-12 19:43:17 +00001588 if (!Py_VerboseFlag)
1589 return;
1590 fprintf(stderr, "# cleanup floats");
1591 if (!fsum) {
1592 fprintf(stderr, "\n");
1593 }
1594 else {
1595 fprintf(stderr,
Christian Heimesba4af492008-03-28 00:55:15 +00001596 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes15ebc882008-02-04 18:48:49 +00001597 PY_FORMAT_SIZE_T "d out of %"
1598 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001599 fsum, fsum == 1 ? "" : "s",
1600 bc - bf, bc, bc == 1 ? "" : "s");
1601 }
1602 if (Py_VerboseFlag > 1) {
1603 list = block_list;
1604 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001605 for (i = 0, p = &list->objects[0];
1606 i < N_FLOATOBJECTS;
1607 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001608 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001609 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001610 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001611 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001612 /* XXX(twouters) cast refcount to
1613 long until %zd is universally
1614 available
1615 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001616 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001617 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001618 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001619 }
1620 }
1621 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001622 }
1623 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001624}
Tim Peters9905b942003-03-20 20:53:32 +00001625
1626/*----------------------------------------------------------------------------
1627 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001628 */
1629int
1630_PyFloat_Pack4(double x, unsigned char *p, int le)
1631{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001632 if (float_format == unknown_format) {
1633 unsigned char sign;
1634 int e;
1635 double f;
1636 unsigned int fbits;
1637 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001638
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001639 if (le) {
1640 p += 3;
1641 incr = -1;
1642 }
Tim Peters9905b942003-03-20 20:53:32 +00001643
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001644 if (x < 0) {
1645 sign = 1;
1646 x = -x;
1647 }
1648 else
1649 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001650
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001651 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001652
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001653 /* Normalize f to be in the range [1.0, 2.0) */
1654 if (0.5 <= f && f < 1.0) {
1655 f *= 2.0;
1656 e--;
1657 }
1658 else if (f == 0.0)
1659 e = 0;
1660 else {
1661 PyErr_SetString(PyExc_SystemError,
1662 "frexp() result out of range");
1663 return -1;
1664 }
1665
1666 if (e >= 128)
1667 goto Overflow;
1668 else if (e < -126) {
1669 /* Gradual underflow */
1670 f = ldexp(f, 126 + e);
1671 e = 0;
1672 }
1673 else if (!(e == 0 && f == 0.0)) {
1674 e += 127;
1675 f -= 1.0; /* Get rid of leading 1 */
1676 }
1677
1678 f *= 8388608.0; /* 2**23 */
1679 fbits = (unsigned int)(f + 0.5); /* Round */
1680 assert(fbits <= 8388608);
1681 if (fbits >> 23) {
1682 /* The carry propagated out of a string of 23 1 bits. */
1683 fbits = 0;
1684 ++e;
1685 if (e >= 255)
1686 goto Overflow;
1687 }
1688
1689 /* First byte */
1690 *p = (sign << 7) | (e >> 1);
1691 p += incr;
1692
1693 /* Second byte */
1694 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1695 p += incr;
1696
1697 /* Third byte */
1698 *p = (fbits >> 8) & 0xFF;
1699 p += incr;
1700
1701 /* Fourth byte */
1702 *p = fbits & 0xFF;
1703
1704 /* Done */
1705 return 0;
1706
Tim Peters9905b942003-03-20 20:53:32 +00001707 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001708 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001709 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001710 const char *s = (char*)&y;
1711 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001712
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001713 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1714 goto Overflow;
1715
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001716 if ((float_format == ieee_little_endian_format && !le)
1717 || (float_format == ieee_big_endian_format && le)) {
1718 p += 3;
1719 incr = -1;
1720 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001721
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001722 for (i = 0; i < 4; i++) {
1723 *p = *s++;
1724 p += incr;
1725 }
1726 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001727 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001728 Overflow:
1729 PyErr_SetString(PyExc_OverflowError,
1730 "float too large to pack with f format");
1731 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001732}
1733
1734int
1735_PyFloat_Pack8(double x, unsigned char *p, int le)
1736{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001737 if (double_format == unknown_format) {
1738 unsigned char sign;
1739 int e;
1740 double f;
1741 unsigned int fhi, flo;
1742 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001743
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001744 if (le) {
1745 p += 7;
1746 incr = -1;
1747 }
Tim Peters9905b942003-03-20 20:53:32 +00001748
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001749 if (x < 0) {
1750 sign = 1;
1751 x = -x;
1752 }
1753 else
1754 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001755
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001756 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001757
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001758 /* Normalize f to be in the range [1.0, 2.0) */
1759 if (0.5 <= f && f < 1.0) {
1760 f *= 2.0;
1761 e--;
1762 }
1763 else if (f == 0.0)
1764 e = 0;
1765 else {
1766 PyErr_SetString(PyExc_SystemError,
1767 "frexp() result out of range");
1768 return -1;
1769 }
1770
1771 if (e >= 1024)
1772 goto Overflow;
1773 else if (e < -1022) {
1774 /* Gradual underflow */
1775 f = ldexp(f, 1022 + e);
1776 e = 0;
1777 }
1778 else if (!(e == 0 && f == 0.0)) {
1779 e += 1023;
1780 f -= 1.0; /* Get rid of leading 1 */
1781 }
1782
1783 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1784 f *= 268435456.0; /* 2**28 */
1785 fhi = (unsigned int)f; /* Truncate */
1786 assert(fhi < 268435456);
1787
1788 f -= (double)fhi;
1789 f *= 16777216.0; /* 2**24 */
1790 flo = (unsigned int)(f + 0.5); /* Round */
1791 assert(flo <= 16777216);
1792 if (flo >> 24) {
1793 /* The carry propagated out of a string of 24 1 bits. */
1794 flo = 0;
1795 ++fhi;
1796 if (fhi >> 28) {
1797 /* And it also progagated out of the next 28 bits. */
1798 fhi = 0;
1799 ++e;
1800 if (e >= 2047)
1801 goto Overflow;
1802 }
1803 }
1804
1805 /* First byte */
1806 *p = (sign << 7) | (e >> 4);
1807 p += incr;
1808
1809 /* Second byte */
1810 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1811 p += incr;
1812
1813 /* Third byte */
1814 *p = (fhi >> 16) & 0xFF;
1815 p += incr;
1816
1817 /* Fourth byte */
1818 *p = (fhi >> 8) & 0xFF;
1819 p += incr;
1820
1821 /* Fifth byte */
1822 *p = fhi & 0xFF;
1823 p += incr;
1824
1825 /* Sixth byte */
1826 *p = (flo >> 16) & 0xFF;
1827 p += incr;
1828
1829 /* Seventh byte */
1830 *p = (flo >> 8) & 0xFF;
1831 p += incr;
1832
1833 /* Eighth byte */
1834 *p = flo & 0xFF;
1835 p += incr;
1836
1837 /* Done */
1838 return 0;
1839
1840 Overflow:
1841 PyErr_SetString(PyExc_OverflowError,
1842 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001843 return -1;
1844 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001845 else {
1846 const char *s = (char*)&x;
1847 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001848
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001849 if ((double_format == ieee_little_endian_format && !le)
1850 || (double_format == ieee_big_endian_format && le)) {
1851 p += 7;
1852 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001853 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001854
1855 for (i = 0; i < 8; i++) {
1856 *p = *s++;
1857 p += incr;
1858 }
1859 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001860 }
Tim Peters9905b942003-03-20 20:53:32 +00001861}
1862
Neal Norwitz545686b2006-12-28 04:45:06 +00001863/* Should only be used by marshal. */
1864int
1865_PyFloat_Repr(double x, char *p, size_t len)
1866{
1867 format_double(p, len, x, PREC_REPR);
1868 return (int)strlen(p);
1869}
1870
Tim Peters9905b942003-03-20 20:53:32 +00001871double
1872_PyFloat_Unpack4(const unsigned char *p, int le)
1873{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001874 if (float_format == unknown_format) {
1875 unsigned char sign;
1876 int e;
1877 unsigned int f;
1878 double x;
1879 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001880
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001881 if (le) {
1882 p += 3;
1883 incr = -1;
1884 }
1885
1886 /* First byte */
1887 sign = (*p >> 7) & 1;
1888 e = (*p & 0x7F) << 1;
1889 p += incr;
1890
1891 /* Second byte */
1892 e |= (*p >> 7) & 1;
1893 f = (*p & 0x7F) << 16;
1894 p += incr;
1895
1896 if (e == 255) {
1897 PyErr_SetString(
1898 PyExc_ValueError,
1899 "can't unpack IEEE 754 special value "
1900 "on non-IEEE platform");
1901 return -1;
1902 }
1903
1904 /* Third byte */
1905 f |= *p << 8;
1906 p += incr;
1907
1908 /* Fourth byte */
1909 f |= *p;
1910
1911 x = (double)f / 8388608.0;
1912
1913 /* XXX This sadly ignores Inf/NaN issues */
1914 if (e == 0)
1915 e = -126;
1916 else {
1917 x += 1.0;
1918 e -= 127;
1919 }
1920 x = ldexp(x, e);
1921
1922 if (sign)
1923 x = -x;
1924
1925 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001926 }
Tim Peters9905b942003-03-20 20:53:32 +00001927 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001928 float x;
1929
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001930 if ((float_format == ieee_little_endian_format && !le)
1931 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001932 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001933 char *d = &buf[3];
1934 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001935
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936 for (i = 0; i < 4; i++) {
1937 *d-- = *p++;
1938 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001939 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940 }
1941 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001942 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001944
1945 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001946 }
Tim Peters9905b942003-03-20 20:53:32 +00001947}
1948
1949double
1950_PyFloat_Unpack8(const unsigned char *p, int le)
1951{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001952 if (double_format == unknown_format) {
1953 unsigned char sign;
1954 int e;
1955 unsigned int fhi, flo;
1956 double x;
1957 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001958
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001959 if (le) {
1960 p += 7;
1961 incr = -1;
1962 }
1963
1964 /* First byte */
1965 sign = (*p >> 7) & 1;
1966 e = (*p & 0x7F) << 4;
1967
1968 p += incr;
1969
1970 /* Second byte */
1971 e |= (*p >> 4) & 0xF;
1972 fhi = (*p & 0xF) << 24;
1973 p += incr;
1974
1975 if (e == 2047) {
1976 PyErr_SetString(
1977 PyExc_ValueError,
1978 "can't unpack IEEE 754 special value "
1979 "on non-IEEE platform");
1980 return -1.0;
1981 }
1982
1983 /* Third byte */
1984 fhi |= *p << 16;
1985 p += incr;
1986
1987 /* Fourth byte */
1988 fhi |= *p << 8;
1989 p += incr;
1990
1991 /* Fifth byte */
1992 fhi |= *p;
1993 p += incr;
1994
1995 /* Sixth byte */
1996 flo = *p << 16;
1997 p += incr;
1998
1999 /* Seventh byte */
2000 flo |= *p << 8;
2001 p += incr;
2002
2003 /* Eighth byte */
2004 flo |= *p;
2005
2006 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2007 x /= 268435456.0; /* 2**28 */
2008
2009 if (e == 0)
2010 e = -1022;
2011 else {
2012 x += 1.0;
2013 e -= 1023;
2014 }
2015 x = ldexp(x, e);
2016
2017 if (sign)
2018 x = -x;
2019
2020 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002021 }
Tim Peters9905b942003-03-20 20:53:32 +00002022 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002023 double x;
2024
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002025 if ((double_format == ieee_little_endian_format && !le)
2026 || (double_format == ieee_big_endian_format && le)) {
2027 char buf[8];
2028 char *d = &buf[7];
2029 int i;
2030
2031 for (i = 0; i < 8; i++) {
2032 *d-- = *p++;
2033 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002034 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002035 }
2036 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002037 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002038 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002039
2040 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002041 }
Tim Peters9905b942003-03-20 20:53:32 +00002042}