blob: 0eaca0f7bea769784b033be9b7e1402cca1f6484 [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
Eric Smitha9f7d622008-02-17 19:46:49 +000013#include "formatter_string.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +000014
Jack Janseneddc1442003-11-20 01:44:59 +000015#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000016extern double fmod(double, double);
17extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000018#endif
19
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) {
250 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
251 }
252#ifdef Py_NAN
253 if(PyOS_strnicmp(p, "nan", 4) == 0) {
254 return PyFloat_FromDouble(Py_NAN);
255 }
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
Christian Heimesf15c66e2007-12-11 00:54:34 +0000404#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000405/* The following function is based on Tcl_PrintDouble,
406 * from tclUtil.c.
407 */
408
409#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
410#define is_nan(d) ((d) != (d))
411
412static void
413format_double_repr(char *dst, double value)
414{
415 char *p, c;
416 int exp;
417 int signum;
418 char buffer[30];
419
420 /*
421 * Handle NaN.
422 */
423
424 if (is_nan(value)) {
425 strcpy(dst, "nan");
426 return;
427 }
428
429 /*
430 * Handle infinities.
431 */
432
433 if (is_infinite(value)) {
434 if (value < 0) {
435 strcpy(dst, "-inf");
436 } else {
437 strcpy(dst, "inf");
438 }
439 return;
440 }
441
442 /*
443 * Ordinary (normal and denormal) values.
444 */
445
446 exp = _PyFloat_Digits(buffer, value, &signum)+1;
447 if (signum) {
448 *dst++ = '-';
449 }
450 p = buffer;
451 if (exp < -3 || exp > 17) {
452 /*
453 * E format for numbers < 1e-3 or >= 1e17.
454 */
455
456 *dst++ = *p++;
457 c = *p;
458 if (c != '\0') {
459 *dst++ = '.';
460 while (c != '\0') {
461 *dst++ = c;
462 c = *++p;
463 }
464 }
465 sprintf(dst, "e%+d", exp-1);
466 } else {
467 /*
468 * F format for others.
469 */
470
471 if (exp <= 0) {
472 *dst++ = '0';
473 }
474 c = *p;
475 while (exp-- > 0) {
476 if (c != '\0') {
477 *dst++ = c;
478 c = *++p;
479 } else {
480 *dst++ = '0';
481 }
482 }
483 *dst++ = '.';
484 if (c == '\0') {
485 *dst++ = '0';
486 } else {
487 while (++exp < 0) {
488 *dst++ = '0';
489 }
490 while (c != '\0') {
491 *dst++ = c;
492 c = *++p;
493 }
494 }
495 *dst++ = '\0';
496 }
497}
498
499static void
500format_float_repr(char *buf, PyFloatObject *v)
501{
502 assert(PyFloat_Check(v));
503 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
504}
505
Christian Heimesf15c66e2007-12-11 00:54:34 +0000506#endif /* Py_BROKEN_REPR */
507
Neil Schemenauer32117e52001-01-04 01:44:34 +0000508/* Macro and helper that convert PyObject obj to a C double and store
509 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000510 slot function. If conversion to double raises an exception, obj is
511 set to NULL, and the function invoking this macro returns NULL. If
512 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
513 stored in obj, and returned from the function invoking this macro.
514*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000515#define CONVERT_TO_DOUBLE(obj, dbl) \
516 if (PyFloat_Check(obj)) \
517 dbl = PyFloat_AS_DOUBLE(obj); \
518 else if (convert_to_double(&(obj), &(dbl)) < 0) \
519 return obj;
520
521static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000522convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000523{
524 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000525
Neil Schemenauer32117e52001-01-04 01:44:34 +0000526 if (PyInt_Check(obj)) {
527 *dbl = (double)PyInt_AS_LONG(obj);
528 }
529 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000530 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000531 if (*dbl == -1.0 && PyErr_Occurred()) {
532 *v = NULL;
533 return -1;
534 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000535 }
536 else {
537 Py_INCREF(Py_NotImplemented);
538 *v = Py_NotImplemented;
539 return -1;
540 }
541 return 0;
542}
543
Guido van Rossum57072eb1999-12-23 19:00:28 +0000544/* Precisions used by repr() and str(), respectively.
545
546 The repr() precision (17 significant decimal digits) is the minimal number
547 that is guaranteed to have enough precision so that if the number is read
548 back in the exact same binary value is recreated. This is true for IEEE
549 floating point by design, and also happens to work for all other modern
550 hardware.
551
552 The str() precision is chosen so that in most cases, the rounding noise
553 created by various operations is suppressed, while giving plenty of
554 precision for practical use.
555
556*/
557
558#define PREC_REPR 17
559#define PREC_STR 12
560
Tim Peters97019e42001-11-28 22:43:45 +0000561/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
562 XXX they pass a char buffer without passing a length.
563*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000564void
Fred Drakefd99de62000-07-09 05:02:18 +0000565PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000566{
Tim Peters97019e42001-11-28 22:43:45 +0000567 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000568}
569
Tim Peters72f98e92001-05-08 15:19:57 +0000570void
571PyFloat_AsReprString(char *buf, PyFloatObject *v)
572{
Tim Peters97019e42001-11-28 22:43:45 +0000573 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000574}
575
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000576/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000577static int
Fred Drakefd99de62000-07-09 05:02:18 +0000578float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000579{
580 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000581 format_float(buf, sizeof(buf), v,
582 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000583 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000585 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000586 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000590float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000592#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000593 char buf[30];
594 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000595#else
596 char buf[100];
597 format_float(buf, sizeof(buf), v, PREC_REPR);
598#endif
599
Guido van Rossum57072eb1999-12-23 19:00:28 +0000600 return PyString_FromString(buf);
601}
602
603static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000604float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000605{
606 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000607 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609}
610
Tim Peters307fa782004-09-23 08:06:40 +0000611/* Comparison is pretty much a nightmare. When comparing float to float,
612 * we do it as straightforwardly (and long-windedly) as conceivable, so
613 * that, e.g., Python x == y delivers the same result as the platform
614 * C x == y when x and/or y is a NaN.
615 * When mixing float with an integer type, there's no good *uniform* approach.
616 * Converting the double to an integer obviously doesn't work, since we
617 * may lose info from fractional bits. Converting the integer to a double
618 * also has two failure modes: (1) a long int may trigger overflow (too
619 * large to fit in the dynamic range of a C double); (2) even a C long may have
620 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
621 * 63 bits of precision, but a C double probably has only 53), and then
622 * we can falsely claim equality when low-order integer bits are lost by
623 * coercion to double. So this part is painful too.
624 */
625
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000626static PyObject*
627float_richcompare(PyObject *v, PyObject *w, int op)
628{
629 double i, j;
630 int r = 0;
631
Tim Peters307fa782004-09-23 08:06:40 +0000632 assert(PyFloat_Check(v));
633 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000634
Tim Peters307fa782004-09-23 08:06:40 +0000635 /* Switch on the type of w. Set i and j to doubles to be compared,
636 * and op to the richcomp to use.
637 */
638 if (PyFloat_Check(w))
639 j = PyFloat_AS_DOUBLE(w);
640
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000641 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000642 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000643 /* If i is an infinity, its magnitude exceeds any
644 * finite integer, so it doesn't matter which int we
645 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000646 */
647 j = 0.0;
648 else
649 goto Unimplemented;
650 }
651
652 else if (PyInt_Check(w)) {
653 long jj = PyInt_AS_LONG(w);
654 /* In the worst realistic case I can imagine, C double is a
655 * Cray single with 48 bits of precision, and long has 64
656 * bits.
657 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000658#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000659 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
660 if (abs >> 48) {
661 /* Needs more than 48 bits. Make it take the
662 * PyLong path.
663 */
664 PyObject *result;
665 PyObject *ww = PyLong_FromLong(jj);
666
667 if (ww == NULL)
668 return NULL;
669 result = float_richcompare(v, ww, op);
670 Py_DECREF(ww);
671 return result;
672 }
673#endif
674 j = (double)jj;
675 assert((long)j == jj);
676 }
677
678 else if (PyLong_Check(w)) {
679 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
680 int wsign = _PyLong_Sign(w);
681 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000682 int exponent;
683
684 if (vsign != wsign) {
685 /* Magnitudes are irrelevant -- the signs alone
686 * determine the outcome.
687 */
688 i = (double)vsign;
689 j = (double)wsign;
690 goto Compare;
691 }
692 /* The signs are the same. */
693 /* Convert w to a double if it fits. In particular, 0 fits. */
694 nbits = _PyLong_NumBits(w);
695 if (nbits == (size_t)-1 && PyErr_Occurred()) {
696 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000697 * to hold the # of bits. Replace with little doubles
698 * that give the same outcome -- w is so large that
699 * its magnitude must exceed the magnitude of any
700 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000701 */
702 PyErr_Clear();
703 i = (double)vsign;
704 assert(wsign != 0);
705 j = wsign * 2.0;
706 goto Compare;
707 }
708 if (nbits <= 48) {
709 j = PyLong_AsDouble(w);
710 /* It's impossible that <= 48 bits overflowed. */
711 assert(j != -1.0 || ! PyErr_Occurred());
712 goto Compare;
713 }
714 assert(wsign != 0); /* else nbits was 0 */
715 assert(vsign != 0); /* if vsign were 0, then since wsign is
716 * not 0, we would have taken the
717 * vsign != wsign branch at the start */
718 /* We want to work with non-negative numbers. */
719 if (vsign < 0) {
720 /* "Multiply both sides" by -1; this also swaps the
721 * comparator.
722 */
723 i = -i;
724 op = _Py_SwappedOp[op];
725 }
726 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000727 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000728 /* exponent is the # of bits in v before the radix point;
729 * we know that nbits (the # of bits in w) > 48 at this point
730 */
731 if (exponent < 0 || (size_t)exponent < nbits) {
732 i = 1.0;
733 j = 2.0;
734 goto Compare;
735 }
736 if ((size_t)exponent > nbits) {
737 i = 2.0;
738 j = 1.0;
739 goto Compare;
740 }
741 /* v and w have the same number of bits before the radix
742 * point. Construct two longs that have the same comparison
743 * outcome.
744 */
745 {
746 double fracpart;
747 double intpart;
748 PyObject *result = NULL;
749 PyObject *one = NULL;
750 PyObject *vv = NULL;
751 PyObject *ww = w;
752
753 if (wsign < 0) {
754 ww = PyNumber_Negative(w);
755 if (ww == NULL)
756 goto Error;
757 }
758 else
759 Py_INCREF(ww);
760
761 fracpart = modf(i, &intpart);
762 vv = PyLong_FromDouble(intpart);
763 if (vv == NULL)
764 goto Error;
765
766 if (fracpart != 0.0) {
767 /* Shift left, and or a 1 bit into vv
768 * to represent the lost fraction.
769 */
770 PyObject *temp;
771
772 one = PyInt_FromLong(1);
773 if (one == NULL)
774 goto Error;
775
776 temp = PyNumber_Lshift(ww, one);
777 if (temp == NULL)
778 goto Error;
779 Py_DECREF(ww);
780 ww = temp;
781
782 temp = PyNumber_Lshift(vv, one);
783 if (temp == NULL)
784 goto Error;
785 Py_DECREF(vv);
786 vv = temp;
787
788 temp = PyNumber_Or(vv, one);
789 if (temp == NULL)
790 goto Error;
791 Py_DECREF(vv);
792 vv = temp;
793 }
794
795 r = PyObject_RichCompareBool(vv, ww, op);
796 if (r < 0)
797 goto Error;
798 result = PyBool_FromLong(r);
799 Error:
800 Py_XDECREF(vv);
801 Py_XDECREF(ww);
802 Py_XDECREF(one);
803 return result;
804 }
805 } /* else if (PyLong_Check(w)) */
806
807 else /* w isn't float, int, or long */
808 goto Unimplemented;
809
810 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000811 PyFPE_START_PROTECT("richcompare", return NULL)
812 switch (op) {
813 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000814 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000815 break;
816 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000817 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000818 break;
819 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000820 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000821 break;
822 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000823 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000824 break;
825 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000826 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000827 break;
828 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000829 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000830 break;
831 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000832 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000833 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000834
835 Unimplemented:
836 Py_INCREF(Py_NotImplemented);
837 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000838}
839
Guido van Rossum9bfef441993-03-29 10:43:31 +0000840static long
Fred Drakefd99de62000-07-09 05:02:18 +0000841float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000842{
Tim Peters39dce292000-08-15 03:34:48 +0000843 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000844}
845
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000846static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000847float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000848{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000849 double a,b;
850 CONVERT_TO_DOUBLE(v, a);
851 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000852 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000853 a = a + b;
854 PyFPE_END_PROTECT(a)
855 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000856}
857
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000858static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000859float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000860{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000861 double a,b;
862 CONVERT_TO_DOUBLE(v, a);
863 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000864 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000865 a = a - b;
866 PyFPE_END_PROTECT(a)
867 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000868}
869
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000870static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000871float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000873 double a,b;
874 CONVERT_TO_DOUBLE(v, a);
875 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000876 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000877 a = a * b;
878 PyFPE_END_PROTECT(a)
879 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880}
881
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000882static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000883float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000885 double a,b;
886 CONVERT_TO_DOUBLE(v, a);
887 CONVERT_TO_DOUBLE(w, b);
888 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000890 return NULL;
891 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000892 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000893 a = a / b;
894 PyFPE_END_PROTECT(a)
895 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000896}
897
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000898static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000899float_classic_div(PyObject *v, PyObject *w)
900{
901 double a,b;
902 CONVERT_TO_DOUBLE(v, a);
903 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000904 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000905 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
906 return NULL;
907 if (b == 0.0) {
908 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
909 return NULL;
910 }
911 PyFPE_START_PROTECT("divide", return 0)
912 a = a / b;
913 PyFPE_END_PROTECT(a)
914 return PyFloat_FromDouble(a);
915}
916
917static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000918float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000919{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000920 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000921 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000922 CONVERT_TO_DOUBLE(v, vx);
923 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000924 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000926 return NULL;
927 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000928 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000929 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000930 /* note: checking mod*wx < 0 is incorrect -- underflows to
931 0 if wx < sqrt(smallest nonzero double) */
932 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000933 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000934 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000935 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000936 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000937}
938
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000939static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000940float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000941{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000942 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000943 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000944 CONVERT_TO_DOUBLE(v, vx);
945 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000946 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000947 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000948 return NULL;
949 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000950 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000951 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000952 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000953 exact multiple of wx. But this is fp arithmetic, and fp
954 vx - mod is an approximation; the result is that div may
955 not be an exact integral value after the division, although
956 it will always be very close to one.
957 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000958 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000959 if (mod) {
960 /* ensure the remainder has the same sign as the denominator */
961 if ((wx < 0) != (mod < 0)) {
962 mod += wx;
963 div -= 1.0;
964 }
965 }
966 else {
967 /* the remainder is zero, and in the presence of signed zeroes
968 fmod returns different results across platforms; ensure
969 it has the same sign as the denominator; we'd like to do
970 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000971 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000972 if (wx < 0.0)
973 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000974 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000975 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000976 if (div) {
977 floordiv = floor(div);
978 if (div - floordiv > 0.5)
979 floordiv += 1.0;
980 }
981 else {
982 /* div is zero - get the same sign as the true quotient */
983 div *= div; /* hide "div = +0" from optimizers */
984 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
985 }
986 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000987 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000988}
989
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000990static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000991float_floor_div(PyObject *v, PyObject *w)
992{
993 PyObject *t, *r;
994
995 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000996 if (t == NULL || t == Py_NotImplemented)
997 return t;
998 assert(PyTuple_CheckExact(t));
999 r = PyTuple_GET_ITEM(t, 0);
1000 Py_INCREF(r);
1001 Py_DECREF(t);
1002 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001003}
1004
1005static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001006float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001007{
1008 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001009
1010 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001011 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001012 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001013 return NULL;
1014 }
1015
Neil Schemenauer32117e52001-01-04 01:44:34 +00001016 CONVERT_TO_DOUBLE(v, iv);
1017 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001018
1019 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001020 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001021 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001022 }
Tim Peters96685bf2001-08-23 22:31:37 +00001023 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001024 if (iw < 0.0) {
1025 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001026 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001027 return NULL;
1028 }
1029 return PyFloat_FromDouble(0.0);
1030 }
Tim Peterse87568d2003-05-24 20:18:24 +00001031 if (iv < 0.0) {
1032 /* Whether this is an error is a mess, and bumps into libm
1033 * bugs so we have to figure it out ourselves.
1034 */
1035 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001036 PyErr_SetString(PyExc_ValueError, "negative number "
1037 "cannot be raised to a fractional power");
1038 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001039 }
1040 /* iw is an exact integer, albeit perhaps a very large one.
1041 * -1 raised to an exact integer should never be exceptional.
1042 * Alas, some libms (chiefly glibc as of early 2003) return
1043 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1044 * happen to be representable in a *C* integer. That's a
1045 * bug; we let that slide in math.pow() (which currently
1046 * reflects all platform accidents), but not for Python's **.
1047 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001048 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001049 /* Return 1 if iw is even, -1 if iw is odd; there's
1050 * no guarantee that any C integral type is big
1051 * enough to hold iw, so we have to check this
1052 * indirectly.
1053 */
1054 ix = floor(iw * 0.5) * 2.0;
1055 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1056 }
1057 /* Else iv != -1.0, and overflow or underflow are possible.
1058 * Unless we're to write pow() ourselves, we have to trust
1059 * the platform to do this correctly.
1060 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001061 }
Tim Peters96685bf2001-08-23 22:31:37 +00001062 errno = 0;
1063 PyFPE_START_PROTECT("pow", return NULL)
1064 ix = pow(iv, iw);
1065 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001066 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001067 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001068 /* We don't expect any errno value other than ERANGE, but
1069 * the range of libm bugs appears unbounded.
1070 */
Alex Martelli348dc882006-08-23 22:17:59 +00001071 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1072 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001073 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001074 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001075 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001076}
1077
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001078static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001079float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001080{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001081 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001082}
1083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001084static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001085float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001086{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001087 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001088}
1089
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001090static int
Fred Drakefd99de62000-07-09 05:02:18 +00001091float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001092{
1093 return v->ob_fval != 0.0;
1094}
1095
Guido van Rossum234f9421993-06-17 12:35:49 +00001096static int
Fred Drakefd99de62000-07-09 05:02:18 +00001097float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001098{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001099 if (PyInt_Check(*pw)) {
1100 long x = PyInt_AsLong(*pw);
1101 *pw = PyFloat_FromDouble((double)x);
1102 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001103 return 0;
1104 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001105 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001106 double x = PyLong_AsDouble(*pw);
1107 if (x == -1.0 && PyErr_Occurred())
1108 return -1;
1109 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001110 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001111 return 0;
1112 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001113 else if (PyFloat_Check(*pw)) {
1114 Py_INCREF(*pv);
1115 Py_INCREF(*pw);
1116 return 0;
1117 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001118 return 1; /* Can't do it */
1119}
1120
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001122float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001123{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001124 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001125 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001126
1127 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001128 /* Try to get out cheap if this fits in a Python int. The attempt
1129 * to cast to long must be protected, as C doesn't define what
1130 * happens if the double is too big to fit in a long. Some rare
1131 * systems raise an exception then (RISCOS was mentioned as one,
1132 * and someone using a non-default option on Sun also bumped into
1133 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1134 * still be vulnerable: if a long has more bits of precision than
1135 * a double, casting MIN/MAX to double may yield an approximation,
1136 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1137 * yield true from the C expression wholepart<=LONG_MAX, despite
1138 * that wholepart is actually greater than LONG_MAX.
1139 */
1140 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1141 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001142 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001143 }
1144 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001145}
1146
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001147static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001148float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001149{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001150 if (PyFloat_CheckExact(v))
1151 Py_INCREF(v);
1152 else
1153 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001154 return v;
1155}
1156
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001157static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001158float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001159{
1160 double self;
1161 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001162 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001163 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001164
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001165 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001166 PyObject *py_exponent = NULL;
1167 PyObject *numerator = NULL;
1168 PyObject *denominator = NULL;
1169 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001170 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001171
1172#define INPLACE_UPDATE(obj, call) \
1173 prev = obj; \
1174 obj = call; \
1175 Py_DECREF(prev); \
1176
1177 CONVERT_TO_DOUBLE(v, self);
1178
1179 if (Py_IS_INFINITY(self)) {
1180 PyErr_SetString(PyExc_OverflowError,
1181 "Cannot pass infinity to float.as_integer_ratio.");
1182 return NULL;
1183 }
1184#ifdef Py_NAN
1185 if (Py_IS_NAN(self)) {
1186 PyErr_SetString(PyExc_ValueError,
1187 "Cannot pass nan to float.as_integer_ratio.");
1188 return NULL;
1189 }
1190#endif
1191
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001192 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001193 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001194 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001195
Raymond Hettingerf9859032008-02-01 23:45:44 +00001196 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001197 float_part *= 2.0;
1198 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001199 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001200 /* self == float_part * 2**exponent exactly and float_part is integral.
1201 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1202 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001203
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001204 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001205 if (numerator == NULL) goto error;
1206
Raymond Hettingerf9859032008-02-01 23:45:44 +00001207 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001208 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001209 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001210 if (py_exponent == NULL) goto error;
1211 INPLACE_UPDATE(py_exponent,
1212 long_methods->nb_lshift(denominator, py_exponent));
1213 if (py_exponent == NULL) goto error;
1214 if (exponent > 0) {
1215 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001216 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001217 if (numerator == NULL) goto error;
1218 }
1219 else {
1220 Py_DECREF(denominator);
1221 denominator = py_exponent;
1222 py_exponent = NULL;
1223 }
1224
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001225 /* Returns ints instead of longs where possible */
1226 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1227 if (numerator == NULL) goto error;
1228 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1229 if (denominator == NULL) goto error;
1230
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001231 result_pair = PyTuple_Pack(2, numerator, denominator);
1232
1233#undef INPLACE_UPDATE
1234error:
1235 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001236 Py_XDECREF(denominator);
1237 Py_XDECREF(numerator);
1238 return result_pair;
1239}
1240
1241PyDoc_STRVAR(float_as_integer_ratio_doc,
1242"float.as_integer_ratio() -> (int, int)\n"
1243"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001244"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1245"float and with a positive denominator.\n"
1246"Raises OverflowError on infinities and a ValueError on nans.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001247"\n"
1248">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001249"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001250">>> (0.0).as_integer_ratio()\n"
1251"(0, 1)\n"
1252">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001253"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001254
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001255
Jeremy Hylton938ace62002-07-17 16:30:39 +00001256static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001257float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1258
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259static PyObject *
1260float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1261{
1262 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001263 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264
Guido van Rossumbef14172001-08-29 15:47:46 +00001265 if (type != &PyFloat_Type)
1266 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1268 return NULL;
1269 if (PyString_Check(x))
1270 return PyFloat_FromString(x, NULL);
1271 return PyNumber_Float(x);
1272}
1273
Guido van Rossumbef14172001-08-29 15:47:46 +00001274/* Wimpy, slow approach to tp_new calls for subtypes of float:
1275 first create a regular float from whatever arguments we got,
1276 then allocate a subtype instance and initialize its ob_fval
1277 from the regular float. The regular float is then thrown away.
1278*/
1279static PyObject *
1280float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1281{
Anthony Baxter377be112006-04-11 06:54:30 +00001282 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001283
1284 assert(PyType_IsSubtype(type, &PyFloat_Type));
1285 tmp = float_new(&PyFloat_Type, args, kwds);
1286 if (tmp == NULL)
1287 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001288 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001289 newobj = type->tp_alloc(type, 0);
1290 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001291 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001292 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001293 }
Anthony Baxter377be112006-04-11 06:54:30 +00001294 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001295 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001296 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001297}
1298
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001299static PyObject *
1300float_getnewargs(PyFloatObject *v)
1301{
1302 return Py_BuildValue("(d)", v->ob_fval);
1303}
1304
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001305/* this is for the benefit of the pack/unpack routines below */
1306
1307typedef enum {
1308 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1309} float_format_type;
1310
1311static float_format_type double_format, float_format;
1312static float_format_type detected_double_format, detected_float_format;
1313
1314static PyObject *
1315float_getformat(PyTypeObject *v, PyObject* arg)
1316{
1317 char* s;
1318 float_format_type r;
1319
1320 if (!PyString_Check(arg)) {
1321 PyErr_Format(PyExc_TypeError,
1322 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001323 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001324 return NULL;
1325 }
1326 s = PyString_AS_STRING(arg);
1327 if (strcmp(s, "double") == 0) {
1328 r = double_format;
1329 }
1330 else if (strcmp(s, "float") == 0) {
1331 r = float_format;
1332 }
1333 else {
1334 PyErr_SetString(PyExc_ValueError,
1335 "__getformat__() argument 1 must be "
1336 "'double' or 'float'");
1337 return NULL;
1338 }
1339
1340 switch (r) {
1341 case unknown_format:
1342 return PyString_FromString("unknown");
1343 case ieee_little_endian_format:
1344 return PyString_FromString("IEEE, little-endian");
1345 case ieee_big_endian_format:
1346 return PyString_FromString("IEEE, big-endian");
1347 default:
1348 Py_FatalError("insane float_format or double_format");
1349 return NULL;
1350 }
1351}
1352
1353PyDoc_STRVAR(float_getformat_doc,
1354"float.__getformat__(typestr) -> string\n"
1355"\n"
1356"You probably don't want to use this function. It exists mainly to be\n"
1357"used in Python's test suite.\n"
1358"\n"
1359"typestr must be 'double' or 'float'. This function returns whichever of\n"
1360"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1361"format of floating point numbers used by the C type named by typestr.");
1362
1363static PyObject *
1364float_setformat(PyTypeObject *v, PyObject* args)
1365{
1366 char* typestr;
1367 char* format;
1368 float_format_type f;
1369 float_format_type detected;
1370 float_format_type *p;
1371
1372 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1373 return NULL;
1374
1375 if (strcmp(typestr, "double") == 0) {
1376 p = &double_format;
1377 detected = detected_double_format;
1378 }
1379 else if (strcmp(typestr, "float") == 0) {
1380 p = &float_format;
1381 detected = detected_float_format;
1382 }
1383 else {
1384 PyErr_SetString(PyExc_ValueError,
1385 "__setformat__() argument 1 must "
1386 "be 'double' or 'float'");
1387 return NULL;
1388 }
1389
1390 if (strcmp(format, "unknown") == 0) {
1391 f = unknown_format;
1392 }
1393 else if (strcmp(format, "IEEE, little-endian") == 0) {
1394 f = ieee_little_endian_format;
1395 }
1396 else if (strcmp(format, "IEEE, big-endian") == 0) {
1397 f = ieee_big_endian_format;
1398 }
1399 else {
1400 PyErr_SetString(PyExc_ValueError,
1401 "__setformat__() argument 2 must be "
1402 "'unknown', 'IEEE, little-endian' or "
1403 "'IEEE, big-endian'");
1404 return NULL;
1405
1406 }
1407
1408 if (f != unknown_format && f != detected) {
1409 PyErr_Format(PyExc_ValueError,
1410 "can only set %s format to 'unknown' or the "
1411 "detected platform value", typestr);
1412 return NULL;
1413 }
1414
1415 *p = f;
1416 Py_RETURN_NONE;
1417}
1418
1419PyDoc_STRVAR(float_setformat_doc,
1420"float.__setformat__(typestr, fmt) -> None\n"
1421"\n"
1422"You probably don't want to use this function. It exists mainly to be\n"
1423"used in Python's test suite.\n"
1424"\n"
1425"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1426"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1427"one of the latter two if it appears to match the underlying C reality.\n"
1428"\n"
1429"Overrides the automatic determination of C-level floating point type.\n"
1430"This affects how floats are converted to and from binary strings.");
1431
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001432static PyObject *
1433float_getzero(PyObject *v, void *closure)
1434{
1435 return PyFloat_FromDouble(0.0);
1436}
1437
Eric Smitha9f7d622008-02-17 19:46:49 +00001438static PyObject *
1439float__format__(PyObject *self, PyObject *args)
1440{
1441 PyObject *format_spec;
1442
1443 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1444 return NULL;
1445 if (PyString_Check(format_spec))
1446 return string_float__format__(self, args);
1447 if (PyUnicode_Check(format_spec)) {
1448 /* Convert format_spec to a str */
1449 PyObject *result = NULL;
1450 PyObject *newargs = NULL;
1451 PyObject *string_format_spec = NULL;
1452
1453 string_format_spec = PyObject_Str(format_spec);
1454 if (string_format_spec == NULL)
1455 goto done;
1456
1457 newargs = Py_BuildValue("(O)", string_format_spec);
1458 if (newargs == NULL)
1459 goto done;
1460
1461 result = string_float__format__(self, newargs);
1462
1463 done:
1464 Py_XDECREF(string_format_spec);
1465 Py_XDECREF(newargs);
1466 return result;
1467 }
1468 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1469 return NULL;
1470}
1471
1472PyDoc_STRVAR(float__format__doc,
1473"float.__format__(format_spec) -> string\n"
1474"\n"
1475"Formats the float according to format_spec.");
1476
1477
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001478static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001479 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1480 "Returns self, the complex conjugate of any float."},
1481 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1482 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001483 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1484 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001485 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001486 {"__getformat__", (PyCFunction)float_getformat,
1487 METH_O|METH_CLASS, float_getformat_doc},
1488 {"__setformat__", (PyCFunction)float_setformat,
1489 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001490 {"__format__", (PyCFunction)float__format__,
1491 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001492 {NULL, NULL} /* sentinel */
1493};
1494
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001495static PyGetSetDef float_getset[] = {
1496 {"real",
1497 (getter)float_float, (setter)NULL,
1498 "the real part of a complex number",
1499 NULL},
1500 {"imag",
1501 (getter)float_getzero, (setter)NULL,
1502 "the imaginary part of a complex number",
1503 NULL},
1504 {NULL} /* Sentinel */
1505};
1506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001507PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508"float(x) -> floating point number\n\
1509\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001510Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001511
1512
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001514 float_add, /*nb_add*/
1515 float_sub, /*nb_subtract*/
1516 float_mul, /*nb_multiply*/
1517 float_classic_div, /*nb_divide*/
1518 float_rem, /*nb_remainder*/
1519 float_divmod, /*nb_divmod*/
1520 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001521 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001522 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001523 (unaryfunc)float_abs, /*nb_absolute*/
1524 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001525 0, /*nb_invert*/
1526 0, /*nb_lshift*/
1527 0, /*nb_rshift*/
1528 0, /*nb_and*/
1529 0, /*nb_xor*/
1530 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001531 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001532 float_trunc, /*nb_int*/
1533 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001534 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001535 0, /* nb_oct */
1536 0, /* nb_hex */
1537 0, /* nb_inplace_add */
1538 0, /* nb_inplace_subtract */
1539 0, /* nb_inplace_multiply */
1540 0, /* nb_inplace_divide */
1541 0, /* nb_inplace_remainder */
1542 0, /* nb_inplace_power */
1543 0, /* nb_inplace_lshift */
1544 0, /* nb_inplace_rshift */
1545 0, /* nb_inplace_and */
1546 0, /* nb_inplace_xor */
1547 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001548 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001549 float_div, /* nb_true_divide */
1550 0, /* nb_inplace_floor_divide */
1551 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001552};
1553
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001554PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001555 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001556 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001557 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001558 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559 (destructor)float_dealloc, /* tp_dealloc */
1560 (printfunc)float_print, /* tp_print */
1561 0, /* tp_getattr */
1562 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001563 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564 (reprfunc)float_repr, /* tp_repr */
1565 &float_as_number, /* tp_as_number */
1566 0, /* tp_as_sequence */
1567 0, /* tp_as_mapping */
1568 (hashfunc)float_hash, /* tp_hash */
1569 0, /* tp_call */
1570 (reprfunc)float_str, /* tp_str */
1571 PyObject_GenericGetAttr, /* tp_getattro */
1572 0, /* tp_setattro */
1573 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001574 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1575 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 float_doc, /* tp_doc */
1577 0, /* tp_traverse */
1578 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001579 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 0, /* tp_weaklistoffset */
1581 0, /* tp_iter */
1582 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001583 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001585 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 0, /* tp_base */
1587 0, /* tp_dict */
1588 0, /* tp_descr_get */
1589 0, /* tp_descr_set */
1590 0, /* tp_dictoffset */
1591 0, /* tp_init */
1592 0, /* tp_alloc */
1593 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001594};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001595
1596void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001597_PyFloat_Init(void)
1598{
1599 /* We attempt to determine if this machine is using IEEE
1600 floating point formats by peering at the bits of some
1601 carefully chosen values. If it looks like we are on an
1602 IEEE platform, the float packing/unpacking routines can
1603 just copy bits, if not they resort to arithmetic & shifts
1604 and masks. The shifts & masks approach works on all finite
1605 values, but what happens to infinities, NaNs and signed
1606 zeroes on packing is an accident, and attempting to unpack
1607 a NaN or an infinity will raise an exception.
1608
1609 Note that if we're on some whacked-out platform which uses
1610 IEEE formats but isn't strictly little-endian or big-
1611 endian, we will fall back to the portable shifts & masks
1612 method. */
1613
1614#if SIZEOF_DOUBLE == 8
1615 {
1616 double x = 9006104071832581.0;
1617 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1618 detected_double_format = ieee_big_endian_format;
1619 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1620 detected_double_format = ieee_little_endian_format;
1621 else
1622 detected_double_format = unknown_format;
1623 }
1624#else
1625 detected_double_format = unknown_format;
1626#endif
1627
1628#if SIZEOF_FLOAT == 4
1629 {
1630 float y = 16711938.0;
1631 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1632 detected_float_format = ieee_big_endian_format;
1633 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1634 detected_float_format = ieee_little_endian_format;
1635 else
1636 detected_float_format = unknown_format;
1637 }
1638#else
1639 detected_float_format = unknown_format;
1640#endif
1641
1642 double_format = detected_double_format;
1643 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001644
1645#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001646 /* Initialize floating point repr */
1647 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001648#endif
Christian Heimes796fc312008-01-30 18:58:29 +00001649 /* Init float info */
1650 if (FloatInfoType.tp_name == 0)
1651 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001652}
1653
1654void
Christian Heimes422051a2008-02-04 18:00:12 +00001655PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001656{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001657 PyFloatObject *p;
1658 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001659 unsigned i;
Christian Heimes422051a2008-02-04 18:00:12 +00001660 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1661 size_t fsum = 0; /* total unfreed ints */
1662 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001663
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001664 list = block_list;
1665 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001666 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001667 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001668 bc++;
1669 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001670 for (i = 0, p = &list->objects[0];
1671 i < N_FLOATOBJECTS;
1672 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001673 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001674 frem++;
1675 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001676 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001677 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001678 list->next = block_list;
1679 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001680 for (i = 0, p = &list->objects[0];
1681 i < N_FLOATOBJECTS;
1682 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001683 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001684 Py_REFCNT(p) == 0) {
1685 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001686 free_list;
1687 free_list = p;
1688 }
1689 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001690 }
1691 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001692 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001693 bf++;
1694 }
1695 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001696 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001697 }
Christian Heimes422051a2008-02-04 18:00:12 +00001698 *pbc = bc;
1699 *pbf = bf;
1700 *bsum = fsum;
1701}
1702
1703void
1704PyFloat_Fini(void)
1705{
1706 PyFloatObject *p;
1707 PyFloatBlock *list;
1708 unsigned i;
1709 size_t bc, bf; /* block count, number of freed blocks */
1710 size_t fsum; /* total unfreed floats per block */
1711
1712 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1713
Guido van Rossum3fce8831999-03-12 19:43:17 +00001714 if (!Py_VerboseFlag)
1715 return;
1716 fprintf(stderr, "# cleanup floats");
1717 if (!fsum) {
1718 fprintf(stderr, "\n");
1719 }
1720 else {
1721 fprintf(stderr,
Christian Heimes422051a2008-02-04 18:00:12 +00001722 ": %" PY_FORMAT_SIZE_T "d unfreed floats%s in %"
1723 PY_FORMAT_SIZE_T "d out of %"
1724 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001725 fsum, fsum == 1 ? "" : "s",
1726 bc - bf, bc, bc == 1 ? "" : "s");
1727 }
1728 if (Py_VerboseFlag > 1) {
1729 list = block_list;
1730 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001731 for (i = 0, p = &list->objects[0];
1732 i < N_FLOATOBJECTS;
1733 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001734 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001735 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001736 char buf[100];
1737 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001738 /* XXX(twouters) cast refcount to
1739 long until %zd is universally
1740 available
1741 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001742 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001743 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001744 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001745 }
1746 }
1747 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001748 }
1749 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001750}
Tim Peters9905b942003-03-20 20:53:32 +00001751
1752/*----------------------------------------------------------------------------
1753 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001754 */
1755int
1756_PyFloat_Pack4(double x, unsigned char *p, int le)
1757{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001758 if (float_format == unknown_format) {
1759 unsigned char sign;
1760 int e;
1761 double f;
1762 unsigned int fbits;
1763 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001764
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001765 if (le) {
1766 p += 3;
1767 incr = -1;
1768 }
Tim Peters9905b942003-03-20 20:53:32 +00001769
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001770 if (x < 0) {
1771 sign = 1;
1772 x = -x;
1773 }
1774 else
1775 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001776
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001778
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001779 /* Normalize f to be in the range [1.0, 2.0) */
1780 if (0.5 <= f && f < 1.0) {
1781 f *= 2.0;
1782 e--;
1783 }
1784 else if (f == 0.0)
1785 e = 0;
1786 else {
1787 PyErr_SetString(PyExc_SystemError,
1788 "frexp() result out of range");
1789 return -1;
1790 }
1791
1792 if (e >= 128)
1793 goto Overflow;
1794 else if (e < -126) {
1795 /* Gradual underflow */
1796 f = ldexp(f, 126 + e);
1797 e = 0;
1798 }
1799 else if (!(e == 0 && f == 0.0)) {
1800 e += 127;
1801 f -= 1.0; /* Get rid of leading 1 */
1802 }
1803
1804 f *= 8388608.0; /* 2**23 */
1805 fbits = (unsigned int)(f + 0.5); /* Round */
1806 assert(fbits <= 8388608);
1807 if (fbits >> 23) {
1808 /* The carry propagated out of a string of 23 1 bits. */
1809 fbits = 0;
1810 ++e;
1811 if (e >= 255)
1812 goto Overflow;
1813 }
1814
1815 /* First byte */
1816 *p = (sign << 7) | (e >> 1);
1817 p += incr;
1818
1819 /* Second byte */
1820 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1821 p += incr;
1822
1823 /* Third byte */
1824 *p = (fbits >> 8) & 0xFF;
1825 p += incr;
1826
1827 /* Fourth byte */
1828 *p = fbits & 0xFF;
1829
1830 /* Done */
1831 return 0;
1832
Tim Peters9905b942003-03-20 20:53:32 +00001833 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001834 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001835 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001836 const char *s = (char*)&y;
1837 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001838
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001839 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1840 goto Overflow;
1841
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001842 if ((float_format == ieee_little_endian_format && !le)
1843 || (float_format == ieee_big_endian_format && le)) {
1844 p += 3;
1845 incr = -1;
1846 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001847
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001848 for (i = 0; i < 4; i++) {
1849 *p = *s++;
1850 p += incr;
1851 }
1852 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001853 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001854 Overflow:
1855 PyErr_SetString(PyExc_OverflowError,
1856 "float too large to pack with f format");
1857 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001858}
1859
1860int
1861_PyFloat_Pack8(double x, unsigned char *p, int le)
1862{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001863 if (double_format == unknown_format) {
1864 unsigned char sign;
1865 int e;
1866 double f;
1867 unsigned int fhi, flo;
1868 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001869
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001870 if (le) {
1871 p += 7;
1872 incr = -1;
1873 }
Tim Peters9905b942003-03-20 20:53:32 +00001874
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001875 if (x < 0) {
1876 sign = 1;
1877 x = -x;
1878 }
1879 else
1880 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001881
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001882 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001883
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001884 /* Normalize f to be in the range [1.0, 2.0) */
1885 if (0.5 <= f && f < 1.0) {
1886 f *= 2.0;
1887 e--;
1888 }
1889 else if (f == 0.0)
1890 e = 0;
1891 else {
1892 PyErr_SetString(PyExc_SystemError,
1893 "frexp() result out of range");
1894 return -1;
1895 }
1896
1897 if (e >= 1024)
1898 goto Overflow;
1899 else if (e < -1022) {
1900 /* Gradual underflow */
1901 f = ldexp(f, 1022 + e);
1902 e = 0;
1903 }
1904 else if (!(e == 0 && f == 0.0)) {
1905 e += 1023;
1906 f -= 1.0; /* Get rid of leading 1 */
1907 }
1908
1909 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1910 f *= 268435456.0; /* 2**28 */
1911 fhi = (unsigned int)f; /* Truncate */
1912 assert(fhi < 268435456);
1913
1914 f -= (double)fhi;
1915 f *= 16777216.0; /* 2**24 */
1916 flo = (unsigned int)(f + 0.5); /* Round */
1917 assert(flo <= 16777216);
1918 if (flo >> 24) {
1919 /* The carry propagated out of a string of 24 1 bits. */
1920 flo = 0;
1921 ++fhi;
1922 if (fhi >> 28) {
1923 /* And it also progagated out of the next 28 bits. */
1924 fhi = 0;
1925 ++e;
1926 if (e >= 2047)
1927 goto Overflow;
1928 }
1929 }
1930
1931 /* First byte */
1932 *p = (sign << 7) | (e >> 4);
1933 p += incr;
1934
1935 /* Second byte */
1936 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1937 p += incr;
1938
1939 /* Third byte */
1940 *p = (fhi >> 16) & 0xFF;
1941 p += incr;
1942
1943 /* Fourth byte */
1944 *p = (fhi >> 8) & 0xFF;
1945 p += incr;
1946
1947 /* Fifth byte */
1948 *p = fhi & 0xFF;
1949 p += incr;
1950
1951 /* Sixth byte */
1952 *p = (flo >> 16) & 0xFF;
1953 p += incr;
1954
1955 /* Seventh byte */
1956 *p = (flo >> 8) & 0xFF;
1957 p += incr;
1958
1959 /* Eighth byte */
1960 *p = flo & 0xFF;
1961 p += incr;
1962
1963 /* Done */
1964 return 0;
1965
1966 Overflow:
1967 PyErr_SetString(PyExc_OverflowError,
1968 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001969 return -1;
1970 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001971 else {
1972 const char *s = (char*)&x;
1973 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001974
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001975 if ((double_format == ieee_little_endian_format && !le)
1976 || (double_format == ieee_big_endian_format && le)) {
1977 p += 7;
1978 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001979 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001980
1981 for (i = 0; i < 8; i++) {
1982 *p = *s++;
1983 p += incr;
1984 }
1985 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001986 }
Tim Peters9905b942003-03-20 20:53:32 +00001987}
1988
1989double
1990_PyFloat_Unpack4(const unsigned char *p, int le)
1991{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001992 if (float_format == unknown_format) {
1993 unsigned char sign;
1994 int e;
1995 unsigned int f;
1996 double x;
1997 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001998
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999 if (le) {
2000 p += 3;
2001 incr = -1;
2002 }
2003
2004 /* First byte */
2005 sign = (*p >> 7) & 1;
2006 e = (*p & 0x7F) << 1;
2007 p += incr;
2008
2009 /* Second byte */
2010 e |= (*p >> 7) & 1;
2011 f = (*p & 0x7F) << 16;
2012 p += incr;
2013
2014 if (e == 255) {
2015 PyErr_SetString(
2016 PyExc_ValueError,
2017 "can't unpack IEEE 754 special value "
2018 "on non-IEEE platform");
2019 return -1;
2020 }
2021
2022 /* Third byte */
2023 f |= *p << 8;
2024 p += incr;
2025
2026 /* Fourth byte */
2027 f |= *p;
2028
2029 x = (double)f / 8388608.0;
2030
2031 /* XXX This sadly ignores Inf/NaN issues */
2032 if (e == 0)
2033 e = -126;
2034 else {
2035 x += 1.0;
2036 e -= 127;
2037 }
2038 x = ldexp(x, e);
2039
2040 if (sign)
2041 x = -x;
2042
2043 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002044 }
Tim Peters9905b942003-03-20 20:53:32 +00002045 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002046 float x;
2047
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002048 if ((float_format == ieee_little_endian_format && !le)
2049 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002050 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002051 char *d = &buf[3];
2052 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002053
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002054 for (i = 0; i < 4; i++) {
2055 *d-- = *p++;
2056 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002057 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002058 }
2059 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002060 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002061 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002062
2063 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002064 }
Tim Peters9905b942003-03-20 20:53:32 +00002065}
2066
2067double
2068_PyFloat_Unpack8(const unsigned char *p, int le)
2069{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002070 if (double_format == unknown_format) {
2071 unsigned char sign;
2072 int e;
2073 unsigned int fhi, flo;
2074 double x;
2075 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002076
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002077 if (le) {
2078 p += 7;
2079 incr = -1;
2080 }
2081
2082 /* First byte */
2083 sign = (*p >> 7) & 1;
2084 e = (*p & 0x7F) << 4;
2085
2086 p += incr;
2087
2088 /* Second byte */
2089 e |= (*p >> 4) & 0xF;
2090 fhi = (*p & 0xF) << 24;
2091 p += incr;
2092
2093 if (e == 2047) {
2094 PyErr_SetString(
2095 PyExc_ValueError,
2096 "can't unpack IEEE 754 special value "
2097 "on non-IEEE platform");
2098 return -1.0;
2099 }
2100
2101 /* Third byte */
2102 fhi |= *p << 16;
2103 p += incr;
2104
2105 /* Fourth byte */
2106 fhi |= *p << 8;
2107 p += incr;
2108
2109 /* Fifth byte */
2110 fhi |= *p;
2111 p += incr;
2112
2113 /* Sixth byte */
2114 flo = *p << 16;
2115 p += incr;
2116
2117 /* Seventh byte */
2118 flo |= *p << 8;
2119 p += incr;
2120
2121 /* Eighth byte */
2122 flo |= *p;
2123
2124 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2125 x /= 268435456.0; /* 2**28 */
2126
2127 if (e == 0)
2128 e = -1022;
2129 else {
2130 x += 1.0;
2131 e -= 1023;
2132 }
2133 x = ldexp(x, e);
2134
2135 if (sign)
2136 x = -x;
2137
2138 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002139 }
Tim Peters9905b942003-03-20 20:53:32 +00002140 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002141 double x;
2142
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002143 if ((double_format == ieee_little_endian_format && !le)
2144 || (double_format == ieee_big_endian_format && le)) {
2145 char buf[8];
2146 char *d = &buf[7];
2147 int i;
2148
2149 for (i = 0; i < 8; i++) {
2150 *d-- = *p++;
2151 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002152 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002153 }
2154 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002155 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002156 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002157
2158 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002159 }
Tim Peters9905b942003-03-20 20:53:32 +00002160}