blob: 45cb9059f59c66f2608cb4b163bb538d3fc364b9 [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 }
Mark Dickinsonbf9f4d82008-07-05 11:33:52 +0000249 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
250 Py_RETURN_INF(sign);
251 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000252#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*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +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;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000416
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
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000491 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000492}
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);
Gregory P. Smithdd96db62008-06-09 04:58:54 +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;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001224 if (PyString_Check(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 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
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001275 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001276 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 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001281 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001282 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:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001297 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001298 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001299 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001300 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001301 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001302 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;
Christian Heimes593daf52008-05-26 12:51:38 +00001400 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001401 return _PyFloat_FormatAdvanced(self,
1402 PyBytes_AS_STRING(format_spec),
1403 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001404 if (PyUnicode_Check(format_spec)) {
1405 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001406 PyObject *result;
1407 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001408
Eric Smithdc13b792008-05-30 18:10:04 +00001409 if (str_spec == NULL)
1410 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001411
Eric Smithdc13b792008-05-30 18:10:04 +00001412 result = _PyFloat_FormatAdvanced(self,
1413 PyBytes_AS_STRING(str_spec),
1414 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001415
Eric Smithdc13b792008-05-30 18:10:04 +00001416 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001417 return result;
1418 }
1419 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1420 return NULL;
1421}
1422
1423PyDoc_STRVAR(float__format__doc,
1424"float.__format__(format_spec) -> string\n"
1425"\n"
1426"Formats the float according to format_spec.");
1427
1428
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001429static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001430 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001431 "Returns self, the complex conjugate of any float."},
1432 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1433 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001434 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1435 float_as_integer_ratio_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001436 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1437 "Returns True if the float is an integer."},
1438#if 0
1439 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1440 "Returns True if the float is positive or negative infinite."},
1441 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1442 "Returns True if the float is finite, neither infinite nor NaN."},
1443 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1444 "Returns True if the float is not a number (NaN)."},
1445#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001446 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001447 {"__getformat__", (PyCFunction)float_getformat,
1448 METH_O|METH_CLASS, float_getformat_doc},
1449 {"__setformat__", (PyCFunction)float_setformat,
1450 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001451 {"__format__", (PyCFunction)float__format__,
1452 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001453 {NULL, NULL} /* sentinel */
1454};
1455
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001456static PyGetSetDef float_getset[] = {
1457 {"real",
1458 (getter)float_float, (setter)NULL,
1459 "the real part of a complex number",
1460 NULL},
1461 {"imag",
1462 (getter)float_getzero, (setter)NULL,
1463 "the imaginary part of a complex number",
1464 NULL},
1465 {NULL} /* Sentinel */
1466};
1467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001468PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001469"float(x) -> floating point number\n\
1470\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001471Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472
1473
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001474static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001475 float_add, /*nb_add*/
1476 float_sub, /*nb_subtract*/
1477 float_mul, /*nb_multiply*/
1478 float_classic_div, /*nb_divide*/
1479 float_rem, /*nb_remainder*/
1480 float_divmod, /*nb_divmod*/
1481 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001482 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001483 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001484 (unaryfunc)float_abs, /*nb_absolute*/
1485 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001486 0, /*nb_invert*/
1487 0, /*nb_lshift*/
1488 0, /*nb_rshift*/
1489 0, /*nb_and*/
1490 0, /*nb_xor*/
1491 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001492 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001493 float_trunc, /*nb_int*/
1494 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001495 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001496 0, /* nb_oct */
1497 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001498 0, /* nb_inplace_add */
1499 0, /* nb_inplace_subtract */
1500 0, /* nb_inplace_multiply */
1501 0, /* nb_inplace_divide */
1502 0, /* nb_inplace_remainder */
1503 0, /* nb_inplace_power */
1504 0, /* nb_inplace_lshift */
1505 0, /* nb_inplace_rshift */
1506 0, /* nb_inplace_and */
1507 0, /* nb_inplace_xor */
1508 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001509 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001510 float_div, /* nb_true_divide */
1511 0, /* nb_inplace_floor_divide */
1512 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001513};
1514
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001515PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001516 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001517 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001518 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001519 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 (destructor)float_dealloc, /* tp_dealloc */
1521 (printfunc)float_print, /* tp_print */
1522 0, /* tp_getattr */
1523 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001524 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 (reprfunc)float_repr, /* tp_repr */
1526 &float_as_number, /* tp_as_number */
1527 0, /* tp_as_sequence */
1528 0, /* tp_as_mapping */
1529 (hashfunc)float_hash, /* tp_hash */
1530 0, /* tp_call */
1531 (reprfunc)float_str, /* tp_str */
1532 PyObject_GenericGetAttr, /* tp_getattro */
1533 0, /* tp_setattro */
1534 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001535 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1536 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537 float_doc, /* tp_doc */
1538 0, /* tp_traverse */
1539 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001540 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 0, /* tp_weaklistoffset */
1542 0, /* tp_iter */
1543 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001544 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001546 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 0, /* tp_base */
1548 0, /* tp_dict */
1549 0, /* tp_descr_get */
1550 0, /* tp_descr_set */
1551 0, /* tp_dictoffset */
1552 0, /* tp_init */
1553 0, /* tp_alloc */
1554 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001555};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001556
1557void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001558_PyFloat_Init(void)
1559{
1560 /* We attempt to determine if this machine is using IEEE
1561 floating point formats by peering at the bits of some
1562 carefully chosen values. If it looks like we are on an
1563 IEEE platform, the float packing/unpacking routines can
1564 just copy bits, if not they resort to arithmetic & shifts
1565 and masks. The shifts & masks approach works on all finite
1566 values, but what happens to infinities, NaNs and signed
1567 zeroes on packing is an accident, and attempting to unpack
1568 a NaN or an infinity will raise an exception.
1569
1570 Note that if we're on some whacked-out platform which uses
1571 IEEE formats but isn't strictly little-endian or big-
1572 endian, we will fall back to the portable shifts & masks
1573 method. */
1574
1575#if SIZEOF_DOUBLE == 8
1576 {
1577 double x = 9006104071832581.0;
1578 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1579 detected_double_format = ieee_big_endian_format;
1580 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1581 detected_double_format = ieee_little_endian_format;
1582 else
1583 detected_double_format = unknown_format;
1584 }
1585#else
1586 detected_double_format = unknown_format;
1587#endif
1588
1589#if SIZEOF_FLOAT == 4
1590 {
1591 float y = 16711938.0;
1592 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1593 detected_float_format = ieee_big_endian_format;
1594 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1595 detected_float_format = ieee_little_endian_format;
1596 else
1597 detected_float_format = unknown_format;
1598 }
1599#else
1600 detected_float_format = unknown_format;
1601#endif
1602
1603 double_format = detected_double_format;
1604 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001605
Christian Heimes796fc312008-01-30 18:58:29 +00001606 /* Init float info */
1607 if (FloatInfoType.tp_name == 0)
1608 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001609}
1610
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001611int
1612PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001613{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001614 PyFloatObject *p;
1615 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001616 int i;
1617 int u; /* remaining unfreed ints per block */
1618 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001619
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001620 list = block_list;
1621 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001622 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001623 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001624 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001625 for (i = 0, p = &list->objects[0];
1626 i < N_FLOATOBJECTS;
1627 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001628 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001629 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001630 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001631 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001632 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001633 list->next = block_list;
1634 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001635 for (i = 0, p = &list->objects[0];
1636 i < N_FLOATOBJECTS;
1637 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001638 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001639 Py_REFCNT(p) == 0) {
1640 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001641 free_list;
1642 free_list = p;
1643 }
1644 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001645 }
1646 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001647 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001648 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001649 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001650 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001651 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001652 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001653}
1654
1655void
1656PyFloat_Fini(void)
1657{
1658 PyFloatObject *p;
1659 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001660 int i;
1661 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001662
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001663 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00001664
Guido van Rossum3fce8831999-03-12 19:43:17 +00001665 if (!Py_VerboseFlag)
1666 return;
1667 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001668 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001669 fprintf(stderr, "\n");
1670 }
1671 else {
1672 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001673 ": %d unfreed float%s\n",
1674 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00001675 }
1676 if (Py_VerboseFlag > 1) {
1677 list = block_list;
1678 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001679 for (i = 0, p = &list->objects[0];
1680 i < N_FLOATOBJECTS;
1681 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001682 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001683 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001684 char buf[100];
1685 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001686 /* XXX(twouters) cast refcount to
1687 long until %zd is universally
1688 available
1689 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001690 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001691 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001692 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001693 }
1694 }
1695 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001696 }
1697 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001698}
Tim Peters9905b942003-03-20 20:53:32 +00001699
1700/*----------------------------------------------------------------------------
1701 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001702 */
1703int
1704_PyFloat_Pack4(double x, unsigned char *p, int le)
1705{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001706 if (float_format == unknown_format) {
1707 unsigned char sign;
1708 int e;
1709 double f;
1710 unsigned int fbits;
1711 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001712
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001713 if (le) {
1714 p += 3;
1715 incr = -1;
1716 }
Tim Peters9905b942003-03-20 20:53:32 +00001717
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001718 if (x < 0) {
1719 sign = 1;
1720 x = -x;
1721 }
1722 else
1723 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001724
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001725 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001726
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001727 /* Normalize f to be in the range [1.0, 2.0) */
1728 if (0.5 <= f && f < 1.0) {
1729 f *= 2.0;
1730 e--;
1731 }
1732 else if (f == 0.0)
1733 e = 0;
1734 else {
1735 PyErr_SetString(PyExc_SystemError,
1736 "frexp() result out of range");
1737 return -1;
1738 }
1739
1740 if (e >= 128)
1741 goto Overflow;
1742 else if (e < -126) {
1743 /* Gradual underflow */
1744 f = ldexp(f, 126 + e);
1745 e = 0;
1746 }
1747 else if (!(e == 0 && f == 0.0)) {
1748 e += 127;
1749 f -= 1.0; /* Get rid of leading 1 */
1750 }
1751
1752 f *= 8388608.0; /* 2**23 */
1753 fbits = (unsigned int)(f + 0.5); /* Round */
1754 assert(fbits <= 8388608);
1755 if (fbits >> 23) {
1756 /* The carry propagated out of a string of 23 1 bits. */
1757 fbits = 0;
1758 ++e;
1759 if (e >= 255)
1760 goto Overflow;
1761 }
1762
1763 /* First byte */
1764 *p = (sign << 7) | (e >> 1);
1765 p += incr;
1766
1767 /* Second byte */
1768 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1769 p += incr;
1770
1771 /* Third byte */
1772 *p = (fbits >> 8) & 0xFF;
1773 p += incr;
1774
1775 /* Fourth byte */
1776 *p = fbits & 0xFF;
1777
1778 /* Done */
1779 return 0;
1780
Tim Peters9905b942003-03-20 20:53:32 +00001781 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001782 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001783 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001784 const char *s = (char*)&y;
1785 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001786
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001787 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1788 goto Overflow;
1789
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001790 if ((float_format == ieee_little_endian_format && !le)
1791 || (float_format == ieee_big_endian_format && le)) {
1792 p += 3;
1793 incr = -1;
1794 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001795
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001796 for (i = 0; i < 4; i++) {
1797 *p = *s++;
1798 p += incr;
1799 }
1800 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001801 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001802 Overflow:
1803 PyErr_SetString(PyExc_OverflowError,
1804 "float too large to pack with f format");
1805 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001806}
1807
1808int
1809_PyFloat_Pack8(double x, unsigned char *p, int le)
1810{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001811 if (double_format == unknown_format) {
1812 unsigned char sign;
1813 int e;
1814 double f;
1815 unsigned int fhi, flo;
1816 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001817
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001818 if (le) {
1819 p += 7;
1820 incr = -1;
1821 }
Tim Peters9905b942003-03-20 20:53:32 +00001822
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001823 if (x < 0) {
1824 sign = 1;
1825 x = -x;
1826 }
1827 else
1828 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001829
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001830 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001831
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001832 /* Normalize f to be in the range [1.0, 2.0) */
1833 if (0.5 <= f && f < 1.0) {
1834 f *= 2.0;
1835 e--;
1836 }
1837 else if (f == 0.0)
1838 e = 0;
1839 else {
1840 PyErr_SetString(PyExc_SystemError,
1841 "frexp() result out of range");
1842 return -1;
1843 }
1844
1845 if (e >= 1024)
1846 goto Overflow;
1847 else if (e < -1022) {
1848 /* Gradual underflow */
1849 f = ldexp(f, 1022 + e);
1850 e = 0;
1851 }
1852 else if (!(e == 0 && f == 0.0)) {
1853 e += 1023;
1854 f -= 1.0; /* Get rid of leading 1 */
1855 }
1856
1857 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1858 f *= 268435456.0; /* 2**28 */
1859 fhi = (unsigned int)f; /* Truncate */
1860 assert(fhi < 268435456);
1861
1862 f -= (double)fhi;
1863 f *= 16777216.0; /* 2**24 */
1864 flo = (unsigned int)(f + 0.5); /* Round */
1865 assert(flo <= 16777216);
1866 if (flo >> 24) {
1867 /* The carry propagated out of a string of 24 1 bits. */
1868 flo = 0;
1869 ++fhi;
1870 if (fhi >> 28) {
1871 /* And it also progagated out of the next 28 bits. */
1872 fhi = 0;
1873 ++e;
1874 if (e >= 2047)
1875 goto Overflow;
1876 }
1877 }
1878
1879 /* First byte */
1880 *p = (sign << 7) | (e >> 4);
1881 p += incr;
1882
1883 /* Second byte */
1884 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1885 p += incr;
1886
1887 /* Third byte */
1888 *p = (fhi >> 16) & 0xFF;
1889 p += incr;
1890
1891 /* Fourth byte */
1892 *p = (fhi >> 8) & 0xFF;
1893 p += incr;
1894
1895 /* Fifth byte */
1896 *p = fhi & 0xFF;
1897 p += incr;
1898
1899 /* Sixth byte */
1900 *p = (flo >> 16) & 0xFF;
1901 p += incr;
1902
1903 /* Seventh byte */
1904 *p = (flo >> 8) & 0xFF;
1905 p += incr;
1906
1907 /* Eighth byte */
1908 *p = flo & 0xFF;
1909 p += incr;
1910
1911 /* Done */
1912 return 0;
1913
1914 Overflow:
1915 PyErr_SetString(PyExc_OverflowError,
1916 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001917 return -1;
1918 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919 else {
1920 const char *s = (char*)&x;
1921 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001922
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001923 if ((double_format == ieee_little_endian_format && !le)
1924 || (double_format == ieee_big_endian_format && le)) {
1925 p += 7;
1926 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001927 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001928
1929 for (i = 0; i < 8; i++) {
1930 *p = *s++;
1931 p += incr;
1932 }
1933 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001934 }
Tim Peters9905b942003-03-20 20:53:32 +00001935}
1936
1937double
1938_PyFloat_Unpack4(const unsigned char *p, int le)
1939{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940 if (float_format == unknown_format) {
1941 unsigned char sign;
1942 int e;
1943 unsigned int f;
1944 double x;
1945 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001946
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001947 if (le) {
1948 p += 3;
1949 incr = -1;
1950 }
1951
1952 /* First byte */
1953 sign = (*p >> 7) & 1;
1954 e = (*p & 0x7F) << 1;
1955 p += incr;
1956
1957 /* Second byte */
1958 e |= (*p >> 7) & 1;
1959 f = (*p & 0x7F) << 16;
1960 p += incr;
1961
1962 if (e == 255) {
1963 PyErr_SetString(
1964 PyExc_ValueError,
1965 "can't unpack IEEE 754 special value "
1966 "on non-IEEE platform");
1967 return -1;
1968 }
1969
1970 /* Third byte */
1971 f |= *p << 8;
1972 p += incr;
1973
1974 /* Fourth byte */
1975 f |= *p;
1976
1977 x = (double)f / 8388608.0;
1978
1979 /* XXX This sadly ignores Inf/NaN issues */
1980 if (e == 0)
1981 e = -126;
1982 else {
1983 x += 1.0;
1984 e -= 127;
1985 }
1986 x = ldexp(x, e);
1987
1988 if (sign)
1989 x = -x;
1990
1991 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001992 }
Tim Peters9905b942003-03-20 20:53:32 +00001993 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001994 float x;
1995
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001996 if ((float_format == ieee_little_endian_format && !le)
1997 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001998 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999 char *d = &buf[3];
2000 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002001
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002002 for (i = 0; i < 4; i++) {
2003 *d-- = *p++;
2004 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002005 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002006 }
2007 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002008 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002010
2011 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012 }
Tim Peters9905b942003-03-20 20:53:32 +00002013}
2014
2015double
2016_PyFloat_Unpack8(const unsigned char *p, int le)
2017{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002018 if (double_format == unknown_format) {
2019 unsigned char sign;
2020 int e;
2021 unsigned int fhi, flo;
2022 double x;
2023 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002024
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002025 if (le) {
2026 p += 7;
2027 incr = -1;
2028 }
2029
2030 /* First byte */
2031 sign = (*p >> 7) & 1;
2032 e = (*p & 0x7F) << 4;
2033
2034 p += incr;
2035
2036 /* Second byte */
2037 e |= (*p >> 4) & 0xF;
2038 fhi = (*p & 0xF) << 24;
2039 p += incr;
2040
2041 if (e == 2047) {
2042 PyErr_SetString(
2043 PyExc_ValueError,
2044 "can't unpack IEEE 754 special value "
2045 "on non-IEEE platform");
2046 return -1.0;
2047 }
2048
2049 /* Third byte */
2050 fhi |= *p << 16;
2051 p += incr;
2052
2053 /* Fourth byte */
2054 fhi |= *p << 8;
2055 p += incr;
2056
2057 /* Fifth byte */
2058 fhi |= *p;
2059 p += incr;
2060
2061 /* Sixth byte */
2062 flo = *p << 16;
2063 p += incr;
2064
2065 /* Seventh byte */
2066 flo |= *p << 8;
2067 p += incr;
2068
2069 /* Eighth byte */
2070 flo |= *p;
2071
2072 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2073 x /= 268435456.0; /* 2**28 */
2074
2075 if (e == 0)
2076 e = -1022;
2077 else {
2078 x += 1.0;
2079 e -= 1023;
2080 }
2081 x = ldexp(x, e);
2082
2083 if (sign)
2084 x = -x;
2085
2086 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002087 }
Tim Peters9905b942003-03-20 20:53:32 +00002088 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002089 double x;
2090
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002091 if ((double_format == ieee_little_endian_format && !le)
2092 || (double_format == ieee_big_endian_format && le)) {
2093 char buf[8];
2094 char *d = &buf[7];
2095 int i;
2096
2097 for (i = 0; i < 8; i++) {
2098 *d-- = *p++;
2099 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002100 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101 }
2102 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002103 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002104 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002105
2106 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002107 }
Tim Peters9905b942003-03-20 20:53:32 +00002108}