blob: ceb0b6dfb86f92f4b91bfea710aea105a3bd8796 [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
Eric Smitha9f7d622008-02-17 19:46:49 +000017#include "formatter_string.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +000018
Guido van Rossum6923e131990-11-02 17:50:43 +000019
Neal Norwitz5f95a792008-01-25 08:04:16 +000020#ifdef _OSF_SOURCE
21/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
22extern int finite(double);
23#endif
24
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000026#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000027#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000028#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000029
Guido van Rossum3fce8831999-03-12 19:43:17 +000030struct _floatblock {
31 struct _floatblock *next;
32 PyFloatObject objects[N_FLOATOBJECTS];
33};
34
35typedef struct _floatblock PyFloatBlock;
36
37static PyFloatBlock *block_list = NULL;
38static PyFloatObject *free_list = NULL;
39
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000041fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042{
43 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000044 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
45 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000047 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000048 ((PyFloatBlock *)p)->next = block_list;
49 block_list = (PyFloatBlock *)p;
50 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000051 q = p + N_FLOATOBJECTS;
52 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000053 Py_TYPE(q) = (struct _typeobject *)(q-1);
54 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055 return p + N_FLOATOBJECTS - 1;
56}
57
Christian Heimesdfdfaab2007-12-01 11:20:10 +000058double
59PyFloat_GetMax(void)
60{
61 return DBL_MAX;
62}
63
64double
65PyFloat_GetMin(void)
66{
67 return DBL_MIN;
68}
69
Christian Heimes796fc312008-01-30 18:58:29 +000070static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000071
72PyDoc_STRVAR(floatinfo__doc__,
73"sys.floatinfo\n\
74\n\
75A structseq holding information about the float type. It contains low level\n\
76information about the precision and internal representation. Please study\n\
77your system's :file:`float.h` for more information.");
78
79static PyStructSequence_Field floatinfo_fields[] = {
80 {"max", "DBL_MAX -- maximum representable finite float"},
81 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
82 "is representable"},
83 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
84 "is representable"},
85 {"min", "DBL_MIN -- Minimum positive normalizer float"},
86 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
87 "is a normalized float"},
88 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
89 "a normalized"},
90 {"dig", "DBL_DIG -- digits"},
91 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
92 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
93 "representable float"},
94 {"radix", "FLT_RADIX -- radix of exponent"},
95 {"rounds", "FLT_ROUNDS -- addition rounds"},
96 {0}
97};
98
99static PyStructSequence_Desc floatinfo_desc = {
100 "sys.floatinfo", /* name */
101 floatinfo__doc__, /* doc */
102 floatinfo_fields, /* fields */
103 11
104};
105
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000106PyObject *
107PyFloat_GetInfo(void)
108{
Christian Heimes796fc312008-01-30 18:58:29 +0000109 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000110 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000111
Christian Heimesc94e2b52008-01-14 04:13:37 +0000112 floatinfo = PyStructSequence_New(&FloatInfoType);
113 if (floatinfo == NULL) {
114 return NULL;
115 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000116
Christian Heimesc94e2b52008-01-14 04:13:37 +0000117#define SetIntFlag(flag) \
118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
119#define SetDblFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000121
Christian Heimesc94e2b52008-01-14 04:13:37 +0000122 SetDblFlag(DBL_MAX);
123 SetIntFlag(DBL_MAX_EXP);
124 SetIntFlag(DBL_MAX_10_EXP);
125 SetDblFlag(DBL_MIN);
126 SetIntFlag(DBL_MIN_EXP);
127 SetIntFlag(DBL_MIN_10_EXP);
128 SetIntFlag(DBL_DIG);
129 SetIntFlag(DBL_MANT_DIG);
130 SetDblFlag(DBL_EPSILON);
131 SetIntFlag(FLT_RADIX);
132 SetIntFlag(FLT_ROUNDS);
133#undef SetIntFlag
134#undef SetDblFlag
135
136 if (PyErr_Occurred()) {
137 Py_CLEAR(floatinfo);
138 return NULL;
139 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000140 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000141}
142
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000146 register PyFloatObject *op;
147 if (free_list == NULL) {
148 if ((free_list = fill_free_list()) == NULL)
149 return NULL;
150 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000151 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000152 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000153 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000154 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000155 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157}
158
Tim Petersef14d732000-09-23 03:39:17 +0000159/**************************************************************************
160RED_FLAG 22-Sep-2000 tim
161PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
162
1631. If v was a regular string, *pend was set to point to its terminating
164 null byte. That's useless (the caller can find that without any
165 help from this function!).
166
1672. If v was a Unicode string, or an object convertible to a character
168 buffer, *pend was set to point into stack trash (the auto temp
169 vector holding the character buffer). That was downright dangerous.
170
171Since we can't change the interface of a public API function, pend is
172still supported but now *officially* useless: if pend is not NULL,
173*pend is set to NULL.
174**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000176PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000178 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000180 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000181#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000182 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000184 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000185
Tim Petersef14d732000-09-23 03:39:17 +0000186 if (pend)
187 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000188 if (PyString_Check(v)) {
189 s = PyString_AS_STRING(v);
190 len = PyString_GET_SIZE(v);
191 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000192#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000193 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000194 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000195 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000196 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 return NULL;
198 }
Tim Petersef14d732000-09-23 03:39:17 +0000199 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000200 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000201 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 NULL))
203 return NULL;
204 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000205 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000206 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000207#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000208 else if (PyObject_AsCharBuffer(v, &s, &len)) {
209 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000210 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000211 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000212 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215 while (*s && isspace(Py_CHARMASK(*s)))
216 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000217 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 PyErr_SetString(PyExc_ValueError, "empty string for float()");
219 return NULL;
220 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000221 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000222 /* We don't care about overflow or underflow. If the platform supports
223 * them, infinities and signed zeroes (on underflow) are fine.
224 * However, strtod can return 0 for denormalized numbers, where atof
225 * does not. So (alas!) we special-case a zero result. Note that
226 * whether strtod sets errno on underflow is not defined, so we can't
227 * key off errno.
228 */
Tim Peters858346e2000-09-25 21:01:28 +0000229 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000230 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000231 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000232 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000233 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000234 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000235 if (end > last)
236 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000237 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000238 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000239 char *p = (char*)sp;
240 int sign = 1;
241
242 if (*p == '-') {
243 sign = -1;
244 p++;
245 }
246 if (*p == '+') {
247 p++;
248 }
249 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000250 Py_RETURN_INF(sign);
Christian Heimes0a8143f2007-12-18 23:22:54 +0000251 }
252#ifdef Py_NAN
253 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000254 Py_RETURN_NAN;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000255 }
256#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000257 PyOS_snprintf(buffer, sizeof(buffer),
258 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000259 PyErr_SetString(PyExc_ValueError, buffer);
260 return NULL;
261 }
262 /* Since end != s, the platform made *some* kind of sense out
263 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000264 while (*end && isspace(Py_CHARMASK(*end)))
265 end++;
266 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000267 PyOS_snprintf(buffer, sizeof(buffer),
268 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000269 PyErr_SetString(PyExc_ValueError, buffer);
270 return NULL;
271 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000272 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000273 PyErr_SetString(PyExc_ValueError,
274 "null byte in argument for float()");
275 return NULL;
276 }
Tim Petersef14d732000-09-23 03:39:17 +0000277 if (x == 0.0) {
278 /* See above -- may have been strtod being anal
279 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000280 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000281 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000282 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000283 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000284 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000285 return PyFloat_FromDouble(x);
286}
287
Guido van Rossum234f9421993-06-17 12:35:49 +0000288static void
Fred Drakefd99de62000-07-09 05:02:18 +0000289float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000290{
Guido van Rossum9475a232001-10-05 20:51:39 +0000291 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000292 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000293 free_list = op;
294 }
295 else
Christian Heimese93237d2007-12-19 02:37:44 +0000296 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000297}
298
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299double
Fred Drakefd99de62000-07-09 05:02:18 +0000300PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 PyNumberMethods *nb;
303 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000304 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000305
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 if (op && PyFloat_Check(op))
307 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000308
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000309 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000310 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311 return -1;
312 }
Tim Petersd2364e82001-11-01 20:09:42 +0000313
Christian Heimese93237d2007-12-19 02:37:44 +0000314 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000315 PyErr_SetString(PyExc_TypeError, "a float is required");
316 return -1;
317 }
318
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000320 if (fo == NULL)
321 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322 if (!PyFloat_Check(fo)) {
323 PyErr_SetString(PyExc_TypeError,
324 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000325 return -1;
326 }
Tim Petersd2364e82001-11-01 20:09:42 +0000327
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 val = PyFloat_AS_DOUBLE(fo);
329 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000330
Guido van Rossumb6775db1994-08-01 11:34:53 +0000331 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332}
333
334/* Methods */
335
Tim Peters97019e42001-11-28 22:43:45 +0000336static void
337format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338{
339 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000340 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000341 int i;
342
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343 /* Subroutine for float_repr and float_print.
344 We want float numbers to be recognizable as such,
345 i.e., they should contain a decimal point or an exponent.
346 However, %g may print the number as an integer;
347 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000348
349 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000350 PyOS_snprintf(format, 32, "%%.%ig", precision);
351 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352 cp = buf;
353 if (*cp == '-')
354 cp++;
355 for (; *cp != '\0'; cp++) {
356 /* Any non-digit means it's not an integer;
357 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000358 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359 break;
360 }
361 if (*cp == '\0') {
362 *cp++ = '.';
363 *cp++ = '0';
364 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000365 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000367 /* Checking the next three chars should be more than enough to
368 * detect inf or nan, even on Windows. We check for inf or nan
369 * at last because they are rare cases.
370 */
371 for (i=0; *cp != '\0' && i<3; cp++, i++) {
372 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
373 continue;
374 /* found something that is neither a digit nor point
375 * it might be a NaN or INF
376 */
377#ifdef Py_NAN
378 if (Py_IS_NAN(v->ob_fval)) {
379 strcpy(buf, "nan");
380 }
381 else
382#endif
383 if (Py_IS_INFINITY(v->ob_fval)) {
384 cp = buf;
385 if (*cp == '-')
386 cp++;
387 strcpy(cp, "inf");
388 }
389 break;
390 }
391
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392}
393
Tim Peters97019e42001-11-28 22:43:45 +0000394/* XXX PyFloat_AsStringEx should not be a public API function (for one
395 XXX thing, its signature passes a buffer without a length; for another,
396 XXX it isn't useful outside this file).
397*/
398void
399PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
400{
401 format_float(buf, 100, v, precision);
402}
403
Neil Schemenauer32117e52001-01-04 01:44:34 +0000404/* Macro and helper that convert PyObject obj to a C double and store
405 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000406 slot function. If conversion to double raises an exception, obj is
407 set to NULL, and the function invoking this macro returns NULL. If
408 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
409 stored in obj, and returned from the function invoking this macro.
410*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000411#define CONVERT_TO_DOUBLE(obj, dbl) \
412 if (PyFloat_Check(obj)) \
413 dbl = PyFloat_AS_DOUBLE(obj); \
414 else if (convert_to_double(&(obj), &(dbl)) < 0) \
415 return obj;
416
417static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000418convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000419{
420 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000421
Neil Schemenauer32117e52001-01-04 01:44:34 +0000422 if (PyInt_Check(obj)) {
423 *dbl = (double)PyInt_AS_LONG(obj);
424 }
425 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000426 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000427 if (*dbl == -1.0 && PyErr_Occurred()) {
428 *v = NULL;
429 return -1;
430 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000431 }
432 else {
433 Py_INCREF(Py_NotImplemented);
434 *v = Py_NotImplemented;
435 return -1;
436 }
437 return 0;
438}
439
Guido van Rossum57072eb1999-12-23 19:00:28 +0000440/* Precisions used by repr() and str(), respectively.
441
442 The repr() precision (17 significant decimal digits) is the minimal number
443 that is guaranteed to have enough precision so that if the number is read
444 back in the exact same binary value is recreated. This is true for IEEE
445 floating point by design, and also happens to work for all other modern
446 hardware.
447
448 The str() precision is chosen so that in most cases, the rounding noise
449 created by various operations is suppressed, while giving plenty of
450 precision for practical use.
451
452*/
453
454#define PREC_REPR 17
455#define PREC_STR 12
456
Tim Peters97019e42001-11-28 22:43:45 +0000457/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
458 XXX they pass a char buffer without passing a length.
459*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000460void
Fred Drakefd99de62000-07-09 05:02:18 +0000461PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000462{
Tim Peters97019e42001-11-28 22:43:45 +0000463 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000464}
465
Tim Peters72f98e92001-05-08 15:19:57 +0000466void
467PyFloat_AsReprString(char *buf, PyFloatObject *v)
468{
Tim Peters97019e42001-11-28 22:43:45 +0000469 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000470}
471
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000472/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000473static int
Fred Drakefd99de62000-07-09 05:02:18 +0000474float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475{
476 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000477 format_float(buf, sizeof(buf), v,
478 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000479 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000481 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000482 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000483}
484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000486float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000488 char buf[100];
489 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000490
Guido van Rossum57072eb1999-12-23 19:00:28 +0000491 return PyString_FromString(buf);
492}
493
494static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000495float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000496{
497 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000498 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500}
501
Tim Peters307fa782004-09-23 08:06:40 +0000502/* Comparison is pretty much a nightmare. When comparing float to float,
503 * we do it as straightforwardly (and long-windedly) as conceivable, so
504 * that, e.g., Python x == y delivers the same result as the platform
505 * C x == y when x and/or y is a NaN.
506 * When mixing float with an integer type, there's no good *uniform* approach.
507 * Converting the double to an integer obviously doesn't work, since we
508 * may lose info from fractional bits. Converting the integer to a double
509 * also has two failure modes: (1) a long int may trigger overflow (too
510 * large to fit in the dynamic range of a C double); (2) even a C long may have
511 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
512 * 63 bits of precision, but a C double probably has only 53), and then
513 * we can falsely claim equality when low-order integer bits are lost by
514 * coercion to double. So this part is painful too.
515 */
516
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000517static PyObject*
518float_richcompare(PyObject *v, PyObject *w, int op)
519{
520 double i, j;
521 int r = 0;
522
Tim Peters307fa782004-09-23 08:06:40 +0000523 assert(PyFloat_Check(v));
524 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000525
Tim Peters307fa782004-09-23 08:06:40 +0000526 /* Switch on the type of w. Set i and j to doubles to be compared,
527 * and op to the richcomp to use.
528 */
529 if (PyFloat_Check(w))
530 j = PyFloat_AS_DOUBLE(w);
531
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000532 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000533 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000534 /* If i is an infinity, its magnitude exceeds any
535 * finite integer, so it doesn't matter which int we
536 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000537 */
538 j = 0.0;
539 else
540 goto Unimplemented;
541 }
542
543 else if (PyInt_Check(w)) {
544 long jj = PyInt_AS_LONG(w);
545 /* In the worst realistic case I can imagine, C double is a
546 * Cray single with 48 bits of precision, and long has 64
547 * bits.
548 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000549#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000550 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
551 if (abs >> 48) {
552 /* Needs more than 48 bits. Make it take the
553 * PyLong path.
554 */
555 PyObject *result;
556 PyObject *ww = PyLong_FromLong(jj);
557
558 if (ww == NULL)
559 return NULL;
560 result = float_richcompare(v, ww, op);
561 Py_DECREF(ww);
562 return result;
563 }
564#endif
565 j = (double)jj;
566 assert((long)j == jj);
567 }
568
569 else if (PyLong_Check(w)) {
570 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
571 int wsign = _PyLong_Sign(w);
572 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000573 int exponent;
574
575 if (vsign != wsign) {
576 /* Magnitudes are irrelevant -- the signs alone
577 * determine the outcome.
578 */
579 i = (double)vsign;
580 j = (double)wsign;
581 goto Compare;
582 }
583 /* The signs are the same. */
584 /* Convert w to a double if it fits. In particular, 0 fits. */
585 nbits = _PyLong_NumBits(w);
586 if (nbits == (size_t)-1 && PyErr_Occurred()) {
587 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000588 * to hold the # of bits. Replace with little doubles
589 * that give the same outcome -- w is so large that
590 * its magnitude must exceed the magnitude of any
591 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000592 */
593 PyErr_Clear();
594 i = (double)vsign;
595 assert(wsign != 0);
596 j = wsign * 2.0;
597 goto Compare;
598 }
599 if (nbits <= 48) {
600 j = PyLong_AsDouble(w);
601 /* It's impossible that <= 48 bits overflowed. */
602 assert(j != -1.0 || ! PyErr_Occurred());
603 goto Compare;
604 }
605 assert(wsign != 0); /* else nbits was 0 */
606 assert(vsign != 0); /* if vsign were 0, then since wsign is
607 * not 0, we would have taken the
608 * vsign != wsign branch at the start */
609 /* We want to work with non-negative numbers. */
610 if (vsign < 0) {
611 /* "Multiply both sides" by -1; this also swaps the
612 * comparator.
613 */
614 i = -i;
615 op = _Py_SwappedOp[op];
616 }
617 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000618 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000619 /* exponent is the # of bits in v before the radix point;
620 * we know that nbits (the # of bits in w) > 48 at this point
621 */
622 if (exponent < 0 || (size_t)exponent < nbits) {
623 i = 1.0;
624 j = 2.0;
625 goto Compare;
626 }
627 if ((size_t)exponent > nbits) {
628 i = 2.0;
629 j = 1.0;
630 goto Compare;
631 }
632 /* v and w have the same number of bits before the radix
633 * point. Construct two longs that have the same comparison
634 * outcome.
635 */
636 {
637 double fracpart;
638 double intpart;
639 PyObject *result = NULL;
640 PyObject *one = NULL;
641 PyObject *vv = NULL;
642 PyObject *ww = w;
643
644 if (wsign < 0) {
645 ww = PyNumber_Negative(w);
646 if (ww == NULL)
647 goto Error;
648 }
649 else
650 Py_INCREF(ww);
651
652 fracpart = modf(i, &intpart);
653 vv = PyLong_FromDouble(intpart);
654 if (vv == NULL)
655 goto Error;
656
657 if (fracpart != 0.0) {
658 /* Shift left, and or a 1 bit into vv
659 * to represent the lost fraction.
660 */
661 PyObject *temp;
662
663 one = PyInt_FromLong(1);
664 if (one == NULL)
665 goto Error;
666
667 temp = PyNumber_Lshift(ww, one);
668 if (temp == NULL)
669 goto Error;
670 Py_DECREF(ww);
671 ww = temp;
672
673 temp = PyNumber_Lshift(vv, one);
674 if (temp == NULL)
675 goto Error;
676 Py_DECREF(vv);
677 vv = temp;
678
679 temp = PyNumber_Or(vv, one);
680 if (temp == NULL)
681 goto Error;
682 Py_DECREF(vv);
683 vv = temp;
684 }
685
686 r = PyObject_RichCompareBool(vv, ww, op);
687 if (r < 0)
688 goto Error;
689 result = PyBool_FromLong(r);
690 Error:
691 Py_XDECREF(vv);
692 Py_XDECREF(ww);
693 Py_XDECREF(one);
694 return result;
695 }
696 } /* else if (PyLong_Check(w)) */
697
698 else /* w isn't float, int, or long */
699 goto Unimplemented;
700
701 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000702 PyFPE_START_PROTECT("richcompare", return NULL)
703 switch (op) {
704 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000705 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000706 break;
707 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000708 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000709 break;
710 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000711 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000712 break;
713 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000714 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000715 break;
716 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000717 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000718 break;
719 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000720 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000721 break;
722 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000723 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000724 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000725
726 Unimplemented:
727 Py_INCREF(Py_NotImplemented);
728 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000729}
730
Guido van Rossum9bfef441993-03-29 10:43:31 +0000731static long
Fred Drakefd99de62000-07-09 05:02:18 +0000732float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000733{
Tim Peters39dce292000-08-15 03:34:48 +0000734 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000735}
736
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000738float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000739{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000740 double a,b;
741 CONVERT_TO_DOUBLE(v, a);
742 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000743 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000744 a = a + b;
745 PyFPE_END_PROTECT(a)
746 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000747}
748
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000750float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000752 double a,b;
753 CONVERT_TO_DOUBLE(v, a);
754 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000755 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000756 a = a - b;
757 PyFPE_END_PROTECT(a)
758 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759}
760
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000762float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000764 double a,b;
765 CONVERT_TO_DOUBLE(v, a);
766 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000767 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000768 a = a * b;
769 PyFPE_END_PROTECT(a)
770 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771}
772
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000774float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000776 double a,b;
777 CONVERT_TO_DOUBLE(v, a);
778 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000779#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000780 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000781 PyErr_SetString(PyExc_ZeroDivisionError,
782 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783 return NULL;
784 }
Christian Heimes6f341092008-04-18 23:13:07 +0000785#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000786 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000787 a = a / b;
788 PyFPE_END_PROTECT(a)
789 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790}
791
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000792static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000793float_classic_div(PyObject *v, PyObject *w)
794{
795 double a,b;
796 CONVERT_TO_DOUBLE(v, a);
797 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000798 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000799 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
800 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000801#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000802 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000803 PyErr_SetString(PyExc_ZeroDivisionError,
804 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000805 return NULL;
806 }
Christian Heimes6f341092008-04-18 23:13:07 +0000807#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000808 PyFPE_START_PROTECT("divide", return 0)
809 a = a / b;
810 PyFPE_END_PROTECT(a)
811 return PyFloat_FromDouble(a);
812}
813
814static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000815float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000817 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000818 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000819 CONVERT_TO_DOUBLE(v, vx);
820 CONVERT_TO_DOUBLE(w, wx);
821#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000823 PyErr_SetString(PyExc_ZeroDivisionError,
824 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825 return NULL;
826 }
Christian Heimes6f341092008-04-18 23:13:07 +0000827#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000828 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000829 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000830 /* note: checking mod*wx < 0 is incorrect -- underflows to
831 0 if wx < sqrt(smallest nonzero double) */
832 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000833 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000834 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000835 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837}
838
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000839static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000840float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000841{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000842 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000843 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000844 CONVERT_TO_DOUBLE(v, vx);
845 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000846 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000847 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000848 return NULL;
849 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000850 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000851 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000852 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000853 exact multiple of wx. But this is fp arithmetic, and fp
854 vx - mod is an approximation; the result is that div may
855 not be an exact integral value after the division, although
856 it will always be very close to one.
857 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000858 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000859 if (mod) {
860 /* ensure the remainder has the same sign as the denominator */
861 if ((wx < 0) != (mod < 0)) {
862 mod += wx;
863 div -= 1.0;
864 }
865 }
866 else {
867 /* the remainder is zero, and in the presence of signed zeroes
868 fmod returns different results across platforms; ensure
869 it has the same sign as the denominator; we'd like to do
870 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000871 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000872 if (wx < 0.0)
873 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000874 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000875 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000876 if (div) {
877 floordiv = floor(div);
878 if (div - floordiv > 0.5)
879 floordiv += 1.0;
880 }
881 else {
882 /* div is zero - get the same sign as the true quotient */
883 div *= div; /* hide "div = +0" from optimizers */
884 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
885 }
886 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000887 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000888}
889
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000890static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000891float_floor_div(PyObject *v, PyObject *w)
892{
893 PyObject *t, *r;
894
895 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000896 if (t == NULL || t == Py_NotImplemented)
897 return t;
898 assert(PyTuple_CheckExact(t));
899 r = PyTuple_GET_ITEM(t, 0);
900 Py_INCREF(r);
901 Py_DECREF(t);
902 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000903}
904
905static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000906float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000907{
908 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000909
910 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000911 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000912 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000913 return NULL;
914 }
915
Neil Schemenauer32117e52001-01-04 01:44:34 +0000916 CONVERT_TO_DOUBLE(v, iv);
917 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000918
919 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000920 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000921 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000922 }
Tim Peters96685bf2001-08-23 22:31:37 +0000923 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000924 if (iw < 0.0) {
925 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000926 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000927 return NULL;
928 }
929 return PyFloat_FromDouble(0.0);
930 }
Christian Heimes6f341092008-04-18 23:13:07 +0000931 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
932 return PyFloat_FromDouble(1.0);
933 }
Tim Peterse87568d2003-05-24 20:18:24 +0000934 if (iv < 0.0) {
935 /* Whether this is an error is a mess, and bumps into libm
936 * bugs so we have to figure it out ourselves.
937 */
938 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000939 PyErr_SetString(PyExc_ValueError, "negative number "
940 "cannot be raised to a fractional power");
941 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000942 }
943 /* iw is an exact integer, albeit perhaps a very large one.
944 * -1 raised to an exact integer should never be exceptional.
945 * Alas, some libms (chiefly glibc as of early 2003) return
946 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
947 * happen to be representable in a *C* integer. That's a
948 * bug; we let that slide in math.pow() (which currently
949 * reflects all platform accidents), but not for Python's **.
950 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000951 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000952 /* Return 1 if iw is even, -1 if iw is odd; there's
953 * no guarantee that any C integral type is big
954 * enough to hold iw, so we have to check this
955 * indirectly.
956 */
957 ix = floor(iw * 0.5) * 2.0;
958 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
959 }
960 /* Else iv != -1.0, and overflow or underflow are possible.
961 * Unless we're to write pow() ourselves, we have to trust
962 * the platform to do this correctly.
963 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000964 }
Tim Peters96685bf2001-08-23 22:31:37 +0000965 errno = 0;
966 PyFPE_START_PROTECT("pow", return NULL)
967 ix = pow(iv, iw);
968 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000969 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000970 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000971 /* We don't expect any errno value other than ERANGE, but
972 * the range of libm bugs appears unbounded.
973 */
Alex Martelli348dc882006-08-23 22:17:59 +0000974 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
975 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000976 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000977 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000978 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000979}
980
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000981static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000982float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000983{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000985}
986
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000987static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000988float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000989{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000990 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000991}
992
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000993static int
Fred Drakefd99de62000-07-09 05:02:18 +0000994float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000995{
996 return v->ob_fval != 0.0;
997}
998
Guido van Rossum234f9421993-06-17 12:35:49 +0000999static int
Fred Drakefd99de62000-07-09 05:02:18 +00001000float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001001{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001002 if (PyInt_Check(*pw)) {
1003 long x = PyInt_AsLong(*pw);
1004 *pw = PyFloat_FromDouble((double)x);
1005 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001006 return 0;
1007 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001008 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001009 double x = PyLong_AsDouble(*pw);
1010 if (x == -1.0 && PyErr_Occurred())
1011 return -1;
1012 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001014 return 0;
1015 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001016 else if (PyFloat_Check(*pw)) {
1017 Py_INCREF(*pv);
1018 Py_INCREF(*pw);
1019 return 0;
1020 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001021 return 1; /* Can't do it */
1022}
1023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +00001025float_is_integer(PyObject *v)
1026{
1027 double x = PyFloat_AsDouble(v);
1028 PyObject *o;
1029
1030 if (x == -1.0 && PyErr_Occurred())
1031 return NULL;
1032 if (!Py_IS_FINITE(x))
1033 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +00001034 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +00001035 PyFPE_START_PROTECT("is_integer", return NULL)
1036 o = (floor(x) == x) ? Py_True : Py_False;
1037 PyFPE_END_PROTECT(x)
1038 if (errno != 0) {
1039 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1040 PyExc_ValueError);
1041 return NULL;
1042 }
1043 Py_INCREF(o);
1044 return o;
1045}
1046
1047#if 0
1048static PyObject *
1049float_is_inf(PyObject *v)
1050{
1051 double x = PyFloat_AsDouble(v);
1052 if (x == -1.0 && PyErr_Occurred())
1053 return NULL;
1054 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1055}
1056
1057static PyObject *
1058float_is_nan(PyObject *v)
1059{
1060 double x = PyFloat_AsDouble(v);
1061 if (x == -1.0 && PyErr_Occurred())
1062 return NULL;
1063 return PyBool_FromLong((long)Py_IS_NAN(x));
1064}
1065
1066static PyObject *
1067float_is_finite(PyObject *v)
1068{
1069 double x = PyFloat_AsDouble(v);
1070 if (x == -1.0 && PyErr_Occurred())
1071 return NULL;
1072 return PyBool_FromLong((long)Py_IS_FINITE(x));
1073}
1074#endif
1075
1076static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001077float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001078{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001079 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001080 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001081
1082 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001083 /* Try to get out cheap if this fits in a Python int. The attempt
1084 * to cast to long must be protected, as C doesn't define what
1085 * happens if the double is too big to fit in a long. Some rare
1086 * systems raise an exception then (RISCOS was mentioned as one,
1087 * and someone using a non-default option on Sun also bumped into
1088 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1089 * still be vulnerable: if a long has more bits of precision than
1090 * a double, casting MIN/MAX to double may yield an approximation,
1091 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1092 * yield true from the C expression wholepart<=LONG_MAX, despite
1093 * that wholepart is actually greater than LONG_MAX.
1094 */
1095 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1096 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001097 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001098 }
1099 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001100}
1101
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001102static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001103float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001104{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001105 if (PyFloat_CheckExact(v))
1106 Py_INCREF(v);
1107 else
1108 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001109 return v;
1110}
1111
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001112static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001113float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001114{
1115 double self;
1116 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001117 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001118 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001119
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001120 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001121 PyObject *py_exponent = NULL;
1122 PyObject *numerator = NULL;
1123 PyObject *denominator = NULL;
1124 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001125 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001126
1127#define INPLACE_UPDATE(obj, call) \
1128 prev = obj; \
1129 obj = call; \
1130 Py_DECREF(prev); \
1131
1132 CONVERT_TO_DOUBLE(v, self);
1133
1134 if (Py_IS_INFINITY(self)) {
1135 PyErr_SetString(PyExc_OverflowError,
1136 "Cannot pass infinity to float.as_integer_ratio.");
1137 return NULL;
1138 }
1139#ifdef Py_NAN
1140 if (Py_IS_NAN(self)) {
1141 PyErr_SetString(PyExc_ValueError,
1142 "Cannot pass nan to float.as_integer_ratio.");
1143 return NULL;
1144 }
1145#endif
1146
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001147 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001148 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001149 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001150
Raymond Hettingerf9859032008-02-01 23:45:44 +00001151 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001152 float_part *= 2.0;
1153 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001154 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001155 /* self == float_part * 2**exponent exactly and float_part is integral.
1156 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1157 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001158
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001159 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001160 if (numerator == NULL) goto error;
1161
Raymond Hettingerf9859032008-02-01 23:45:44 +00001162 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001163 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001164 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001165 if (py_exponent == NULL) goto error;
1166 INPLACE_UPDATE(py_exponent,
1167 long_methods->nb_lshift(denominator, py_exponent));
1168 if (py_exponent == NULL) goto error;
1169 if (exponent > 0) {
1170 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001171 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001172 if (numerator == NULL) goto error;
1173 }
1174 else {
1175 Py_DECREF(denominator);
1176 denominator = py_exponent;
1177 py_exponent = NULL;
1178 }
1179
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001180 /* Returns ints instead of longs where possible */
1181 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1182 if (numerator == NULL) goto error;
1183 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1184 if (denominator == NULL) goto error;
1185
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001186 result_pair = PyTuple_Pack(2, numerator, denominator);
1187
1188#undef INPLACE_UPDATE
1189error:
1190 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001191 Py_XDECREF(denominator);
1192 Py_XDECREF(numerator);
1193 return result_pair;
1194}
1195
1196PyDoc_STRVAR(float_as_integer_ratio_doc,
1197"float.as_integer_ratio() -> (int, int)\n"
1198"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001199"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1200"float and with a positive denominator.\n"
1201"Raises OverflowError on infinities and a ValueError on nans.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001202"\n"
1203">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001204"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001205">>> (0.0).as_integer_ratio()\n"
1206"(0, 1)\n"
1207">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001208"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001209
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001210
Jeremy Hylton938ace62002-07-17 16:30:39 +00001211static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001212float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1213
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214static PyObject *
1215float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1216{
1217 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001218 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219
Guido van Rossumbef14172001-08-29 15:47:46 +00001220 if (type != &PyFloat_Type)
1221 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1223 return NULL;
1224 if (PyString_Check(x))
1225 return PyFloat_FromString(x, NULL);
1226 return PyNumber_Float(x);
1227}
1228
Guido van Rossumbef14172001-08-29 15:47:46 +00001229/* Wimpy, slow approach to tp_new calls for subtypes of float:
1230 first create a regular float from whatever arguments we got,
1231 then allocate a subtype instance and initialize its ob_fval
1232 from the regular float. The regular float is then thrown away.
1233*/
1234static PyObject *
1235float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1236{
Anthony Baxter377be112006-04-11 06:54:30 +00001237 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001238
1239 assert(PyType_IsSubtype(type, &PyFloat_Type));
1240 tmp = float_new(&PyFloat_Type, args, kwds);
1241 if (tmp == NULL)
1242 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001243 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001244 newobj = type->tp_alloc(type, 0);
1245 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001246 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001247 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001248 }
Anthony Baxter377be112006-04-11 06:54:30 +00001249 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001250 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001251 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001252}
1253
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001254static PyObject *
1255float_getnewargs(PyFloatObject *v)
1256{
1257 return Py_BuildValue("(d)", v->ob_fval);
1258}
1259
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001260/* this is for the benefit of the pack/unpack routines below */
1261
1262typedef enum {
1263 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1264} float_format_type;
1265
1266static float_format_type double_format, float_format;
1267static float_format_type detected_double_format, detected_float_format;
1268
1269static PyObject *
1270float_getformat(PyTypeObject *v, PyObject* arg)
1271{
1272 char* s;
1273 float_format_type r;
1274
1275 if (!PyString_Check(arg)) {
1276 PyErr_Format(PyExc_TypeError,
1277 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001278 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001279 return NULL;
1280 }
1281 s = PyString_AS_STRING(arg);
1282 if (strcmp(s, "double") == 0) {
1283 r = double_format;
1284 }
1285 else if (strcmp(s, "float") == 0) {
1286 r = float_format;
1287 }
1288 else {
1289 PyErr_SetString(PyExc_ValueError,
1290 "__getformat__() argument 1 must be "
1291 "'double' or 'float'");
1292 return NULL;
1293 }
1294
1295 switch (r) {
1296 case unknown_format:
1297 return PyString_FromString("unknown");
1298 case ieee_little_endian_format:
1299 return PyString_FromString("IEEE, little-endian");
1300 case ieee_big_endian_format:
1301 return PyString_FromString("IEEE, big-endian");
1302 default:
1303 Py_FatalError("insane float_format or double_format");
1304 return NULL;
1305 }
1306}
1307
1308PyDoc_STRVAR(float_getformat_doc,
1309"float.__getformat__(typestr) -> string\n"
1310"\n"
1311"You probably don't want to use this function. It exists mainly to be\n"
1312"used in Python's test suite.\n"
1313"\n"
1314"typestr must be 'double' or 'float'. This function returns whichever of\n"
1315"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1316"format of floating point numbers used by the C type named by typestr.");
1317
1318static PyObject *
1319float_setformat(PyTypeObject *v, PyObject* args)
1320{
1321 char* typestr;
1322 char* format;
1323 float_format_type f;
1324 float_format_type detected;
1325 float_format_type *p;
1326
1327 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1328 return NULL;
1329
1330 if (strcmp(typestr, "double") == 0) {
1331 p = &double_format;
1332 detected = detected_double_format;
1333 }
1334 else if (strcmp(typestr, "float") == 0) {
1335 p = &float_format;
1336 detected = detected_float_format;
1337 }
1338 else {
1339 PyErr_SetString(PyExc_ValueError,
1340 "__setformat__() argument 1 must "
1341 "be 'double' or 'float'");
1342 return NULL;
1343 }
1344
1345 if (strcmp(format, "unknown") == 0) {
1346 f = unknown_format;
1347 }
1348 else if (strcmp(format, "IEEE, little-endian") == 0) {
1349 f = ieee_little_endian_format;
1350 }
1351 else if (strcmp(format, "IEEE, big-endian") == 0) {
1352 f = ieee_big_endian_format;
1353 }
1354 else {
1355 PyErr_SetString(PyExc_ValueError,
1356 "__setformat__() argument 2 must be "
1357 "'unknown', 'IEEE, little-endian' or "
1358 "'IEEE, big-endian'");
1359 return NULL;
1360
1361 }
1362
1363 if (f != unknown_format && f != detected) {
1364 PyErr_Format(PyExc_ValueError,
1365 "can only set %s format to 'unknown' or the "
1366 "detected platform value", typestr);
1367 return NULL;
1368 }
1369
1370 *p = f;
1371 Py_RETURN_NONE;
1372}
1373
1374PyDoc_STRVAR(float_setformat_doc,
1375"float.__setformat__(typestr, fmt) -> None\n"
1376"\n"
1377"You probably don't want to use this function. It exists mainly to be\n"
1378"used in Python's test suite.\n"
1379"\n"
1380"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1381"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1382"one of the latter two if it appears to match the underlying C reality.\n"
1383"\n"
1384"Overrides the automatic determination of C-level floating point type.\n"
1385"This affects how floats are converted to and from binary strings.");
1386
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001387static PyObject *
1388float_getzero(PyObject *v, void *closure)
1389{
1390 return PyFloat_FromDouble(0.0);
1391}
1392
Eric Smitha9f7d622008-02-17 19:46:49 +00001393static PyObject *
1394float__format__(PyObject *self, PyObject *args)
1395{
1396 PyObject *format_spec;
1397
1398 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1399 return NULL;
1400 if (PyString_Check(format_spec))
1401 return string_float__format__(self, args);
1402 if (PyUnicode_Check(format_spec)) {
1403 /* Convert format_spec to a str */
1404 PyObject *result = NULL;
1405 PyObject *newargs = NULL;
1406 PyObject *string_format_spec = NULL;
1407
1408 string_format_spec = PyObject_Str(format_spec);
1409 if (string_format_spec == NULL)
1410 goto done;
1411
1412 newargs = Py_BuildValue("(O)", string_format_spec);
1413 if (newargs == NULL)
1414 goto done;
1415
1416 result = string_float__format__(self, newargs);
1417
1418 done:
1419 Py_XDECREF(string_format_spec);
1420 Py_XDECREF(newargs);
1421 return result;
1422 }
1423 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1424 return NULL;
1425}
1426
1427PyDoc_STRVAR(float__format__doc,
1428"float.__format__(format_spec) -> string\n"
1429"\n"
1430"Formats the float according to format_spec.");
1431
1432
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001433static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001434 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001435 "Returns self, the complex conjugate of any float."},
1436 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1437 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001438 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1439 float_as_integer_ratio_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001440 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1441 "Returns True if the float is an integer."},
1442#if 0
1443 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1444 "Returns True if the float is positive or negative infinite."},
1445 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1446 "Returns True if the float is finite, neither infinite nor NaN."},
1447 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1448 "Returns True if the float is not a number (NaN)."},
1449#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001450 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001451 {"__getformat__", (PyCFunction)float_getformat,
1452 METH_O|METH_CLASS, float_getformat_doc},
1453 {"__setformat__", (PyCFunction)float_setformat,
1454 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001455 {"__format__", (PyCFunction)float__format__,
1456 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001457 {NULL, NULL} /* sentinel */
1458};
1459
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001460static PyGetSetDef float_getset[] = {
1461 {"real",
1462 (getter)float_float, (setter)NULL,
1463 "the real part of a complex number",
1464 NULL},
1465 {"imag",
1466 (getter)float_getzero, (setter)NULL,
1467 "the imaginary part of a complex number",
1468 NULL},
1469 {NULL} /* Sentinel */
1470};
1471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001472PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001473"float(x) -> floating point number\n\
1474\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001475Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476
1477
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001478static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001479 float_add, /*nb_add*/
1480 float_sub, /*nb_subtract*/
1481 float_mul, /*nb_multiply*/
1482 float_classic_div, /*nb_divide*/
1483 float_rem, /*nb_remainder*/
1484 float_divmod, /*nb_divmod*/
1485 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001486 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001487 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001488 (unaryfunc)float_abs, /*nb_absolute*/
1489 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001490 0, /*nb_invert*/
1491 0, /*nb_lshift*/
1492 0, /*nb_rshift*/
1493 0, /*nb_and*/
1494 0, /*nb_xor*/
1495 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001496 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001497 float_trunc, /*nb_int*/
1498 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001499 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001500 0, /* nb_oct */
1501 0, /* nb_hex */
1502 0, /* nb_inplace_add */
1503 0, /* nb_inplace_subtract */
1504 0, /* nb_inplace_multiply */
1505 0, /* nb_inplace_divide */
1506 0, /* nb_inplace_remainder */
1507 0, /* nb_inplace_power */
1508 0, /* nb_inplace_lshift */
1509 0, /* nb_inplace_rshift */
1510 0, /* nb_inplace_and */
1511 0, /* nb_inplace_xor */
1512 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001513 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001514 float_div, /* nb_true_divide */
1515 0, /* nb_inplace_floor_divide */
1516 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001517};
1518
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001519PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001520 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001521 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001522 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001523 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524 (destructor)float_dealloc, /* tp_dealloc */
1525 (printfunc)float_print, /* tp_print */
1526 0, /* tp_getattr */
1527 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001528 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 (reprfunc)float_repr, /* tp_repr */
1530 &float_as_number, /* tp_as_number */
1531 0, /* tp_as_sequence */
1532 0, /* tp_as_mapping */
1533 (hashfunc)float_hash, /* tp_hash */
1534 0, /* tp_call */
1535 (reprfunc)float_str, /* tp_str */
1536 PyObject_GenericGetAttr, /* tp_getattro */
1537 0, /* tp_setattro */
1538 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001539 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1540 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 float_doc, /* tp_doc */
1542 0, /* tp_traverse */
1543 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001544 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 0, /* tp_weaklistoffset */
1546 0, /* tp_iter */
1547 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001548 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001550 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 0, /* tp_base */
1552 0, /* tp_dict */
1553 0, /* tp_descr_get */
1554 0, /* tp_descr_set */
1555 0, /* tp_dictoffset */
1556 0, /* tp_init */
1557 0, /* tp_alloc */
1558 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001559};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001560
1561void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001562_PyFloat_Init(void)
1563{
1564 /* We attempt to determine if this machine is using IEEE
1565 floating point formats by peering at the bits of some
1566 carefully chosen values. If it looks like we are on an
1567 IEEE platform, the float packing/unpacking routines can
1568 just copy bits, if not they resort to arithmetic & shifts
1569 and masks. The shifts & masks approach works on all finite
1570 values, but what happens to infinities, NaNs and signed
1571 zeroes on packing is an accident, and attempting to unpack
1572 a NaN or an infinity will raise an exception.
1573
1574 Note that if we're on some whacked-out platform which uses
1575 IEEE formats but isn't strictly little-endian or big-
1576 endian, we will fall back to the portable shifts & masks
1577 method. */
1578
1579#if SIZEOF_DOUBLE == 8
1580 {
1581 double x = 9006104071832581.0;
1582 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1583 detected_double_format = ieee_big_endian_format;
1584 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1585 detected_double_format = ieee_little_endian_format;
1586 else
1587 detected_double_format = unknown_format;
1588 }
1589#else
1590 detected_double_format = unknown_format;
1591#endif
1592
1593#if SIZEOF_FLOAT == 4
1594 {
1595 float y = 16711938.0;
1596 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1597 detected_float_format = ieee_big_endian_format;
1598 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1599 detected_float_format = ieee_little_endian_format;
1600 else
1601 detected_float_format = unknown_format;
1602 }
1603#else
1604 detected_float_format = unknown_format;
1605#endif
1606
1607 double_format = detected_double_format;
1608 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001609
Christian Heimes796fc312008-01-30 18:58:29 +00001610 /* Init float info */
1611 if (FloatInfoType.tp_name == 0)
1612 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001613}
1614
1615void
Christian Heimes422051a2008-02-04 18:00:12 +00001616PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001617{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001618 PyFloatObject *p;
1619 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001620 unsigned i;
Christian Heimes422051a2008-02-04 18:00:12 +00001621 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1622 size_t fsum = 0; /* total unfreed ints */
1623 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001624
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001625 list = block_list;
1626 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001627 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001628 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001629 bc++;
1630 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001631 for (i = 0, p = &list->objects[0];
1632 i < N_FLOATOBJECTS;
1633 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001634 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001635 frem++;
1636 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001637 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001638 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001639 list->next = block_list;
1640 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001641 for (i = 0, p = &list->objects[0];
1642 i < N_FLOATOBJECTS;
1643 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001644 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001645 Py_REFCNT(p) == 0) {
1646 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001647 free_list;
1648 free_list = p;
1649 }
1650 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001651 }
1652 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001653 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001654 bf++;
1655 }
1656 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001657 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001658 }
Christian Heimes422051a2008-02-04 18:00:12 +00001659 *pbc = bc;
1660 *pbf = bf;
1661 *bsum = fsum;
1662}
1663
1664void
1665PyFloat_Fini(void)
1666{
1667 PyFloatObject *p;
1668 PyFloatBlock *list;
1669 unsigned i;
1670 size_t bc, bf; /* block count, number of freed blocks */
1671 size_t fsum; /* total unfreed floats per block */
1672
1673 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1674
Guido van Rossum3fce8831999-03-12 19:43:17 +00001675 if (!Py_VerboseFlag)
1676 return;
1677 fprintf(stderr, "# cleanup floats");
1678 if (!fsum) {
1679 fprintf(stderr, "\n");
1680 }
1681 else {
1682 fprintf(stderr,
Neal Norwitzc0a56ff2008-03-27 06:52:01 +00001683 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes422051a2008-02-04 18:00:12 +00001684 PY_FORMAT_SIZE_T "d out of %"
1685 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001686 fsum, fsum == 1 ? "" : "s",
1687 bc - bf, bc, bc == 1 ? "" : "s");
1688 }
1689 if (Py_VerboseFlag > 1) {
1690 list = block_list;
1691 while (list != NULL) {
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) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001697 char buf[100];
1698 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001699 /* XXX(twouters) cast refcount to
1700 long until %zd is universally
1701 available
1702 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001703 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001704 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001705 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001706 }
1707 }
1708 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001709 }
1710 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001711}
Tim Peters9905b942003-03-20 20:53:32 +00001712
1713/*----------------------------------------------------------------------------
1714 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001715 */
1716int
1717_PyFloat_Pack4(double x, unsigned char *p, int le)
1718{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001719 if (float_format == unknown_format) {
1720 unsigned char sign;
1721 int e;
1722 double f;
1723 unsigned int fbits;
1724 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001725
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001726 if (le) {
1727 p += 3;
1728 incr = -1;
1729 }
Tim Peters9905b942003-03-20 20:53:32 +00001730
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731 if (x < 0) {
1732 sign = 1;
1733 x = -x;
1734 }
1735 else
1736 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001737
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001738 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001739
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001740 /* Normalize f to be in the range [1.0, 2.0) */
1741 if (0.5 <= f && f < 1.0) {
1742 f *= 2.0;
1743 e--;
1744 }
1745 else if (f == 0.0)
1746 e = 0;
1747 else {
1748 PyErr_SetString(PyExc_SystemError,
1749 "frexp() result out of range");
1750 return -1;
1751 }
1752
1753 if (e >= 128)
1754 goto Overflow;
1755 else if (e < -126) {
1756 /* Gradual underflow */
1757 f = ldexp(f, 126 + e);
1758 e = 0;
1759 }
1760 else if (!(e == 0 && f == 0.0)) {
1761 e += 127;
1762 f -= 1.0; /* Get rid of leading 1 */
1763 }
1764
1765 f *= 8388608.0; /* 2**23 */
1766 fbits = (unsigned int)(f + 0.5); /* Round */
1767 assert(fbits <= 8388608);
1768 if (fbits >> 23) {
1769 /* The carry propagated out of a string of 23 1 bits. */
1770 fbits = 0;
1771 ++e;
1772 if (e >= 255)
1773 goto Overflow;
1774 }
1775
1776 /* First byte */
1777 *p = (sign << 7) | (e >> 1);
1778 p += incr;
1779
1780 /* Second byte */
1781 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1782 p += incr;
1783
1784 /* Third byte */
1785 *p = (fbits >> 8) & 0xFF;
1786 p += incr;
1787
1788 /* Fourth byte */
1789 *p = fbits & 0xFF;
1790
1791 /* Done */
1792 return 0;
1793
Tim Peters9905b942003-03-20 20:53:32 +00001794 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001795 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001796 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001797 const char *s = (char*)&y;
1798 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001799
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001800 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1801 goto Overflow;
1802
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001803 if ((float_format == ieee_little_endian_format && !le)
1804 || (float_format == ieee_big_endian_format && le)) {
1805 p += 3;
1806 incr = -1;
1807 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001808
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001809 for (i = 0; i < 4; i++) {
1810 *p = *s++;
1811 p += incr;
1812 }
1813 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001814 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001815 Overflow:
1816 PyErr_SetString(PyExc_OverflowError,
1817 "float too large to pack with f format");
1818 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001819}
1820
1821int
1822_PyFloat_Pack8(double x, unsigned char *p, int le)
1823{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001824 if (double_format == unknown_format) {
1825 unsigned char sign;
1826 int e;
1827 double f;
1828 unsigned int fhi, flo;
1829 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001830
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001831 if (le) {
1832 p += 7;
1833 incr = -1;
1834 }
Tim Peters9905b942003-03-20 20:53:32 +00001835
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001836 if (x < 0) {
1837 sign = 1;
1838 x = -x;
1839 }
1840 else
1841 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001842
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001843 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001844
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001845 /* Normalize f to be in the range [1.0, 2.0) */
1846 if (0.5 <= f && f < 1.0) {
1847 f *= 2.0;
1848 e--;
1849 }
1850 else if (f == 0.0)
1851 e = 0;
1852 else {
1853 PyErr_SetString(PyExc_SystemError,
1854 "frexp() result out of range");
1855 return -1;
1856 }
1857
1858 if (e >= 1024)
1859 goto Overflow;
1860 else if (e < -1022) {
1861 /* Gradual underflow */
1862 f = ldexp(f, 1022 + e);
1863 e = 0;
1864 }
1865 else if (!(e == 0 && f == 0.0)) {
1866 e += 1023;
1867 f -= 1.0; /* Get rid of leading 1 */
1868 }
1869
1870 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1871 f *= 268435456.0; /* 2**28 */
1872 fhi = (unsigned int)f; /* Truncate */
1873 assert(fhi < 268435456);
1874
1875 f -= (double)fhi;
1876 f *= 16777216.0; /* 2**24 */
1877 flo = (unsigned int)(f + 0.5); /* Round */
1878 assert(flo <= 16777216);
1879 if (flo >> 24) {
1880 /* The carry propagated out of a string of 24 1 bits. */
1881 flo = 0;
1882 ++fhi;
1883 if (fhi >> 28) {
1884 /* And it also progagated out of the next 28 bits. */
1885 fhi = 0;
1886 ++e;
1887 if (e >= 2047)
1888 goto Overflow;
1889 }
1890 }
1891
1892 /* First byte */
1893 *p = (sign << 7) | (e >> 4);
1894 p += incr;
1895
1896 /* Second byte */
1897 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1898 p += incr;
1899
1900 /* Third byte */
1901 *p = (fhi >> 16) & 0xFF;
1902 p += incr;
1903
1904 /* Fourth byte */
1905 *p = (fhi >> 8) & 0xFF;
1906 p += incr;
1907
1908 /* Fifth byte */
1909 *p = fhi & 0xFF;
1910 p += incr;
1911
1912 /* Sixth byte */
1913 *p = (flo >> 16) & 0xFF;
1914 p += incr;
1915
1916 /* Seventh byte */
1917 *p = (flo >> 8) & 0xFF;
1918 p += incr;
1919
1920 /* Eighth byte */
1921 *p = flo & 0xFF;
1922 p += incr;
1923
1924 /* Done */
1925 return 0;
1926
1927 Overflow:
1928 PyErr_SetString(PyExc_OverflowError,
1929 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001930 return -1;
1931 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001932 else {
1933 const char *s = (char*)&x;
1934 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001935
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001936 if ((double_format == ieee_little_endian_format && !le)
1937 || (double_format == ieee_big_endian_format && le)) {
1938 p += 7;
1939 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001940 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001941
1942 for (i = 0; i < 8; i++) {
1943 *p = *s++;
1944 p += incr;
1945 }
1946 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001947 }
Tim Peters9905b942003-03-20 20:53:32 +00001948}
1949
1950double
1951_PyFloat_Unpack4(const unsigned char *p, int le)
1952{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001953 if (float_format == unknown_format) {
1954 unsigned char sign;
1955 int e;
1956 unsigned int f;
1957 double x;
1958 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001959
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001960 if (le) {
1961 p += 3;
1962 incr = -1;
1963 }
1964
1965 /* First byte */
1966 sign = (*p >> 7) & 1;
1967 e = (*p & 0x7F) << 1;
1968 p += incr;
1969
1970 /* Second byte */
1971 e |= (*p >> 7) & 1;
1972 f = (*p & 0x7F) << 16;
1973 p += incr;
1974
1975 if (e == 255) {
1976 PyErr_SetString(
1977 PyExc_ValueError,
1978 "can't unpack IEEE 754 special value "
1979 "on non-IEEE platform");
1980 return -1;
1981 }
1982
1983 /* Third byte */
1984 f |= *p << 8;
1985 p += incr;
1986
1987 /* Fourth byte */
1988 f |= *p;
1989
1990 x = (double)f / 8388608.0;
1991
1992 /* XXX This sadly ignores Inf/NaN issues */
1993 if (e == 0)
1994 e = -126;
1995 else {
1996 x += 1.0;
1997 e -= 127;
1998 }
1999 x = ldexp(x, e);
2000
2001 if (sign)
2002 x = -x;
2003
2004 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002005 }
Tim Peters9905b942003-03-20 20:53:32 +00002006 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002007 float x;
2008
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 if ((float_format == ieee_little_endian_format && !le)
2010 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002011 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012 char *d = &buf[3];
2013 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002014
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015 for (i = 0; i < 4; i++) {
2016 *d-- = *p++;
2017 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002018 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002019 }
2020 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002021 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002022 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002023
2024 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002025 }
Tim Peters9905b942003-03-20 20:53:32 +00002026}
2027
2028double
2029_PyFloat_Unpack8(const unsigned char *p, int le)
2030{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002031 if (double_format == unknown_format) {
2032 unsigned char sign;
2033 int e;
2034 unsigned int fhi, flo;
2035 double x;
2036 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002037
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002038 if (le) {
2039 p += 7;
2040 incr = -1;
2041 }
2042
2043 /* First byte */
2044 sign = (*p >> 7) & 1;
2045 e = (*p & 0x7F) << 4;
2046
2047 p += incr;
2048
2049 /* Second byte */
2050 e |= (*p >> 4) & 0xF;
2051 fhi = (*p & 0xF) << 24;
2052 p += incr;
2053
2054 if (e == 2047) {
2055 PyErr_SetString(
2056 PyExc_ValueError,
2057 "can't unpack IEEE 754 special value "
2058 "on non-IEEE platform");
2059 return -1.0;
2060 }
2061
2062 /* Third byte */
2063 fhi |= *p << 16;
2064 p += incr;
2065
2066 /* Fourth byte */
2067 fhi |= *p << 8;
2068 p += incr;
2069
2070 /* Fifth byte */
2071 fhi |= *p;
2072 p += incr;
2073
2074 /* Sixth byte */
2075 flo = *p << 16;
2076 p += incr;
2077
2078 /* Seventh byte */
2079 flo |= *p << 8;
2080 p += incr;
2081
2082 /* Eighth byte */
2083 flo |= *p;
2084
2085 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2086 x /= 268435456.0; /* 2**28 */
2087
2088 if (e == 0)
2089 e = -1022;
2090 else {
2091 x += 1.0;
2092 e -= 1023;
2093 }
2094 x = ldexp(x, e);
2095
2096 if (sign)
2097 x = -x;
2098
2099 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002100 }
Tim Peters9905b942003-03-20 20:53:32 +00002101 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002102 double x;
2103
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002104 if ((double_format == ieee_little_endian_format && !le)
2105 || (double_format == ieee_big_endian_format && le)) {
2106 char buf[8];
2107 char *d = &buf[7];
2108 int i;
2109
2110 for (i = 0; i < 8; i++) {
2111 *d-- = *p++;
2112 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002113 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002114 }
2115 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002116 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002118
2119 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002120 }
Tim Peters9905b942003-03-20 20:53:32 +00002121}