blob: bbe8a196162a91b7013cf0c785a3236e86eada50 [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 Heimesc94e2b52008-01-14 04:13:37 +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 Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000013#ifdef HAVE_IEEEFP_H
14#include <ieeefp.h>
15#endif
16
Neal Norwitz5f95a792008-01-25 08:04:16 +000017#ifdef _OSF_SOURCE
18/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
19extern int finite(double);
20#endif
21
Guido van Rossum93ad0df1997-05-13 21:00:42 +000022/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000023#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000024#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000025#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000026
Guido van Rossum3fce8831999-03-12 19:43:17 +000027struct _floatblock {
28 struct _floatblock *next;
29 PyFloatObject objects[N_FLOATOBJECTS];
30};
31
32typedef struct _floatblock PyFloatBlock;
33
34static PyFloatBlock *block_list = NULL;
35static PyFloatObject *free_list = NULL;
36
Guido van Rossum93ad0df1997-05-13 21:00:42 +000037static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000038fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039{
40 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000041 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
42 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000043 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000044 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000045 ((PyFloatBlock *)p)->next = block_list;
46 block_list = (PyFloatBlock *)p;
47 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 q = p + N_FLOATOBJECTS;
49 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000050 Py_TYPE(q) = (struct _typeobject *)(q-1);
51 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000052 return p + N_FLOATOBJECTS - 1;
53}
54
Christian Heimesdfdfaab2007-12-01 11:20:10 +000055double
56PyFloat_GetMax(void)
57{
58 return DBL_MAX;
59}
60
61double
62PyFloat_GetMin(void)
63{
64 return DBL_MIN;
65}
66
Christian Heimes796fc312008-01-30 18:58:29 +000067static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000068
69PyDoc_STRVAR(floatinfo__doc__,
70"sys.floatinfo\n\
71\n\
72A structseq holding information about the float type. It contains low level\n\
73information about the precision and internal representation. Please study\n\
74your system's :file:`float.h` for more information.");
75
76static PyStructSequence_Field floatinfo_fields[] = {
77 {"max", "DBL_MAX -- maximum representable finite float"},
78 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
79 "is representable"},
80 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
81 "is representable"},
82 {"min", "DBL_MIN -- Minimum positive normalizer float"},
83 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
84 "is a normalized float"},
85 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
86 "a normalized"},
87 {"dig", "DBL_DIG -- digits"},
88 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
89 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
90 "representable float"},
91 {"radix", "FLT_RADIX -- radix of exponent"},
92 {"rounds", "FLT_ROUNDS -- addition rounds"},
93 {0}
94};
95
96static PyStructSequence_Desc floatinfo_desc = {
97 "sys.floatinfo", /* name */
98 floatinfo__doc__, /* doc */
99 floatinfo_fields, /* fields */
100 11
101};
102
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000103PyObject *
104PyFloat_GetInfo(void)
105{
Christian Heimes796fc312008-01-30 18:58:29 +0000106 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000107 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108
Christian Heimesc94e2b52008-01-14 04:13:37 +0000109 floatinfo = PyStructSequence_New(&FloatInfoType);
110 if (floatinfo == NULL) {
111 return NULL;
112 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114#define SetIntFlag(flag) \
115 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
116#define SetDblFlag(flag) \
117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Christian Heimesc94e2b52008-01-14 04:13:37 +0000119 SetDblFlag(DBL_MAX);
120 SetIntFlag(DBL_MAX_EXP);
121 SetIntFlag(DBL_MAX_10_EXP);
122 SetDblFlag(DBL_MIN);
123 SetIntFlag(DBL_MIN_EXP);
124 SetIntFlag(DBL_MIN_10_EXP);
125 SetIntFlag(DBL_DIG);
126 SetIntFlag(DBL_MANT_DIG);
127 SetDblFlag(DBL_EPSILON);
128 SetIntFlag(FLT_RADIX);
129 SetIntFlag(FLT_ROUNDS);
130#undef SetIntFlag
131#undef SetDblFlag
132
133 if (PyErr_Occurred()) {
134 Py_CLEAR(floatinfo);
135 return NULL;
136 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000137 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000143 register PyFloatObject *op;
144 if (free_list == NULL) {
145 if ((free_list = fill_free_list()) == NULL)
146 return NULL;
147 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000148 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000149 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000150 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000151 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000152 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000153 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154}
155
Tim Petersef14d732000-09-23 03:39:17 +0000156/**************************************************************************
157RED_FLAG 22-Sep-2000 tim
158PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
159
1601. If v was a regular string, *pend was set to point to its terminating
161 null byte. That's useless (the caller can find that without any
162 help from this function!).
163
1642. If v was a Unicode string, or an object convertible to a character
165 buffer, *pend was set to point into stack trash (the auto temp
166 vector holding the character buffer). That was downright dangerous.
167
168Since we can't change the interface of a public API function, pend is
169still supported but now *officially* useless: if pend is not NULL,
170*pend is set to NULL.
171**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000173PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000175 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000176 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000177 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000178#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000179 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000180#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000181 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000182
Tim Petersef14d732000-09-23 03:39:17 +0000183 if (pend)
184 *pend = NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000185 if (PyString_Check(v)) {
186 s = PyString_AS_STRING(v);
187 len = PyString_GET_SIZE(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000189#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000190 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000191 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000192 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000193 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000194 return NULL;
195 }
Tim Petersef14d732000-09-23 03:39:17 +0000196 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000198 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 NULL))
200 return NULL;
201 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000202 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000203 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000204#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000205 else if (PyObject_AsCharBuffer(v, &s, &len)) {
206 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000207 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000209 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210
Guido van Rossum4c08d552000-03-10 22:55:18 +0000211 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000212 while (*s && isspace(Py_CHARMASK(*s)))
213 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000214 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215 PyErr_SetString(PyExc_ValueError, "empty string for float()");
216 return NULL;
217 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000218 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000219 /* We don't care about overflow or underflow. If the platform supports
220 * them, infinities and signed zeroes (on underflow) are fine.
221 * However, strtod can return 0 for denormalized numbers, where atof
222 * does not. So (alas!) we special-case a zero result. Note that
223 * whether strtod sets errno on underflow is not defined, so we can't
224 * key off errno.
225 */
Tim Peters858346e2000-09-25 21:01:28 +0000226 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000227 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000228 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000229 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000230 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000231 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000232 if (end > last)
233 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000234 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000235 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000236 char *p = (char*)sp;
237 int sign = 1;
238
239 if (*p == '-') {
240 sign = -1;
241 p++;
242 }
243 if (*p == '+') {
244 p++;
245 }
246 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000247 Py_RETURN_INF(sign);
Christian Heimes0a8143f2007-12-18 23:22:54 +0000248 }
249#ifdef Py_NAN
250 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000251 Py_RETURN_NAN;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000252 }
253#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000254 PyOS_snprintf(buffer, sizeof(buffer),
255 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000256 PyErr_SetString(PyExc_ValueError, buffer);
257 return NULL;
258 }
259 /* Since end != s, the platform made *some* kind of sense out
260 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000261 while (*end && isspace(Py_CHARMASK(*end)))
262 end++;
263 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000264 PyOS_snprintf(buffer, sizeof(buffer),
265 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266 PyErr_SetString(PyExc_ValueError, buffer);
267 return NULL;
268 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000269 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000270 PyErr_SetString(PyExc_ValueError,
271 "null byte in argument for float()");
272 return NULL;
273 }
Tim Petersef14d732000-09-23 03:39:17 +0000274 if (x == 0.0) {
275 /* See above -- may have been strtod being anal
276 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000277 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000278 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000279 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000280 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000281 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000282 return PyFloat_FromDouble(x);
283}
284
Guido van Rossum234f9421993-06-17 12:35:49 +0000285static void
Fred Drakefd99de62000-07-09 05:02:18 +0000286float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000287{
Guido van Rossum9475a232001-10-05 20:51:39 +0000288 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000289 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000290 free_list = op;
291 }
292 else
Christian Heimese93237d2007-12-19 02:37:44 +0000293 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000294}
295
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296double
Fred Drakefd99de62000-07-09 05:02:18 +0000297PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 PyNumberMethods *nb;
300 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000301 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000302
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303 if (op && PyFloat_Check(op))
304 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000305
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000306 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308 return -1;
309 }
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Christian Heimese93237d2007-12-19 02:37:44 +0000311 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000312 PyErr_SetString(PyExc_TypeError, "a float is required");
313 return -1;
314 }
315
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000316 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000317 if (fo == NULL)
318 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 if (!PyFloat_Check(fo)) {
320 PyErr_SetString(PyExc_TypeError,
321 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000322 return -1;
323 }
Tim Petersd2364e82001-11-01 20:09:42 +0000324
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000325 val = PyFloat_AS_DOUBLE(fo);
326 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000327
Guido van Rossumb6775db1994-08-01 11:34:53 +0000328 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329}
330
331/* Methods */
332
Tim Peters97019e42001-11-28 22:43:45 +0000333static void
334format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335{
336 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000337 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000338 int i;
339
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340 /* Subroutine for float_repr and float_print.
341 We want float numbers to be recognizable as such,
342 i.e., they should contain a decimal point or an exponent.
343 However, %g may print the number as an integer;
344 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000345
346 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000347 PyOS_snprintf(format, 32, "%%.%ig", precision);
348 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349 cp = buf;
350 if (*cp == '-')
351 cp++;
352 for (; *cp != '\0'; cp++) {
353 /* Any non-digit means it's not an integer;
354 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000355 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356 break;
357 }
358 if (*cp == '\0') {
359 *cp++ = '.';
360 *cp++ = '0';
361 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000362 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000364 /* Checking the next three chars should be more than enough to
365 * detect inf or nan, even on Windows. We check for inf or nan
366 * at last because they are rare cases.
367 */
368 for (i=0; *cp != '\0' && i<3; cp++, i++) {
369 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
370 continue;
371 /* found something that is neither a digit nor point
372 * it might be a NaN or INF
373 */
374#ifdef Py_NAN
375 if (Py_IS_NAN(v->ob_fval)) {
376 strcpy(buf, "nan");
377 }
378 else
379#endif
380 if (Py_IS_INFINITY(v->ob_fval)) {
381 cp = buf;
382 if (*cp == '-')
383 cp++;
384 strcpy(cp, "inf");
385 }
386 break;
387 }
388
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389}
390
Tim Peters97019e42001-11-28 22:43:45 +0000391/* XXX PyFloat_AsStringEx should not be a public API function (for one
392 XXX thing, its signature passes a buffer without a length; for another,
393 XXX it isn't useful outside this file).
394*/
395void
396PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
397{
398 format_float(buf, 100, v, precision);
399}
400
Neil Schemenauer32117e52001-01-04 01:44:34 +0000401/* Macro and helper that convert PyObject obj to a C double and store
402 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000403 slot function. If conversion to double raises an exception, obj is
404 set to NULL, and the function invoking this macro returns NULL. If
405 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
406 stored in obj, and returned from the function invoking this macro.
407*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000408#define CONVERT_TO_DOUBLE(obj, dbl) \
409 if (PyFloat_Check(obj)) \
410 dbl = PyFloat_AS_DOUBLE(obj); \
411 else if (convert_to_double(&(obj), &(dbl)) < 0) \
412 return obj;
413
414static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000415convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000416{
417 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000418
Neil Schemenauer32117e52001-01-04 01:44:34 +0000419 if (PyInt_Check(obj)) {
420 *dbl = (double)PyInt_AS_LONG(obj);
421 }
422 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000423 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000424 if (*dbl == -1.0 && PyErr_Occurred()) {
425 *v = NULL;
426 return -1;
427 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000428 }
429 else {
430 Py_INCREF(Py_NotImplemented);
431 *v = Py_NotImplemented;
432 return -1;
433 }
434 return 0;
435}
436
Guido van Rossum57072eb1999-12-23 19:00:28 +0000437/* Precisions used by repr() and str(), respectively.
438
439 The repr() precision (17 significant decimal digits) is the minimal number
440 that is guaranteed to have enough precision so that if the number is read
441 back in the exact same binary value is recreated. This is true for IEEE
442 floating point by design, and also happens to work for all other modern
443 hardware.
444
445 The str() precision is chosen so that in most cases, the rounding noise
446 created by various operations is suppressed, while giving plenty of
447 precision for practical use.
448
449*/
450
451#define PREC_REPR 17
452#define PREC_STR 12
453
Tim Peters97019e42001-11-28 22:43:45 +0000454/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
455 XXX they pass a char buffer without passing a length.
456*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000457void
Fred Drakefd99de62000-07-09 05:02:18 +0000458PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000459{
Tim Peters97019e42001-11-28 22:43:45 +0000460 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000461}
462
Tim Peters72f98e92001-05-08 15:19:57 +0000463void
464PyFloat_AsReprString(char *buf, PyFloatObject *v)
465{
Tim Peters97019e42001-11-28 22:43:45 +0000466 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000467}
468
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000469/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000470static int
Fred Drakefd99de62000-07-09 05:02:18 +0000471float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472{
473 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000474 format_float(buf, sizeof(buf), v,
475 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000476 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000477 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000478 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000479 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480}
481
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000483float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000485 char buf[100];
486 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000487
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000488 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000489}
490
491static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000492float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000493{
494 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000495 format_float(buf, sizeof(buf), v, PREC_STR);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000496 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000497}
498
Tim Peters307fa782004-09-23 08:06:40 +0000499/* Comparison is pretty much a nightmare. When comparing float to float,
500 * we do it as straightforwardly (and long-windedly) as conceivable, so
501 * that, e.g., Python x == y delivers the same result as the platform
502 * C x == y when x and/or y is a NaN.
503 * When mixing float with an integer type, there's no good *uniform* approach.
504 * Converting the double to an integer obviously doesn't work, since we
505 * may lose info from fractional bits. Converting the integer to a double
506 * also has two failure modes: (1) a long int may trigger overflow (too
507 * large to fit in the dynamic range of a C double); (2) even a C long may have
508 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
509 * 63 bits of precision, but a C double probably has only 53), and then
510 * we can falsely claim equality when low-order integer bits are lost by
511 * coercion to double. So this part is painful too.
512 */
513
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000514static PyObject*
515float_richcompare(PyObject *v, PyObject *w, int op)
516{
517 double i, j;
518 int r = 0;
519
Tim Peters307fa782004-09-23 08:06:40 +0000520 assert(PyFloat_Check(v));
521 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522
Tim Peters307fa782004-09-23 08:06:40 +0000523 /* Switch on the type of w. Set i and j to doubles to be compared,
524 * and op to the richcomp to use.
525 */
526 if (PyFloat_Check(w))
527 j = PyFloat_AS_DOUBLE(w);
528
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000529 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000530 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000531 /* If i is an infinity, its magnitude exceeds any
532 * finite integer, so it doesn't matter which int we
533 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000534 */
535 j = 0.0;
536 else
537 goto Unimplemented;
538 }
539
540 else if (PyInt_Check(w)) {
541 long jj = PyInt_AS_LONG(w);
542 /* In the worst realistic case I can imagine, C double is a
543 * Cray single with 48 bits of precision, and long has 64
544 * bits.
545 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000546#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000547 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
548 if (abs >> 48) {
549 /* Needs more than 48 bits. Make it take the
550 * PyLong path.
551 */
552 PyObject *result;
553 PyObject *ww = PyLong_FromLong(jj);
554
555 if (ww == NULL)
556 return NULL;
557 result = float_richcompare(v, ww, op);
558 Py_DECREF(ww);
559 return result;
560 }
561#endif
562 j = (double)jj;
563 assert((long)j == jj);
564 }
565
566 else if (PyLong_Check(w)) {
567 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
568 int wsign = _PyLong_Sign(w);
569 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000570 int exponent;
571
572 if (vsign != wsign) {
573 /* Magnitudes are irrelevant -- the signs alone
574 * determine the outcome.
575 */
576 i = (double)vsign;
577 j = (double)wsign;
578 goto Compare;
579 }
580 /* The signs are the same. */
581 /* Convert w to a double if it fits. In particular, 0 fits. */
582 nbits = _PyLong_NumBits(w);
583 if (nbits == (size_t)-1 && PyErr_Occurred()) {
584 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000585 * to hold the # of bits. Replace with little doubles
586 * that give the same outcome -- w is so large that
587 * its magnitude must exceed the magnitude of any
588 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000589 */
590 PyErr_Clear();
591 i = (double)vsign;
592 assert(wsign != 0);
593 j = wsign * 2.0;
594 goto Compare;
595 }
596 if (nbits <= 48) {
597 j = PyLong_AsDouble(w);
598 /* It's impossible that <= 48 bits overflowed. */
599 assert(j != -1.0 || ! PyErr_Occurred());
600 goto Compare;
601 }
602 assert(wsign != 0); /* else nbits was 0 */
603 assert(vsign != 0); /* if vsign were 0, then since wsign is
604 * not 0, we would have taken the
605 * vsign != wsign branch at the start */
606 /* We want to work with non-negative numbers. */
607 if (vsign < 0) {
608 /* "Multiply both sides" by -1; this also swaps the
609 * comparator.
610 */
611 i = -i;
612 op = _Py_SwappedOp[op];
613 }
614 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000615 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000616 /* exponent is the # of bits in v before the radix point;
617 * we know that nbits (the # of bits in w) > 48 at this point
618 */
619 if (exponent < 0 || (size_t)exponent < nbits) {
620 i = 1.0;
621 j = 2.0;
622 goto Compare;
623 }
624 if ((size_t)exponent > nbits) {
625 i = 2.0;
626 j = 1.0;
627 goto Compare;
628 }
629 /* v and w have the same number of bits before the radix
630 * point. Construct two longs that have the same comparison
631 * outcome.
632 */
633 {
634 double fracpart;
635 double intpart;
636 PyObject *result = NULL;
637 PyObject *one = NULL;
638 PyObject *vv = NULL;
639 PyObject *ww = w;
640
641 if (wsign < 0) {
642 ww = PyNumber_Negative(w);
643 if (ww == NULL)
644 goto Error;
645 }
646 else
647 Py_INCREF(ww);
648
649 fracpart = modf(i, &intpart);
650 vv = PyLong_FromDouble(intpart);
651 if (vv == NULL)
652 goto Error;
653
654 if (fracpart != 0.0) {
655 /* Shift left, and or a 1 bit into vv
656 * to represent the lost fraction.
657 */
658 PyObject *temp;
659
660 one = PyInt_FromLong(1);
661 if (one == NULL)
662 goto Error;
663
664 temp = PyNumber_Lshift(ww, one);
665 if (temp == NULL)
666 goto Error;
667 Py_DECREF(ww);
668 ww = temp;
669
670 temp = PyNumber_Lshift(vv, one);
671 if (temp == NULL)
672 goto Error;
673 Py_DECREF(vv);
674 vv = temp;
675
676 temp = PyNumber_Or(vv, one);
677 if (temp == NULL)
678 goto Error;
679 Py_DECREF(vv);
680 vv = temp;
681 }
682
683 r = PyObject_RichCompareBool(vv, ww, op);
684 if (r < 0)
685 goto Error;
686 result = PyBool_FromLong(r);
687 Error:
688 Py_XDECREF(vv);
689 Py_XDECREF(ww);
690 Py_XDECREF(one);
691 return result;
692 }
693 } /* else if (PyLong_Check(w)) */
694
695 else /* w isn't float, int, or long */
696 goto Unimplemented;
697
698 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000699 PyFPE_START_PROTECT("richcompare", return NULL)
700 switch (op) {
701 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000702 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000703 break;
704 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000705 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000706 break;
707 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000708 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000709 break;
710 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000711 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000712 break;
713 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000714 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000715 break;
716 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000717 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000718 break;
719 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000720 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000721 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000722
723 Unimplemented:
724 Py_INCREF(Py_NotImplemented);
725 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000726}
727
Guido van Rossum9bfef441993-03-29 10:43:31 +0000728static long
Fred Drakefd99de62000-07-09 05:02:18 +0000729float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000730{
Tim Peters39dce292000-08-15 03:34:48 +0000731 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000732}
733
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000734static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000735float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000737 double a,b;
738 CONVERT_TO_DOUBLE(v, a);
739 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000740 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000741 a = a + b;
742 PyFPE_END_PROTECT(a)
743 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000744}
745
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000746static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000747float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000748{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000749 double a,b;
750 CONVERT_TO_DOUBLE(v, a);
751 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000752 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000753 a = a - b;
754 PyFPE_END_PROTECT(a)
755 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756}
757
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000758static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000759float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000761 double a,b;
762 CONVERT_TO_DOUBLE(v, a);
763 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000764 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000765 a = a * b;
766 PyFPE_END_PROTECT(a)
767 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768}
769
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000771float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000773 double a,b;
774 CONVERT_TO_DOUBLE(v, a);
775 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000776#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000777 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000778 PyErr_SetString(PyExc_ZeroDivisionError,
779 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780 return NULL;
781 }
Christian Heimes6f341092008-04-18 23:13:07 +0000782#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000783 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000784 a = a / b;
785 PyFPE_END_PROTECT(a)
786 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787}
788
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000790float_classic_div(PyObject *v, PyObject *w)
791{
792 double a,b;
793 CONVERT_TO_DOUBLE(v, a);
794 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000795 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000796 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
797 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000798#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000799 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000800 PyErr_SetString(PyExc_ZeroDivisionError,
801 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000802 return NULL;
803 }
Christian Heimes6f341092008-04-18 23:13:07 +0000804#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000805 PyFPE_START_PROTECT("divide", return 0)
806 a = a / b;
807 PyFPE_END_PROTECT(a)
808 return PyFloat_FromDouble(a);
809}
810
811static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000812float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000814 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000815 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000816 CONVERT_TO_DOUBLE(v, vx);
817 CONVERT_TO_DOUBLE(w, wx);
818#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000820 PyErr_SetString(PyExc_ZeroDivisionError,
821 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822 return NULL;
823 }
Christian Heimes6f341092008-04-18 23:13:07 +0000824#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000825 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000826 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000827 /* note: checking mod*wx < 0 is incorrect -- underflows to
828 0 if wx < sqrt(smallest nonzero double) */
829 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000830 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000831 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000832 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000833 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000834}
835
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000837float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000838{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000839 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000840 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000841 CONVERT_TO_DOUBLE(v, vx);
842 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000843 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000844 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000845 return NULL;
846 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000847 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000848 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000849 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000850 exact multiple of wx. But this is fp arithmetic, and fp
851 vx - mod is an approximation; the result is that div may
852 not be an exact integral value after the division, although
853 it will always be very close to one.
854 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000855 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000856 if (mod) {
857 /* ensure the remainder has the same sign as the denominator */
858 if ((wx < 0) != (mod < 0)) {
859 mod += wx;
860 div -= 1.0;
861 }
862 }
863 else {
864 /* the remainder is zero, and in the presence of signed zeroes
865 fmod returns different results across platforms; ensure
866 it has the same sign as the denominator; we'd like to do
867 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000868 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000869 if (wx < 0.0)
870 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000871 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000872 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000873 if (div) {
874 floordiv = floor(div);
875 if (div - floordiv > 0.5)
876 floordiv += 1.0;
877 }
878 else {
879 /* div is zero - get the same sign as the true quotient */
880 div *= div; /* hide "div = +0" from optimizers */
881 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
882 }
883 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000884 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000885}
886
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000887static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000888float_floor_div(PyObject *v, PyObject *w)
889{
890 PyObject *t, *r;
891
892 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000893 if (t == NULL || t == Py_NotImplemented)
894 return t;
895 assert(PyTuple_CheckExact(t));
896 r = PyTuple_GET_ITEM(t, 0);
897 Py_INCREF(r);
898 Py_DECREF(t);
899 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000900}
901
902static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000903float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000904{
905 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000906
907 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000908 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000909 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000910 return NULL;
911 }
912
Neil Schemenauer32117e52001-01-04 01:44:34 +0000913 CONVERT_TO_DOUBLE(v, iv);
914 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000915
916 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000917 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000918 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000919 }
Tim Peters96685bf2001-08-23 22:31:37 +0000920 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000921 if (iw < 0.0) {
922 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000923 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000924 return NULL;
925 }
926 return PyFloat_FromDouble(0.0);
927 }
Christian Heimes6f341092008-04-18 23:13:07 +0000928 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
929 return PyFloat_FromDouble(1.0);
930 }
Tim Peterse87568d2003-05-24 20:18:24 +0000931 if (iv < 0.0) {
932 /* Whether this is an error is a mess, and bumps into libm
933 * bugs so we have to figure it out ourselves.
934 */
935 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000936 PyErr_SetString(PyExc_ValueError, "negative number "
937 "cannot be raised to a fractional power");
938 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000939 }
940 /* iw is an exact integer, albeit perhaps a very large one.
941 * -1 raised to an exact integer should never be exceptional.
942 * Alas, some libms (chiefly glibc as of early 2003) return
943 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
944 * happen to be representable in a *C* integer. That's a
945 * bug; we let that slide in math.pow() (which currently
946 * reflects all platform accidents), but not for Python's **.
947 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000948 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000949 /* Return 1 if iw is even, -1 if iw is odd; there's
950 * no guarantee that any C integral type is big
951 * enough to hold iw, so we have to check this
952 * indirectly.
953 */
954 ix = floor(iw * 0.5) * 2.0;
955 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
956 }
957 /* Else iv != -1.0, and overflow or underflow are possible.
958 * Unless we're to write pow() ourselves, we have to trust
959 * the platform to do this correctly.
960 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000961 }
Tim Peters96685bf2001-08-23 22:31:37 +0000962 errno = 0;
963 PyFPE_START_PROTECT("pow", return NULL)
964 ix = pow(iv, iw);
965 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000966 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000967 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000968 /* We don't expect any errno value other than ERANGE, but
969 * the range of libm bugs appears unbounded.
970 */
Alex Martelli348dc882006-08-23 22:17:59 +0000971 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
972 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000973 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000974 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000976}
977
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000978static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000979float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000980{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000981 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000982}
983
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000985float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000986{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000987 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000988}
989
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000990static int
Fred Drakefd99de62000-07-09 05:02:18 +0000991float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000992{
993 return v->ob_fval != 0.0;
994}
995
Guido van Rossum234f9421993-06-17 12:35:49 +0000996static int
Fred Drakefd99de62000-07-09 05:02:18 +0000997float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000998{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000999 if (PyInt_Check(*pw)) {
1000 long x = PyInt_AsLong(*pw);
1001 *pw = PyFloat_FromDouble((double)x);
1002 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001003 return 0;
1004 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001005 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001006 double x = PyLong_AsDouble(*pw);
1007 if (x == -1.0 && PyErr_Occurred())
1008 return -1;
1009 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001010 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001011 return 0;
1012 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001013 else if (PyFloat_Check(*pw)) {
1014 Py_INCREF(*pv);
1015 Py_INCREF(*pw);
1016 return 0;
1017 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001018 return 1; /* Can't do it */
1019}
1020
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001021static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +00001022float_is_integer(PyObject *v)
1023{
1024 double x = PyFloat_AsDouble(v);
1025 PyObject *o;
1026
1027 if (x == -1.0 && PyErr_Occurred())
1028 return NULL;
1029 if (!Py_IS_FINITE(x))
1030 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +00001031 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +00001032 PyFPE_START_PROTECT("is_integer", return NULL)
1033 o = (floor(x) == x) ? Py_True : Py_False;
1034 PyFPE_END_PROTECT(x)
1035 if (errno != 0) {
1036 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1037 PyExc_ValueError);
1038 return NULL;
1039 }
1040 Py_INCREF(o);
1041 return o;
1042}
1043
1044#if 0
1045static PyObject *
1046float_is_inf(PyObject *v)
1047{
1048 double x = PyFloat_AsDouble(v);
1049 if (x == -1.0 && PyErr_Occurred())
1050 return NULL;
1051 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1052}
1053
1054static PyObject *
1055float_is_nan(PyObject *v)
1056{
1057 double x = PyFloat_AsDouble(v);
1058 if (x == -1.0 && PyErr_Occurred())
1059 return NULL;
1060 return PyBool_FromLong((long)Py_IS_NAN(x));
1061}
1062
1063static PyObject *
1064float_is_finite(PyObject *v)
1065{
1066 double x = PyFloat_AsDouble(v);
1067 if (x == -1.0 && PyErr_Occurred())
1068 return NULL;
1069 return PyBool_FromLong((long)Py_IS_FINITE(x));
1070}
1071#endif
1072
1073static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001074float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001075{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001076 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001077 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001078
1079 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001080 /* Try to get out cheap if this fits in a Python int. The attempt
1081 * to cast to long must be protected, as C doesn't define what
1082 * happens if the double is too big to fit in a long. Some rare
1083 * systems raise an exception then (RISCOS was mentioned as one,
1084 * and someone using a non-default option on Sun also bumped into
1085 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1086 * still be vulnerable: if a long has more bits of precision than
1087 * a double, casting MIN/MAX to double may yield an approximation,
1088 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1089 * yield true from the C expression wholepart<=LONG_MAX, despite
1090 * that wholepart is actually greater than LONG_MAX.
1091 */
1092 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1093 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001094 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001095 }
1096 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001097}
1098
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001099static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001100float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001101{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001102 if (PyFloat_CheckExact(v))
1103 Py_INCREF(v);
1104 else
1105 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001106 return v;
1107}
1108
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001109static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001110float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001111{
1112 double self;
1113 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001114 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001115 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001116
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001117 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001118 PyObject *py_exponent = NULL;
1119 PyObject *numerator = NULL;
1120 PyObject *denominator = NULL;
1121 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001122 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001123
1124#define INPLACE_UPDATE(obj, call) \
1125 prev = obj; \
1126 obj = call; \
1127 Py_DECREF(prev); \
1128
1129 CONVERT_TO_DOUBLE(v, self);
1130
1131 if (Py_IS_INFINITY(self)) {
1132 PyErr_SetString(PyExc_OverflowError,
1133 "Cannot pass infinity to float.as_integer_ratio.");
1134 return NULL;
1135 }
1136#ifdef Py_NAN
1137 if (Py_IS_NAN(self)) {
1138 PyErr_SetString(PyExc_ValueError,
1139 "Cannot pass nan to float.as_integer_ratio.");
1140 return NULL;
1141 }
1142#endif
1143
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001144 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001145 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001146 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001147
Raymond Hettingerf9859032008-02-01 23:45:44 +00001148 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001149 float_part *= 2.0;
1150 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001151 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001152 /* self == float_part * 2**exponent exactly and float_part is integral.
1153 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1154 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001155
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001156 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001157 if (numerator == NULL) goto error;
1158
Raymond Hettingerf9859032008-02-01 23:45:44 +00001159 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001160 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001161 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001162 if (py_exponent == NULL) goto error;
1163 INPLACE_UPDATE(py_exponent,
1164 long_methods->nb_lshift(denominator, py_exponent));
1165 if (py_exponent == NULL) goto error;
1166 if (exponent > 0) {
1167 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001168 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001169 if (numerator == NULL) goto error;
1170 }
1171 else {
1172 Py_DECREF(denominator);
1173 denominator = py_exponent;
1174 py_exponent = NULL;
1175 }
1176
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001177 /* Returns ints instead of longs where possible */
1178 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1179 if (numerator == NULL) goto error;
1180 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1181 if (denominator == NULL) goto error;
1182
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001183 result_pair = PyTuple_Pack(2, numerator, denominator);
1184
1185#undef INPLACE_UPDATE
1186error:
1187 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001188 Py_XDECREF(denominator);
1189 Py_XDECREF(numerator);
1190 return result_pair;
1191}
1192
1193PyDoc_STRVAR(float_as_integer_ratio_doc,
1194"float.as_integer_ratio() -> (int, int)\n"
1195"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001196"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1197"float and with a positive denominator.\n"
1198"Raises OverflowError on infinities and a ValueError on nans.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001199"\n"
1200">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001201"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001202">>> (0.0).as_integer_ratio()\n"
1203"(0, 1)\n"
1204">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001205"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001206
Raymond Hettingere0e71142008-06-21 06:39:53 +00001207static PyObject *
1208_float_to_base(PyFloatObject *v, unaryfunc int_to_base)
1209{
1210 PyObject *mant, *conv, *result;
1211 double x, fr;
1212 int i, exp, n;
1213 char *conv_str;
1214
1215 CONVERT_TO_DOUBLE(((PyObject *)v), x);
1216 if (!Py_IS_FINITE(x))
1217 return PyObject_Repr((PyObject *)v);
1218 fr = frexp(x, &exp);
1219 for (i=0; i<300 && fr != floor(fr) ; i++) {
1220 fr *= 2.0;
1221 exp--;
1222 }
1223 mant = PyLong_FromDouble(floor(fr));
1224 if (mant == NULL)
1225 return NULL;
1226 conv = int_to_base(mant);
1227 Py_DECREF(mant);
1228 if (conv== NULL)
1229 return NULL;
1230 n = PyString_GET_SIZE(conv);
1231 conv_str = PyString_AS_STRING(conv);
1232 /* Remove the trailing 'L' if present */
1233 if (n && conv_str[n-1] == 'L') {
1234 PyObject *newconv = PySequence_GetSlice(conv, 0, -1);
1235 Py_DECREF(conv);
1236 if (newconv == NULL)
1237 return NULL;
1238 conv = newconv;
1239 conv_str = PyString_AS_STRING(conv);
1240 }
1241 result = PyString_FromFormat("%s * 2.0 ** %d", conv_str, exp);
1242 Py_DECREF(conv);
1243 return result;
1244}
1245
1246static PyObject *
1247float_hex(PyFloatObject *v)
1248{
1249 return _float_to_base(v, PyLong_Type.tp_as_number->nb_hex);
1250}
1251
1252static PyObject *
1253float_oct(PyFloatObject *v)
1254{
1255 return _float_to_base(v, PyLong_Type.tp_as_number->nb_oct);
1256}
1257
1258static PyObject *
1259float_bin(PyFloatObject *v)
1260{
1261 return _float_to_base(v, PyLong_Type.tp_as_number->nb_bin);
1262}
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001263
Jeremy Hylton938ace62002-07-17 16:30:39 +00001264static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001265float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1266
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267static PyObject *
1268float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1269{
1270 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001271 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272
Guido van Rossumbef14172001-08-29 15:47:46 +00001273 if (type != &PyFloat_Type)
1274 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1276 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001277 if (PyString_Check(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278 return PyFloat_FromString(x, NULL);
1279 return PyNumber_Float(x);
1280}
1281
Guido van Rossumbef14172001-08-29 15:47:46 +00001282/* Wimpy, slow approach to tp_new calls for subtypes of float:
1283 first create a regular float from whatever arguments we got,
1284 then allocate a subtype instance and initialize its ob_fval
1285 from the regular float. The regular float is then thrown away.
1286*/
1287static PyObject *
1288float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1289{
Anthony Baxter377be112006-04-11 06:54:30 +00001290 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001291
1292 assert(PyType_IsSubtype(type, &PyFloat_Type));
1293 tmp = float_new(&PyFloat_Type, args, kwds);
1294 if (tmp == NULL)
1295 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001296 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001297 newobj = type->tp_alloc(type, 0);
1298 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001299 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001300 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001301 }
Anthony Baxter377be112006-04-11 06:54:30 +00001302 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001303 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001304 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001305}
1306
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001307static PyObject *
1308float_getnewargs(PyFloatObject *v)
1309{
1310 return Py_BuildValue("(d)", v->ob_fval);
1311}
1312
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001313/* this is for the benefit of the pack/unpack routines below */
1314
1315typedef enum {
1316 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1317} float_format_type;
1318
1319static float_format_type double_format, float_format;
1320static float_format_type detected_double_format, detected_float_format;
1321
1322static PyObject *
1323float_getformat(PyTypeObject *v, PyObject* arg)
1324{
1325 char* s;
1326 float_format_type r;
1327
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001328 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001329 PyErr_Format(PyExc_TypeError,
1330 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001331 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001332 return NULL;
1333 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001334 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001335 if (strcmp(s, "double") == 0) {
1336 r = double_format;
1337 }
1338 else if (strcmp(s, "float") == 0) {
1339 r = float_format;
1340 }
1341 else {
1342 PyErr_SetString(PyExc_ValueError,
1343 "__getformat__() argument 1 must be "
1344 "'double' or 'float'");
1345 return NULL;
1346 }
1347
1348 switch (r) {
1349 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001350 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001351 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001352 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001353 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001354 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001355 default:
1356 Py_FatalError("insane float_format or double_format");
1357 return NULL;
1358 }
1359}
1360
1361PyDoc_STRVAR(float_getformat_doc,
1362"float.__getformat__(typestr) -> string\n"
1363"\n"
1364"You probably don't want to use this function. It exists mainly to be\n"
1365"used in Python's test suite.\n"
1366"\n"
1367"typestr must be 'double' or 'float'. This function returns whichever of\n"
1368"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1369"format of floating point numbers used by the C type named by typestr.");
1370
1371static PyObject *
1372float_setformat(PyTypeObject *v, PyObject* args)
1373{
1374 char* typestr;
1375 char* format;
1376 float_format_type f;
1377 float_format_type detected;
1378 float_format_type *p;
1379
1380 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1381 return NULL;
1382
1383 if (strcmp(typestr, "double") == 0) {
1384 p = &double_format;
1385 detected = detected_double_format;
1386 }
1387 else if (strcmp(typestr, "float") == 0) {
1388 p = &float_format;
1389 detected = detected_float_format;
1390 }
1391 else {
1392 PyErr_SetString(PyExc_ValueError,
1393 "__setformat__() argument 1 must "
1394 "be 'double' or 'float'");
1395 return NULL;
1396 }
1397
1398 if (strcmp(format, "unknown") == 0) {
1399 f = unknown_format;
1400 }
1401 else if (strcmp(format, "IEEE, little-endian") == 0) {
1402 f = ieee_little_endian_format;
1403 }
1404 else if (strcmp(format, "IEEE, big-endian") == 0) {
1405 f = ieee_big_endian_format;
1406 }
1407 else {
1408 PyErr_SetString(PyExc_ValueError,
1409 "__setformat__() argument 2 must be "
1410 "'unknown', 'IEEE, little-endian' or "
1411 "'IEEE, big-endian'");
1412 return NULL;
1413
1414 }
1415
1416 if (f != unknown_format && f != detected) {
1417 PyErr_Format(PyExc_ValueError,
1418 "can only set %s format to 'unknown' or the "
1419 "detected platform value", typestr);
1420 return NULL;
1421 }
1422
1423 *p = f;
1424 Py_RETURN_NONE;
1425}
1426
1427PyDoc_STRVAR(float_setformat_doc,
1428"float.__setformat__(typestr, fmt) -> None\n"
1429"\n"
1430"You probably don't want to use this function. It exists mainly to be\n"
1431"used in Python's test suite.\n"
1432"\n"
1433"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1434"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1435"one of the latter two if it appears to match the underlying C reality.\n"
1436"\n"
1437"Overrides the automatic determination of C-level floating point type.\n"
1438"This affects how floats are converted to and from binary strings.");
1439
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001440static PyObject *
1441float_getzero(PyObject *v, void *closure)
1442{
1443 return PyFloat_FromDouble(0.0);
1444}
1445
Eric Smitha9f7d622008-02-17 19:46:49 +00001446static PyObject *
1447float__format__(PyObject *self, PyObject *args)
1448{
1449 PyObject *format_spec;
1450
1451 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1452 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001453 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001454 return _PyFloat_FormatAdvanced(self,
1455 PyBytes_AS_STRING(format_spec),
1456 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001457 if (PyUnicode_Check(format_spec)) {
1458 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001459 PyObject *result;
1460 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001461
Eric Smithdc13b792008-05-30 18:10:04 +00001462 if (str_spec == NULL)
1463 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001464
Eric Smithdc13b792008-05-30 18:10:04 +00001465 result = _PyFloat_FormatAdvanced(self,
1466 PyBytes_AS_STRING(str_spec),
1467 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001468
Eric Smithdc13b792008-05-30 18:10:04 +00001469 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001470 return result;
1471 }
1472 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1473 return NULL;
1474}
1475
1476PyDoc_STRVAR(float__format__doc,
1477"float.__format__(format_spec) -> string\n"
1478"\n"
1479"Formats the float according to format_spec.");
1480
1481
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001482static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001483 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001484 "Returns self, the complex conjugate of any float."},
1485 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1486 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001487 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1488 float_as_integer_ratio_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001489 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1490 "Returns True if the float is an integer."},
1491#if 0
1492 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1493 "Returns True if the float is positive or negative infinite."},
1494 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1495 "Returns True if the float is finite, neither infinite nor NaN."},
1496 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1497 "Returns True if the float is not a number (NaN)."},
1498#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001499 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001500 {"__getformat__", (PyCFunction)float_getformat,
1501 METH_O|METH_CLASS, float_getformat_doc},
1502 {"__setformat__", (PyCFunction)float_setformat,
1503 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001504 {"__format__", (PyCFunction)float__format__,
1505 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001506 {NULL, NULL} /* sentinel */
1507};
1508
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001509static PyGetSetDef float_getset[] = {
1510 {"real",
1511 (getter)float_float, (setter)NULL,
1512 "the real part of a complex number",
1513 NULL},
1514 {"imag",
1515 (getter)float_getzero, (setter)NULL,
1516 "the imaginary part of a complex number",
1517 NULL},
1518 {NULL} /* Sentinel */
1519};
1520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001521PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522"float(x) -> floating point number\n\
1523\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001524Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525
1526
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001527static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001528 float_add, /*nb_add*/
1529 float_sub, /*nb_subtract*/
1530 float_mul, /*nb_multiply*/
1531 float_classic_div, /*nb_divide*/
1532 float_rem, /*nb_remainder*/
1533 float_divmod, /*nb_divmod*/
1534 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001535 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001536 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001537 (unaryfunc)float_abs, /*nb_absolute*/
1538 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001539 0, /*nb_invert*/
1540 0, /*nb_lshift*/
1541 0, /*nb_rshift*/
1542 0, /*nb_and*/
1543 0, /*nb_xor*/
1544 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001545 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001546 float_trunc, /*nb_int*/
1547 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001548 float_float, /*nb_float*/
Raymond Hettingere0e71142008-06-21 06:39:53 +00001549 (unaryfunc)float_oct, /* nb_oct */
1550 (unaryfunc)float_hex, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001551 0, /* nb_inplace_add */
1552 0, /* nb_inplace_subtract */
1553 0, /* nb_inplace_multiply */
1554 0, /* nb_inplace_divide */
1555 0, /* nb_inplace_remainder */
1556 0, /* nb_inplace_power */
1557 0, /* nb_inplace_lshift */
1558 0, /* nb_inplace_rshift */
1559 0, /* nb_inplace_and */
1560 0, /* nb_inplace_xor */
1561 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001562 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001563 float_div, /* nb_true_divide */
1564 0, /* nb_inplace_floor_divide */
1565 0, /* nb_inplace_true_divide */
Raymond Hettingere0e71142008-06-21 06:39:53 +00001566 0, /* nb_index */
1567 (unaryfunc)float_bin, /* nb_bin */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001568};
1569
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001570PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001571 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001572 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001573 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001574 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 (destructor)float_dealloc, /* tp_dealloc */
1576 (printfunc)float_print, /* tp_print */
1577 0, /* tp_getattr */
1578 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001579 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 (reprfunc)float_repr, /* tp_repr */
1581 &float_as_number, /* tp_as_number */
1582 0, /* tp_as_sequence */
1583 0, /* tp_as_mapping */
1584 (hashfunc)float_hash, /* tp_hash */
1585 0, /* tp_call */
1586 (reprfunc)float_str, /* tp_str */
1587 PyObject_GenericGetAttr, /* tp_getattro */
1588 0, /* tp_setattro */
1589 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001590 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1591 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 float_doc, /* tp_doc */
1593 0, /* tp_traverse */
1594 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001595 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 0, /* tp_weaklistoffset */
1597 0, /* tp_iter */
1598 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001599 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001601 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 0, /* tp_base */
1603 0, /* tp_dict */
1604 0, /* tp_descr_get */
1605 0, /* tp_descr_set */
1606 0, /* tp_dictoffset */
1607 0, /* tp_init */
1608 0, /* tp_alloc */
1609 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001610};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001611
1612void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613_PyFloat_Init(void)
1614{
1615 /* We attempt to determine if this machine is using IEEE
1616 floating point formats by peering at the bits of some
1617 carefully chosen values. If it looks like we are on an
1618 IEEE platform, the float packing/unpacking routines can
1619 just copy bits, if not they resort to arithmetic & shifts
1620 and masks. The shifts & masks approach works on all finite
1621 values, but what happens to infinities, NaNs and signed
1622 zeroes on packing is an accident, and attempting to unpack
1623 a NaN or an infinity will raise an exception.
1624
1625 Note that if we're on some whacked-out platform which uses
1626 IEEE formats but isn't strictly little-endian or big-
1627 endian, we will fall back to the portable shifts & masks
1628 method. */
1629
1630#if SIZEOF_DOUBLE == 8
1631 {
1632 double x = 9006104071832581.0;
1633 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1634 detected_double_format = ieee_big_endian_format;
1635 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1636 detected_double_format = ieee_little_endian_format;
1637 else
1638 detected_double_format = unknown_format;
1639 }
1640#else
1641 detected_double_format = unknown_format;
1642#endif
1643
1644#if SIZEOF_FLOAT == 4
1645 {
1646 float y = 16711938.0;
1647 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1648 detected_float_format = ieee_big_endian_format;
1649 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1650 detected_float_format = ieee_little_endian_format;
1651 else
1652 detected_float_format = unknown_format;
1653 }
1654#else
1655 detected_float_format = unknown_format;
1656#endif
1657
1658 double_format = detected_double_format;
1659 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001660
Christian Heimes796fc312008-01-30 18:58:29 +00001661 /* Init float info */
1662 if (FloatInfoType.tp_name == 0)
1663 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001664}
1665
1666void
Christian Heimes422051a2008-02-04 18:00:12 +00001667PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001668{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001669 PyFloatObject *p;
1670 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001671 unsigned i;
Christian Heimes422051a2008-02-04 18:00:12 +00001672 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1673 size_t fsum = 0; /* total unfreed ints */
1674 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001675
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001676 list = block_list;
1677 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001678 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001679 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001680 bc++;
1681 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001682 for (i = 0, p = &list->objects[0];
1683 i < N_FLOATOBJECTS;
1684 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001685 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001686 frem++;
1687 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001688 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001689 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001690 list->next = block_list;
1691 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001692 for (i = 0, p = &list->objects[0];
1693 i < N_FLOATOBJECTS;
1694 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001695 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001696 Py_REFCNT(p) == 0) {
1697 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001698 free_list;
1699 free_list = p;
1700 }
1701 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001702 }
1703 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001704 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001705 bf++;
1706 }
1707 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001708 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001709 }
Christian Heimes422051a2008-02-04 18:00:12 +00001710 *pbc = bc;
1711 *pbf = bf;
1712 *bsum = fsum;
1713}
1714
1715void
1716PyFloat_Fini(void)
1717{
1718 PyFloatObject *p;
1719 PyFloatBlock *list;
1720 unsigned i;
1721 size_t bc, bf; /* block count, number of freed blocks */
1722 size_t fsum; /* total unfreed floats per block */
1723
1724 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1725
Guido van Rossum3fce8831999-03-12 19:43:17 +00001726 if (!Py_VerboseFlag)
1727 return;
1728 fprintf(stderr, "# cleanup floats");
1729 if (!fsum) {
1730 fprintf(stderr, "\n");
1731 }
1732 else {
1733 fprintf(stderr,
Neal Norwitzc0a56ff2008-03-27 06:52:01 +00001734 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes422051a2008-02-04 18:00:12 +00001735 PY_FORMAT_SIZE_T "d out of %"
1736 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001737 fsum, fsum == 1 ? "" : "s",
1738 bc - bf, bc, bc == 1 ? "" : "s");
1739 }
1740 if (Py_VerboseFlag > 1) {
1741 list = block_list;
1742 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001743 for (i = 0, p = &list->objects[0];
1744 i < N_FLOATOBJECTS;
1745 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001746 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001747 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001748 char buf[100];
1749 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001750 /* XXX(twouters) cast refcount to
1751 long until %zd is universally
1752 available
1753 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001754 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001755 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001756 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001757 }
1758 }
1759 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001760 }
1761 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001762}
Tim Peters9905b942003-03-20 20:53:32 +00001763
1764/*----------------------------------------------------------------------------
1765 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001766 */
1767int
1768_PyFloat_Pack4(double x, unsigned char *p, int le)
1769{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001770 if (float_format == unknown_format) {
1771 unsigned char sign;
1772 int e;
1773 double f;
1774 unsigned int fbits;
1775 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001776
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777 if (le) {
1778 p += 3;
1779 incr = -1;
1780 }
Tim Peters9905b942003-03-20 20:53:32 +00001781
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001782 if (x < 0) {
1783 sign = 1;
1784 x = -x;
1785 }
1786 else
1787 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001788
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001789 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001790
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001791 /* Normalize f to be in the range [1.0, 2.0) */
1792 if (0.5 <= f && f < 1.0) {
1793 f *= 2.0;
1794 e--;
1795 }
1796 else if (f == 0.0)
1797 e = 0;
1798 else {
1799 PyErr_SetString(PyExc_SystemError,
1800 "frexp() result out of range");
1801 return -1;
1802 }
1803
1804 if (e >= 128)
1805 goto Overflow;
1806 else if (e < -126) {
1807 /* Gradual underflow */
1808 f = ldexp(f, 126 + e);
1809 e = 0;
1810 }
1811 else if (!(e == 0 && f == 0.0)) {
1812 e += 127;
1813 f -= 1.0; /* Get rid of leading 1 */
1814 }
1815
1816 f *= 8388608.0; /* 2**23 */
1817 fbits = (unsigned int)(f + 0.5); /* Round */
1818 assert(fbits <= 8388608);
1819 if (fbits >> 23) {
1820 /* The carry propagated out of a string of 23 1 bits. */
1821 fbits = 0;
1822 ++e;
1823 if (e >= 255)
1824 goto Overflow;
1825 }
1826
1827 /* First byte */
1828 *p = (sign << 7) | (e >> 1);
1829 p += incr;
1830
1831 /* Second byte */
1832 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1833 p += incr;
1834
1835 /* Third byte */
1836 *p = (fbits >> 8) & 0xFF;
1837 p += incr;
1838
1839 /* Fourth byte */
1840 *p = fbits & 0xFF;
1841
1842 /* Done */
1843 return 0;
1844
Tim Peters9905b942003-03-20 20:53:32 +00001845 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001846 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001847 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001848 const char *s = (char*)&y;
1849 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001850
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001851 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1852 goto Overflow;
1853
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001854 if ((float_format == ieee_little_endian_format && !le)
1855 || (float_format == ieee_big_endian_format && le)) {
1856 p += 3;
1857 incr = -1;
1858 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001859
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001860 for (i = 0; i < 4; i++) {
1861 *p = *s++;
1862 p += incr;
1863 }
1864 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001865 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001866 Overflow:
1867 PyErr_SetString(PyExc_OverflowError,
1868 "float too large to pack with f format");
1869 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001870}
1871
1872int
1873_PyFloat_Pack8(double x, unsigned char *p, int le)
1874{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001875 if (double_format == unknown_format) {
1876 unsigned char sign;
1877 int e;
1878 double f;
1879 unsigned int fhi, flo;
1880 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001881
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001882 if (le) {
1883 p += 7;
1884 incr = -1;
1885 }
Tim Peters9905b942003-03-20 20:53:32 +00001886
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001887 if (x < 0) {
1888 sign = 1;
1889 x = -x;
1890 }
1891 else
1892 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001893
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001894 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001895
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001896 /* Normalize f to be in the range [1.0, 2.0) */
1897 if (0.5 <= f && f < 1.0) {
1898 f *= 2.0;
1899 e--;
1900 }
1901 else if (f == 0.0)
1902 e = 0;
1903 else {
1904 PyErr_SetString(PyExc_SystemError,
1905 "frexp() result out of range");
1906 return -1;
1907 }
1908
1909 if (e >= 1024)
1910 goto Overflow;
1911 else if (e < -1022) {
1912 /* Gradual underflow */
1913 f = ldexp(f, 1022 + e);
1914 e = 0;
1915 }
1916 else if (!(e == 0 && f == 0.0)) {
1917 e += 1023;
1918 f -= 1.0; /* Get rid of leading 1 */
1919 }
1920
1921 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1922 f *= 268435456.0; /* 2**28 */
1923 fhi = (unsigned int)f; /* Truncate */
1924 assert(fhi < 268435456);
1925
1926 f -= (double)fhi;
1927 f *= 16777216.0; /* 2**24 */
1928 flo = (unsigned int)(f + 0.5); /* Round */
1929 assert(flo <= 16777216);
1930 if (flo >> 24) {
1931 /* The carry propagated out of a string of 24 1 bits. */
1932 flo = 0;
1933 ++fhi;
1934 if (fhi >> 28) {
1935 /* And it also progagated out of the next 28 bits. */
1936 fhi = 0;
1937 ++e;
1938 if (e >= 2047)
1939 goto Overflow;
1940 }
1941 }
1942
1943 /* First byte */
1944 *p = (sign << 7) | (e >> 4);
1945 p += incr;
1946
1947 /* Second byte */
1948 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1949 p += incr;
1950
1951 /* Third byte */
1952 *p = (fhi >> 16) & 0xFF;
1953 p += incr;
1954
1955 /* Fourth byte */
1956 *p = (fhi >> 8) & 0xFF;
1957 p += incr;
1958
1959 /* Fifth byte */
1960 *p = fhi & 0xFF;
1961 p += incr;
1962
1963 /* Sixth byte */
1964 *p = (flo >> 16) & 0xFF;
1965 p += incr;
1966
1967 /* Seventh byte */
1968 *p = (flo >> 8) & 0xFF;
1969 p += incr;
1970
1971 /* Eighth byte */
1972 *p = flo & 0xFF;
1973 p += incr;
1974
1975 /* Done */
1976 return 0;
1977
1978 Overflow:
1979 PyErr_SetString(PyExc_OverflowError,
1980 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001981 return -1;
1982 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001983 else {
1984 const char *s = (char*)&x;
1985 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001986
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001987 if ((double_format == ieee_little_endian_format && !le)
1988 || (double_format == ieee_big_endian_format && le)) {
1989 p += 7;
1990 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001991 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001992
1993 for (i = 0; i < 8; i++) {
1994 *p = *s++;
1995 p += incr;
1996 }
1997 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001998 }
Tim Peters9905b942003-03-20 20:53:32 +00001999}
2000
2001double
2002_PyFloat_Unpack4(const unsigned char *p, int le)
2003{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002004 if (float_format == unknown_format) {
2005 unsigned char sign;
2006 int e;
2007 unsigned int f;
2008 double x;
2009 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002010
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002011 if (le) {
2012 p += 3;
2013 incr = -1;
2014 }
2015
2016 /* First byte */
2017 sign = (*p >> 7) & 1;
2018 e = (*p & 0x7F) << 1;
2019 p += incr;
2020
2021 /* Second byte */
2022 e |= (*p >> 7) & 1;
2023 f = (*p & 0x7F) << 16;
2024 p += incr;
2025
2026 if (e == 255) {
2027 PyErr_SetString(
2028 PyExc_ValueError,
2029 "can't unpack IEEE 754 special value "
2030 "on non-IEEE platform");
2031 return -1;
2032 }
2033
2034 /* Third byte */
2035 f |= *p << 8;
2036 p += incr;
2037
2038 /* Fourth byte */
2039 f |= *p;
2040
2041 x = (double)f / 8388608.0;
2042
2043 /* XXX This sadly ignores Inf/NaN issues */
2044 if (e == 0)
2045 e = -126;
2046 else {
2047 x += 1.0;
2048 e -= 127;
2049 }
2050 x = ldexp(x, e);
2051
2052 if (sign)
2053 x = -x;
2054
2055 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002056 }
Tim Peters9905b942003-03-20 20:53:32 +00002057 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002058 float x;
2059
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002060 if ((float_format == ieee_little_endian_format && !le)
2061 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002062 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002063 char *d = &buf[3];
2064 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002065
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002066 for (i = 0; i < 4; i++) {
2067 *d-- = *p++;
2068 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002069 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002070 }
2071 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002072 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002073 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002074
2075 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002076 }
Tim Peters9905b942003-03-20 20:53:32 +00002077}
2078
2079double
2080_PyFloat_Unpack8(const unsigned char *p, int le)
2081{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002082 if (double_format == unknown_format) {
2083 unsigned char sign;
2084 int e;
2085 unsigned int fhi, flo;
2086 double x;
2087 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002088
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002089 if (le) {
2090 p += 7;
2091 incr = -1;
2092 }
2093
2094 /* First byte */
2095 sign = (*p >> 7) & 1;
2096 e = (*p & 0x7F) << 4;
2097
2098 p += incr;
2099
2100 /* Second byte */
2101 e |= (*p >> 4) & 0xF;
2102 fhi = (*p & 0xF) << 24;
2103 p += incr;
2104
2105 if (e == 2047) {
2106 PyErr_SetString(
2107 PyExc_ValueError,
2108 "can't unpack IEEE 754 special value "
2109 "on non-IEEE platform");
2110 return -1.0;
2111 }
2112
2113 /* Third byte */
2114 fhi |= *p << 16;
2115 p += incr;
2116
2117 /* Fourth byte */
2118 fhi |= *p << 8;
2119 p += incr;
2120
2121 /* Fifth byte */
2122 fhi |= *p;
2123 p += incr;
2124
2125 /* Sixth byte */
2126 flo = *p << 16;
2127 p += incr;
2128
2129 /* Seventh byte */
2130 flo |= *p << 8;
2131 p += incr;
2132
2133 /* Eighth byte */
2134 flo |= *p;
2135
2136 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2137 x /= 268435456.0; /* 2**28 */
2138
2139 if (e == 0)
2140 e = -1022;
2141 else {
2142 x += 1.0;
2143 e -= 1023;
2144 }
2145 x = ldexp(x, e);
2146
2147 if (sign)
2148 x = -x;
2149
2150 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002151 }
Tim Peters9905b942003-03-20 20:53:32 +00002152 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002153 double x;
2154
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002155 if ((double_format == ieee_little_endian_format && !le)
2156 || (double_format == ieee_big_endian_format && le)) {
2157 char buf[8];
2158 char *d = &buf[7];
2159 int i;
2160
2161 for (i = 0; i < 8; i++) {
2162 *d-- = *p++;
2163 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002164 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002165 }
2166 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002167 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002168 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002169
2170 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002171 }
Tim Peters9905b942003-03-20 20:53:32 +00002172}