blob: ca05f0da1614793cf41bd56534d2da9a3c1bb798 [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
Christian Heimesc94e2b52008-01-14 04:13:37 +000013
Jack Janseneddc1442003-11-20 01:44:59 +000014#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000015extern double fmod(double, double);
16extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000017#endif
18
Neal Norwitz5f95a792008-01-25 08:04:16 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000026#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000027#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
30 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
32};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
42 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000043 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000047 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 q = p + N_FLOATOBJECTS;
51 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000052 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 return p + N_FLOATOBJECTS - 1;
55}
56
Christian Heimesdfdfaab2007-12-01 11:20:10 +000057double
58PyFloat_GetMax(void)
59{
60 return DBL_MAX;
61}
62
63double
64PyFloat_GetMin(void)
65{
66 return DBL_MIN;
67}
68
Christian Heimes796fc312008-01-30 18:58:29 +000069static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000070
71PyDoc_STRVAR(floatinfo__doc__,
72"sys.floatinfo\n\
73\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
79 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
96};
97
98static PyStructSequence_Desc floatinfo_desc = {
99 "sys.floatinfo", /* name */
100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
103};
104
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Christian Heimes796fc312008-01-30 18:58:29 +0000108 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000109 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000110
Christian Heimesc94e2b52008-01-14 04:13:37 +0000111 floatinfo = PyStructSequence_New(&FloatInfoType);
112 if (floatinfo == NULL) {
113 return NULL;
114 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000115
Christian Heimesc94e2b52008-01-14 04:13:37 +0000116#define SetIntFlag(flag) \
117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
118#define SetDblFlag(flag) \
119 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000120
Christian Heimesc94e2b52008-01-14 04:13:37 +0000121 SetDblFlag(DBL_MAX);
122 SetIntFlag(DBL_MAX_EXP);
123 SetIntFlag(DBL_MAX_10_EXP);
124 SetDblFlag(DBL_MIN);
125 SetIntFlag(DBL_MIN_EXP);
126 SetIntFlag(DBL_MIN_10_EXP);
127 SetIntFlag(DBL_DIG);
128 SetIntFlag(DBL_MANT_DIG);
129 SetDblFlag(DBL_EPSILON);
130 SetIntFlag(FLT_RADIX);
131 SetIntFlag(FLT_ROUNDS);
132#undef SetIntFlag
133#undef SetDblFlag
134
135 if (PyErr_Occurred()) {
136 Py_CLEAR(floatinfo);
137 return NULL;
138 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000139 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000140}
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000145 register PyFloatObject *op;
146 if (free_list == NULL) {
147 if ((free_list = fill_free_list()) == NULL)
148 return NULL;
149 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000150 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000151 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000152 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000153 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000154 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Tim Petersef14d732000-09-23 03:39:17 +0000158/**************************************************************************
159RED_FLAG 22-Sep-2000 tim
160PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
161
1621. If v was a regular string, *pend was set to point to its terminating
163 null byte. That's useless (the caller can find that without any
164 help from this function!).
165
1662. If v was a Unicode string, or an object convertible to a character
167 buffer, *pend was set to point into stack trash (the auto temp
168 vector holding the character buffer). That was downright dangerous.
169
170Since we can't change the interface of a public API function, pend is
171still supported but now *officially* useless: if pend is not NULL,
172*pend is set to NULL.
173**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000175PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000176{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000177 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000178 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000179 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000180#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000181 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000182#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184
Tim Petersef14d732000-09-23 03:39:17 +0000185 if (pend)
186 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000187 if (PyString_Check(v)) {
188 s = PyString_AS_STRING(v);
189 len = PyString_GET_SIZE(v);
190 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000191#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000192 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000193 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000194 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000195 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000196 return NULL;
197 }
Tim Petersef14d732000-09-23 03:39:17 +0000198 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000200 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000201 NULL))
202 return NULL;
203 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000204 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000205 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000206#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000207 else if (PyObject_AsCharBuffer(v, &s, &len)) {
208 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000209 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000211 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000212
Guido van Rossum4c08d552000-03-10 22:55:18 +0000213 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000214 while (*s && isspace(Py_CHARMASK(*s)))
215 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000216 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 PyErr_SetString(PyExc_ValueError, "empty string for float()");
218 return NULL;
219 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000220 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000221 /* We don't care about overflow or underflow. If the platform supports
222 * them, infinities and signed zeroes (on underflow) are fine.
223 * However, strtod can return 0 for denormalized numbers, where atof
224 * does not. So (alas!) we special-case a zero result. Note that
225 * whether strtod sets errno on underflow is not defined, so we can't
226 * key off errno.
227 */
Tim Peters858346e2000-09-25 21:01:28 +0000228 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000229 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000230 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000231 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000232 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000233 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000234 if (end > last)
235 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000236 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000237 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000238 char *p = (char*)sp;
239 int sign = 1;
240
241 if (*p == '-') {
242 sign = -1;
243 p++;
244 }
245 if (*p == '+') {
246 p++;
247 }
248 if (PyOS_strnicmp(p, "inf", 4) == 0) {
249 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
250 }
251#ifdef Py_NAN
252 if(PyOS_strnicmp(p, "nan", 4) == 0) {
253 return PyFloat_FromDouble(Py_NAN);
254 }
255#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000256 PyOS_snprintf(buffer, sizeof(buffer),
257 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000258 PyErr_SetString(PyExc_ValueError, buffer);
259 return NULL;
260 }
261 /* Since end != s, the platform made *some* kind of sense out
262 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000263 while (*end && isspace(Py_CHARMASK(*end)))
264 end++;
265 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000266 PyOS_snprintf(buffer, sizeof(buffer),
267 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000268 PyErr_SetString(PyExc_ValueError, buffer);
269 return NULL;
270 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000271 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000272 PyErr_SetString(PyExc_ValueError,
273 "null byte in argument for float()");
274 return NULL;
275 }
Tim Petersef14d732000-09-23 03:39:17 +0000276 if (x == 0.0) {
277 /* See above -- may have been strtod being anal
278 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000279 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000280 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000281 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000282 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000283 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000284 return PyFloat_FromDouble(x);
285}
286
Guido van Rossum234f9421993-06-17 12:35:49 +0000287static void
Fred Drakefd99de62000-07-09 05:02:18 +0000288float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000289{
Guido van Rossum9475a232001-10-05 20:51:39 +0000290 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000291 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000292 free_list = op;
293 }
294 else
Christian Heimese93237d2007-12-19 02:37:44 +0000295 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000296}
297
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298double
Fred Drakefd99de62000-07-09 05:02:18 +0000299PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000301 PyNumberMethods *nb;
302 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000304
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 if (op && PyFloat_Check(op))
306 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000307
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000308 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000310 return -1;
311 }
Tim Petersd2364e82001-11-01 20:09:42 +0000312
Christian Heimese93237d2007-12-19 02:37:44 +0000313 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000314 PyErr_SetString(PyExc_TypeError, "a float is required");
315 return -1;
316 }
317
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000318 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000319 if (fo == NULL)
320 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321 if (!PyFloat_Check(fo)) {
322 PyErr_SetString(PyExc_TypeError,
323 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000324 return -1;
325 }
Tim Petersd2364e82001-11-01 20:09:42 +0000326
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 val = PyFloat_AS_DOUBLE(fo);
328 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000329
Guido van Rossumb6775db1994-08-01 11:34:53 +0000330 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331}
332
333/* Methods */
334
Tim Peters97019e42001-11-28 22:43:45 +0000335static void
336format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337{
338 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000339 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000340 int i;
341
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342 /* Subroutine for float_repr and float_print.
343 We want float numbers to be recognizable as such,
344 i.e., they should contain a decimal point or an exponent.
345 However, %g may print the number as an integer;
346 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000347
348 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000349 PyOS_snprintf(format, 32, "%%.%ig", precision);
350 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 cp = buf;
352 if (*cp == '-')
353 cp++;
354 for (; *cp != '\0'; cp++) {
355 /* Any non-digit means it's not an integer;
356 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000357 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358 break;
359 }
360 if (*cp == '\0') {
361 *cp++ = '.';
362 *cp++ = '0';
363 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000364 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000366 /* Checking the next three chars should be more than enough to
367 * detect inf or nan, even on Windows. We check for inf or nan
368 * at last because they are rare cases.
369 */
370 for (i=0; *cp != '\0' && i<3; cp++, i++) {
371 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
372 continue;
373 /* found something that is neither a digit nor point
374 * it might be a NaN or INF
375 */
376#ifdef Py_NAN
377 if (Py_IS_NAN(v->ob_fval)) {
378 strcpy(buf, "nan");
379 }
380 else
381#endif
382 if (Py_IS_INFINITY(v->ob_fval)) {
383 cp = buf;
384 if (*cp == '-')
385 cp++;
386 strcpy(cp, "inf");
387 }
388 break;
389 }
390
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Tim Peters97019e42001-11-28 22:43:45 +0000393/* XXX PyFloat_AsStringEx should not be a public API function (for one
394 XXX thing, its signature passes a buffer without a length; for another,
395 XXX it isn't useful outside this file).
396*/
397void
398PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
399{
400 format_float(buf, 100, v, precision);
401}
402
Christian Heimesf15c66e2007-12-11 00:54:34 +0000403#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000404/* The following function is based on Tcl_PrintDouble,
405 * from tclUtil.c.
406 */
407
408#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
409#define is_nan(d) ((d) != (d))
410
411static void
412format_double_repr(char *dst, double value)
413{
414 char *p, c;
415 int exp;
416 int signum;
417 char buffer[30];
418
419 /*
420 * Handle NaN.
421 */
422
423 if (is_nan(value)) {
424 strcpy(dst, "nan");
425 return;
426 }
427
428 /*
429 * Handle infinities.
430 */
431
432 if (is_infinite(value)) {
433 if (value < 0) {
434 strcpy(dst, "-inf");
435 } else {
436 strcpy(dst, "inf");
437 }
438 return;
439 }
440
441 /*
442 * Ordinary (normal and denormal) values.
443 */
444
445 exp = _PyFloat_Digits(buffer, value, &signum)+1;
446 if (signum) {
447 *dst++ = '-';
448 }
449 p = buffer;
450 if (exp < -3 || exp > 17) {
451 /*
452 * E format for numbers < 1e-3 or >= 1e17.
453 */
454
455 *dst++ = *p++;
456 c = *p;
457 if (c != '\0') {
458 *dst++ = '.';
459 while (c != '\0') {
460 *dst++ = c;
461 c = *++p;
462 }
463 }
464 sprintf(dst, "e%+d", exp-1);
465 } else {
466 /*
467 * F format for others.
468 */
469
470 if (exp <= 0) {
471 *dst++ = '0';
472 }
473 c = *p;
474 while (exp-- > 0) {
475 if (c != '\0') {
476 *dst++ = c;
477 c = *++p;
478 } else {
479 *dst++ = '0';
480 }
481 }
482 *dst++ = '.';
483 if (c == '\0') {
484 *dst++ = '0';
485 } else {
486 while (++exp < 0) {
487 *dst++ = '0';
488 }
489 while (c != '\0') {
490 *dst++ = c;
491 c = *++p;
492 }
493 }
494 *dst++ = '\0';
495 }
496}
497
498static void
499format_float_repr(char *buf, PyFloatObject *v)
500{
501 assert(PyFloat_Check(v));
502 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
503}
504
Christian Heimesf15c66e2007-12-11 00:54:34 +0000505#endif /* Py_BROKEN_REPR */
506
Neil Schemenauer32117e52001-01-04 01:44:34 +0000507/* Macro and helper that convert PyObject obj to a C double and store
508 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000509 slot function. If conversion to double raises an exception, obj is
510 set to NULL, and the function invoking this macro returns NULL. If
511 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
512 stored in obj, and returned from the function invoking this macro.
513*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000514#define CONVERT_TO_DOUBLE(obj, dbl) \
515 if (PyFloat_Check(obj)) \
516 dbl = PyFloat_AS_DOUBLE(obj); \
517 else if (convert_to_double(&(obj), &(dbl)) < 0) \
518 return obj;
519
520static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000521convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000522{
523 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000524
Neil Schemenauer32117e52001-01-04 01:44:34 +0000525 if (PyInt_Check(obj)) {
526 *dbl = (double)PyInt_AS_LONG(obj);
527 }
528 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000530 if (*dbl == -1.0 && PyErr_Occurred()) {
531 *v = NULL;
532 return -1;
533 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000534 }
535 else {
536 Py_INCREF(Py_NotImplemented);
537 *v = Py_NotImplemented;
538 return -1;
539 }
540 return 0;
541}
542
Guido van Rossum57072eb1999-12-23 19:00:28 +0000543/* Precisions used by repr() and str(), respectively.
544
545 The repr() precision (17 significant decimal digits) is the minimal number
546 that is guaranteed to have enough precision so that if the number is read
547 back in the exact same binary value is recreated. This is true for IEEE
548 floating point by design, and also happens to work for all other modern
549 hardware.
550
551 The str() precision is chosen so that in most cases, the rounding noise
552 created by various operations is suppressed, while giving plenty of
553 precision for practical use.
554
555*/
556
557#define PREC_REPR 17
558#define PREC_STR 12
559
Tim Peters97019e42001-11-28 22:43:45 +0000560/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
561 XXX they pass a char buffer without passing a length.
562*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000563void
Fred Drakefd99de62000-07-09 05:02:18 +0000564PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000565{
Tim Peters97019e42001-11-28 22:43:45 +0000566 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000567}
568
Tim Peters72f98e92001-05-08 15:19:57 +0000569void
570PyFloat_AsReprString(char *buf, PyFloatObject *v)
571{
Tim Peters97019e42001-11-28 22:43:45 +0000572 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000573}
574
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000575/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000576static int
Fred Drakefd99de62000-07-09 05:02:18 +0000577float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578{
579 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000580 format_float(buf, sizeof(buf), v,
581 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000582 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000584 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000585 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000586}
587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000589float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000591#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000592 char buf[30];
593 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000594#else
595 char buf[100];
596 format_float(buf, sizeof(buf), v, PREC_REPR);
597#endif
598
Guido van Rossum57072eb1999-12-23 19:00:28 +0000599 return PyString_FromString(buf);
600}
601
602static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000603float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000604{
605 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000606 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000608}
609
Tim Peters307fa782004-09-23 08:06:40 +0000610/* Comparison is pretty much a nightmare. When comparing float to float,
611 * we do it as straightforwardly (and long-windedly) as conceivable, so
612 * that, e.g., Python x == y delivers the same result as the platform
613 * C x == y when x and/or y is a NaN.
614 * When mixing float with an integer type, there's no good *uniform* approach.
615 * Converting the double to an integer obviously doesn't work, since we
616 * may lose info from fractional bits. Converting the integer to a double
617 * also has two failure modes: (1) a long int may trigger overflow (too
618 * large to fit in the dynamic range of a C double); (2) even a C long may have
619 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
620 * 63 bits of precision, but a C double probably has only 53), and then
621 * we can falsely claim equality when low-order integer bits are lost by
622 * coercion to double. So this part is painful too.
623 */
624
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000625static PyObject*
626float_richcompare(PyObject *v, PyObject *w, int op)
627{
628 double i, j;
629 int r = 0;
630
Tim Peters307fa782004-09-23 08:06:40 +0000631 assert(PyFloat_Check(v));
632 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000633
Tim Peters307fa782004-09-23 08:06:40 +0000634 /* Switch on the type of w. Set i and j to doubles to be compared,
635 * and op to the richcomp to use.
636 */
637 if (PyFloat_Check(w))
638 j = PyFloat_AS_DOUBLE(w);
639
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000640 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000641 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000642 /* If i is an infinity, its magnitude exceeds any
643 * finite integer, so it doesn't matter which int we
644 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000645 */
646 j = 0.0;
647 else
648 goto Unimplemented;
649 }
650
651 else if (PyInt_Check(w)) {
652 long jj = PyInt_AS_LONG(w);
653 /* In the worst realistic case I can imagine, C double is a
654 * Cray single with 48 bits of precision, and long has 64
655 * bits.
656 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000657#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000658 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
659 if (abs >> 48) {
660 /* Needs more than 48 bits. Make it take the
661 * PyLong path.
662 */
663 PyObject *result;
664 PyObject *ww = PyLong_FromLong(jj);
665
666 if (ww == NULL)
667 return NULL;
668 result = float_richcompare(v, ww, op);
669 Py_DECREF(ww);
670 return result;
671 }
672#endif
673 j = (double)jj;
674 assert((long)j == jj);
675 }
676
677 else if (PyLong_Check(w)) {
678 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
679 int wsign = _PyLong_Sign(w);
680 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000681 int exponent;
682
683 if (vsign != wsign) {
684 /* Magnitudes are irrelevant -- the signs alone
685 * determine the outcome.
686 */
687 i = (double)vsign;
688 j = (double)wsign;
689 goto Compare;
690 }
691 /* The signs are the same. */
692 /* Convert w to a double if it fits. In particular, 0 fits. */
693 nbits = _PyLong_NumBits(w);
694 if (nbits == (size_t)-1 && PyErr_Occurred()) {
695 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000696 * to hold the # of bits. Replace with little doubles
697 * that give the same outcome -- w is so large that
698 * its magnitude must exceed the magnitude of any
699 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000700 */
701 PyErr_Clear();
702 i = (double)vsign;
703 assert(wsign != 0);
704 j = wsign * 2.0;
705 goto Compare;
706 }
707 if (nbits <= 48) {
708 j = PyLong_AsDouble(w);
709 /* It's impossible that <= 48 bits overflowed. */
710 assert(j != -1.0 || ! PyErr_Occurred());
711 goto Compare;
712 }
713 assert(wsign != 0); /* else nbits was 0 */
714 assert(vsign != 0); /* if vsign were 0, then since wsign is
715 * not 0, we would have taken the
716 * vsign != wsign branch at the start */
717 /* We want to work with non-negative numbers. */
718 if (vsign < 0) {
719 /* "Multiply both sides" by -1; this also swaps the
720 * comparator.
721 */
722 i = -i;
723 op = _Py_SwappedOp[op];
724 }
725 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000726 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000727 /* exponent is the # of bits in v before the radix point;
728 * we know that nbits (the # of bits in w) > 48 at this point
729 */
730 if (exponent < 0 || (size_t)exponent < nbits) {
731 i = 1.0;
732 j = 2.0;
733 goto Compare;
734 }
735 if ((size_t)exponent > nbits) {
736 i = 2.0;
737 j = 1.0;
738 goto Compare;
739 }
740 /* v and w have the same number of bits before the radix
741 * point. Construct two longs that have the same comparison
742 * outcome.
743 */
744 {
745 double fracpart;
746 double intpart;
747 PyObject *result = NULL;
748 PyObject *one = NULL;
749 PyObject *vv = NULL;
750 PyObject *ww = w;
751
752 if (wsign < 0) {
753 ww = PyNumber_Negative(w);
754 if (ww == NULL)
755 goto Error;
756 }
757 else
758 Py_INCREF(ww);
759
760 fracpart = modf(i, &intpart);
761 vv = PyLong_FromDouble(intpart);
762 if (vv == NULL)
763 goto Error;
764
765 if (fracpart != 0.0) {
766 /* Shift left, and or a 1 bit into vv
767 * to represent the lost fraction.
768 */
769 PyObject *temp;
770
771 one = PyInt_FromLong(1);
772 if (one == NULL)
773 goto Error;
774
775 temp = PyNumber_Lshift(ww, one);
776 if (temp == NULL)
777 goto Error;
778 Py_DECREF(ww);
779 ww = temp;
780
781 temp = PyNumber_Lshift(vv, one);
782 if (temp == NULL)
783 goto Error;
784 Py_DECREF(vv);
785 vv = temp;
786
787 temp = PyNumber_Or(vv, one);
788 if (temp == NULL)
789 goto Error;
790 Py_DECREF(vv);
791 vv = temp;
792 }
793
794 r = PyObject_RichCompareBool(vv, ww, op);
795 if (r < 0)
796 goto Error;
797 result = PyBool_FromLong(r);
798 Error:
799 Py_XDECREF(vv);
800 Py_XDECREF(ww);
801 Py_XDECREF(one);
802 return result;
803 }
804 } /* else if (PyLong_Check(w)) */
805
806 else /* w isn't float, int, or long */
807 goto Unimplemented;
808
809 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000810 PyFPE_START_PROTECT("richcompare", return NULL)
811 switch (op) {
812 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000813 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000814 break;
815 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000816 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000817 break;
818 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000819 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000820 break;
821 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000822 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000823 break;
824 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000825 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000826 break;
827 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000828 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000829 break;
830 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000831 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000832 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000833
834 Unimplemented:
835 Py_INCREF(Py_NotImplemented);
836 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000837}
838
Guido van Rossum9bfef441993-03-29 10:43:31 +0000839static long
Fred Drakefd99de62000-07-09 05:02:18 +0000840float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000841{
Tim Peters39dce292000-08-15 03:34:48 +0000842 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000843}
844
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000845static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000846float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000847{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000848 double a,b;
849 CONVERT_TO_DOUBLE(v, a);
850 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000851 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000852 a = a + b;
853 PyFPE_END_PROTECT(a)
854 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000855}
856
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000857static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000858float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000859{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000860 double a,b;
861 CONVERT_TO_DOUBLE(v, a);
862 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000863 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000864 a = a - b;
865 PyFPE_END_PROTECT(a)
866 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000867}
868
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000869static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000870float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000871{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000872 double a,b;
873 CONVERT_TO_DOUBLE(v, a);
874 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000875 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000876 a = a * b;
877 PyFPE_END_PROTECT(a)
878 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879}
880
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000882float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000883{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000884 double a,b;
885 CONVERT_TO_DOUBLE(v, a);
886 CONVERT_TO_DOUBLE(w, b);
887 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000888 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889 return NULL;
890 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000891 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000892 a = a / b;
893 PyFPE_END_PROTECT(a)
894 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000895}
896
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000897static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000898float_classic_div(PyObject *v, PyObject *w)
899{
900 double a,b;
901 CONVERT_TO_DOUBLE(v, a);
902 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000903 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000904 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
905 return NULL;
906 if (b == 0.0) {
907 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
908 return NULL;
909 }
910 PyFPE_START_PROTECT("divide", return 0)
911 a = a / b;
912 PyFPE_END_PROTECT(a)
913 return PyFloat_FromDouble(a);
914}
915
916static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000917float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000918{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000919 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000920 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000921 CONVERT_TO_DOUBLE(v, vx);
922 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000923 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000924 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000925 return NULL;
926 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000927 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000928 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000929 /* note: checking mod*wx < 0 is incorrect -- underflows to
930 0 if wx < sqrt(smallest nonzero double) */
931 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000932 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000933 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000934 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000935 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000936}
937
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000938static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000939float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000940{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000941 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000942 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000943 CONVERT_TO_DOUBLE(v, vx);
944 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000945 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000947 return NULL;
948 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000949 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000950 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000951 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000952 exact multiple of wx. But this is fp arithmetic, and fp
953 vx - mod is an approximation; the result is that div may
954 not be an exact integral value after the division, although
955 it will always be very close to one.
956 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000957 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000958 if (mod) {
959 /* ensure the remainder has the same sign as the denominator */
960 if ((wx < 0) != (mod < 0)) {
961 mod += wx;
962 div -= 1.0;
963 }
964 }
965 else {
966 /* the remainder is zero, and in the presence of signed zeroes
967 fmod returns different results across platforms; ensure
968 it has the same sign as the denominator; we'd like to do
969 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000970 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000971 if (wx < 0.0)
972 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000973 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000974 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000975 if (div) {
976 floordiv = floor(div);
977 if (div - floordiv > 0.5)
978 floordiv += 1.0;
979 }
980 else {
981 /* div is zero - get the same sign as the true quotient */
982 div *= div; /* hide "div = +0" from optimizers */
983 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
984 }
985 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000986 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000987}
988
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000990float_floor_div(PyObject *v, PyObject *w)
991{
992 PyObject *t, *r;
993
994 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000995 if (t == NULL || t == Py_NotImplemented)
996 return t;
997 assert(PyTuple_CheckExact(t));
998 r = PyTuple_GET_ITEM(t, 0);
999 Py_INCREF(r);
1000 Py_DECREF(t);
1001 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001002}
1003
1004static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001005float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001006{
1007 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001008
1009 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001010 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001011 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001012 return NULL;
1013 }
1014
Neil Schemenauer32117e52001-01-04 01:44:34 +00001015 CONVERT_TO_DOUBLE(v, iv);
1016 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001017
1018 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001019 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001020 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001021 }
Tim Peters96685bf2001-08-23 22:31:37 +00001022 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001023 if (iw < 0.0) {
1024 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001025 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001026 return NULL;
1027 }
1028 return PyFloat_FromDouble(0.0);
1029 }
Tim Peterse87568d2003-05-24 20:18:24 +00001030 if (iv < 0.0) {
1031 /* Whether this is an error is a mess, and bumps into libm
1032 * bugs so we have to figure it out ourselves.
1033 */
1034 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001035 PyErr_SetString(PyExc_ValueError, "negative number "
1036 "cannot be raised to a fractional power");
1037 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001038 }
1039 /* iw is an exact integer, albeit perhaps a very large one.
1040 * -1 raised to an exact integer should never be exceptional.
1041 * Alas, some libms (chiefly glibc as of early 2003) return
1042 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1043 * happen to be representable in a *C* integer. That's a
1044 * bug; we let that slide in math.pow() (which currently
1045 * reflects all platform accidents), but not for Python's **.
1046 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001047 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001048 /* Return 1 if iw is even, -1 if iw is odd; there's
1049 * no guarantee that any C integral type is big
1050 * enough to hold iw, so we have to check this
1051 * indirectly.
1052 */
1053 ix = floor(iw * 0.5) * 2.0;
1054 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1055 }
1056 /* Else iv != -1.0, and overflow or underflow are possible.
1057 * Unless we're to write pow() ourselves, we have to trust
1058 * the platform to do this correctly.
1059 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001060 }
Tim Peters96685bf2001-08-23 22:31:37 +00001061 errno = 0;
1062 PyFPE_START_PROTECT("pow", return NULL)
1063 ix = pow(iv, iw);
1064 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001065 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001066 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001067 /* We don't expect any errno value other than ERANGE, but
1068 * the range of libm bugs appears unbounded.
1069 */
Alex Martelli348dc882006-08-23 22:17:59 +00001070 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1071 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001072 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001073 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001074 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001075}
1076
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001077static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001078float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001079{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001080 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001081}
1082
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001083static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001084float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001085{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001086 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001087}
1088
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001089static int
Fred Drakefd99de62000-07-09 05:02:18 +00001090float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001091{
1092 return v->ob_fval != 0.0;
1093}
1094
Guido van Rossum234f9421993-06-17 12:35:49 +00001095static int
Fred Drakefd99de62000-07-09 05:02:18 +00001096float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001097{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001098 if (PyInt_Check(*pw)) {
1099 long x = PyInt_AsLong(*pw);
1100 *pw = PyFloat_FromDouble((double)x);
1101 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001102 return 0;
1103 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001104 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001105 double x = PyLong_AsDouble(*pw);
1106 if (x == -1.0 && PyErr_Occurred())
1107 return -1;
1108 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001109 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001110 return 0;
1111 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001112 else if (PyFloat_Check(*pw)) {
1113 Py_INCREF(*pv);
1114 Py_INCREF(*pw);
1115 return 0;
1116 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001117 return 1; /* Can't do it */
1118}
1119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001120static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001121float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001122{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001123 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001124 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001125
1126 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001127 /* Try to get out cheap if this fits in a Python int. The attempt
1128 * to cast to long must be protected, as C doesn't define what
1129 * happens if the double is too big to fit in a long. Some rare
1130 * systems raise an exception then (RISCOS was mentioned as one,
1131 * and someone using a non-default option on Sun also bumped into
1132 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1133 * still be vulnerable: if a long has more bits of precision than
1134 * a double, casting MIN/MAX to double may yield an approximation,
1135 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1136 * yield true from the C expression wholepart<=LONG_MAX, despite
1137 * that wholepart is actually greater than LONG_MAX.
1138 */
1139 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1140 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001141 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001142 }
1143 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001144}
1145
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001146static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001147float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001148{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001149 if (PyFloat_CheckExact(v))
1150 Py_INCREF(v);
1151 else
1152 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001153 return v;
1154}
1155
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001156static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001157float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001158{
1159 double self;
1160 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001161 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001162 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001163
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001164 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001165 PyObject *py_exponent = NULL;
1166 PyObject *numerator = NULL;
1167 PyObject *denominator = NULL;
1168 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001169 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001170
1171#define INPLACE_UPDATE(obj, call) \
1172 prev = obj; \
1173 obj = call; \
1174 Py_DECREF(prev); \
1175
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001176#ifdef FLT_RADIX
1177 if (FLT_RADIX != 2) {
1178 /* This routine depends on base-2 floating_point. */
1179 Py_INCREF(Py_NotImplemented);
1180 return Py_NotImplemented;
1181 }
1182#endif
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001183 CONVERT_TO_DOUBLE(v, self);
1184
1185 if (Py_IS_INFINITY(self)) {
1186 PyErr_SetString(PyExc_OverflowError,
1187 "Cannot pass infinity to float.as_integer_ratio.");
1188 return NULL;
1189 }
1190#ifdef Py_NAN
1191 if (Py_IS_NAN(self)) {
1192 PyErr_SetString(PyExc_ValueError,
1193 "Cannot pass nan to float.as_integer_ratio.");
1194 return NULL;
1195 }
1196#endif
1197
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001198 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001199 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001200 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001201
Raymond Hettingerf9859032008-02-01 23:45:44 +00001202 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001203 float_part *= 2.0;
1204 exponent--;
1205 }
Raymond Hettingerf9859032008-02-01 23:45:44 +00001206 if (i == 300) {
1207 /* Could not convert mantissa to an integer */
1208 Py_INCREF(Py_NotImplemented);
1209 return Py_NotImplemented;
1210 }
1211 /* self == float_part * 2**exponent exactly and float_part is integral */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001212
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001213 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001214 if (numerator == NULL) goto error;
1215
Raymond Hettingerf9859032008-02-01 23:45:44 +00001216 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001217 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001218 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001219 if (py_exponent == NULL) goto error;
1220 INPLACE_UPDATE(py_exponent,
1221 long_methods->nb_lshift(denominator, py_exponent));
1222 if (py_exponent == NULL) goto error;
1223 if (exponent > 0) {
1224 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001225 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001226 if (numerator == NULL) goto error;
1227 }
1228 else {
1229 Py_DECREF(denominator);
1230 denominator = py_exponent;
1231 py_exponent = NULL;
1232 }
1233
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001234 /* Returns ints instead of longs where possible */
1235 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1236 if (numerator == NULL) goto error;
1237 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1238 if (denominator == NULL) goto error;
1239
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001240 result_pair = PyTuple_Pack(2, numerator, denominator);
1241
1242#undef INPLACE_UPDATE
1243error:
1244 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001245 Py_XDECREF(denominator);
1246 Py_XDECREF(numerator);
1247 return result_pair;
1248}
1249
1250PyDoc_STRVAR(float_as_integer_ratio_doc,
1251"float.as_integer_ratio() -> (int, int)\n"
1252"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001253"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1254"float and with a positive denominator.\n"
1255"Raises OverflowError on infinities and a ValueError on nans.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001256"\n"
1257">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001258"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001259">>> (0.0).as_integer_ratio()\n"
1260"(0, 1)\n"
1261">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001262"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001263
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001264
Jeremy Hylton938ace62002-07-17 16:30:39 +00001265static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001266float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1267
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268static PyObject *
1269float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1270{
1271 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001272 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273
Guido van Rossumbef14172001-08-29 15:47:46 +00001274 if (type != &PyFloat_Type)
1275 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1277 return NULL;
1278 if (PyString_Check(x))
1279 return PyFloat_FromString(x, NULL);
1280 return PyNumber_Float(x);
1281}
1282
Guido van Rossumbef14172001-08-29 15:47:46 +00001283/* Wimpy, slow approach to tp_new calls for subtypes of float:
1284 first create a regular float from whatever arguments we got,
1285 then allocate a subtype instance and initialize its ob_fval
1286 from the regular float. The regular float is then thrown away.
1287*/
1288static PyObject *
1289float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1290{
Anthony Baxter377be112006-04-11 06:54:30 +00001291 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001292
1293 assert(PyType_IsSubtype(type, &PyFloat_Type));
1294 tmp = float_new(&PyFloat_Type, args, kwds);
1295 if (tmp == NULL)
1296 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001297 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001298 newobj = type->tp_alloc(type, 0);
1299 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001300 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001301 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001302 }
Anthony Baxter377be112006-04-11 06:54:30 +00001303 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001304 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001305 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001306}
1307
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001308static PyObject *
1309float_getnewargs(PyFloatObject *v)
1310{
1311 return Py_BuildValue("(d)", v->ob_fval);
1312}
1313
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001314/* this is for the benefit of the pack/unpack routines below */
1315
1316typedef enum {
1317 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1318} float_format_type;
1319
1320static float_format_type double_format, float_format;
1321static float_format_type detected_double_format, detected_float_format;
1322
1323static PyObject *
1324float_getformat(PyTypeObject *v, PyObject* arg)
1325{
1326 char* s;
1327 float_format_type r;
1328
1329 if (!PyString_Check(arg)) {
1330 PyErr_Format(PyExc_TypeError,
1331 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001332 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001333 return NULL;
1334 }
1335 s = PyString_AS_STRING(arg);
1336 if (strcmp(s, "double") == 0) {
1337 r = double_format;
1338 }
1339 else if (strcmp(s, "float") == 0) {
1340 r = float_format;
1341 }
1342 else {
1343 PyErr_SetString(PyExc_ValueError,
1344 "__getformat__() argument 1 must be "
1345 "'double' or 'float'");
1346 return NULL;
1347 }
1348
1349 switch (r) {
1350 case unknown_format:
1351 return PyString_FromString("unknown");
1352 case ieee_little_endian_format:
1353 return PyString_FromString("IEEE, little-endian");
1354 case ieee_big_endian_format:
1355 return PyString_FromString("IEEE, big-endian");
1356 default:
1357 Py_FatalError("insane float_format or double_format");
1358 return NULL;
1359 }
1360}
1361
1362PyDoc_STRVAR(float_getformat_doc,
1363"float.__getformat__(typestr) -> string\n"
1364"\n"
1365"You probably don't want to use this function. It exists mainly to be\n"
1366"used in Python's test suite.\n"
1367"\n"
1368"typestr must be 'double' or 'float'. This function returns whichever of\n"
1369"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1370"format of floating point numbers used by the C type named by typestr.");
1371
1372static PyObject *
1373float_setformat(PyTypeObject *v, PyObject* args)
1374{
1375 char* typestr;
1376 char* format;
1377 float_format_type f;
1378 float_format_type detected;
1379 float_format_type *p;
1380
1381 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1382 return NULL;
1383
1384 if (strcmp(typestr, "double") == 0) {
1385 p = &double_format;
1386 detected = detected_double_format;
1387 }
1388 else if (strcmp(typestr, "float") == 0) {
1389 p = &float_format;
1390 detected = detected_float_format;
1391 }
1392 else {
1393 PyErr_SetString(PyExc_ValueError,
1394 "__setformat__() argument 1 must "
1395 "be 'double' or 'float'");
1396 return NULL;
1397 }
1398
1399 if (strcmp(format, "unknown") == 0) {
1400 f = unknown_format;
1401 }
1402 else if (strcmp(format, "IEEE, little-endian") == 0) {
1403 f = ieee_little_endian_format;
1404 }
1405 else if (strcmp(format, "IEEE, big-endian") == 0) {
1406 f = ieee_big_endian_format;
1407 }
1408 else {
1409 PyErr_SetString(PyExc_ValueError,
1410 "__setformat__() argument 2 must be "
1411 "'unknown', 'IEEE, little-endian' or "
1412 "'IEEE, big-endian'");
1413 return NULL;
1414
1415 }
1416
1417 if (f != unknown_format && f != detected) {
1418 PyErr_Format(PyExc_ValueError,
1419 "can only set %s format to 'unknown' or the "
1420 "detected platform value", typestr);
1421 return NULL;
1422 }
1423
1424 *p = f;
1425 Py_RETURN_NONE;
1426}
1427
1428PyDoc_STRVAR(float_setformat_doc,
1429"float.__setformat__(typestr, fmt) -> None\n"
1430"\n"
1431"You probably don't want to use this function. It exists mainly to be\n"
1432"used in Python's test suite.\n"
1433"\n"
1434"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1435"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1436"one of the latter two if it appears to match the underlying C reality.\n"
1437"\n"
1438"Overrides the automatic determination of C-level floating point type.\n"
1439"This affects how floats are converted to and from binary strings.");
1440
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001441static PyObject *
1442float_getzero(PyObject *v, void *closure)
1443{
1444 return PyFloat_FromDouble(0.0);
1445}
1446
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001447static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001448 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1449 "Returns self, the complex conjugate of any float."},
1450 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1451 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001452 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1453 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001454 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001455 {"__getformat__", (PyCFunction)float_getformat,
1456 METH_O|METH_CLASS, float_getformat_doc},
1457 {"__setformat__", (PyCFunction)float_setformat,
1458 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001459 {NULL, NULL} /* sentinel */
1460};
1461
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001462static PyGetSetDef float_getset[] = {
1463 {"real",
1464 (getter)float_float, (setter)NULL,
1465 "the real part of a complex number",
1466 NULL},
1467 {"imag",
1468 (getter)float_getzero, (setter)NULL,
1469 "the imaginary part of a complex number",
1470 NULL},
1471 {NULL} /* Sentinel */
1472};
1473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001474PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475"float(x) -> floating point number\n\
1476\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001477Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478
1479
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001480static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001481 float_add, /*nb_add*/
1482 float_sub, /*nb_subtract*/
1483 float_mul, /*nb_multiply*/
1484 float_classic_div, /*nb_divide*/
1485 float_rem, /*nb_remainder*/
1486 float_divmod, /*nb_divmod*/
1487 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001488 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001489 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001490 (unaryfunc)float_abs, /*nb_absolute*/
1491 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001492 0, /*nb_invert*/
1493 0, /*nb_lshift*/
1494 0, /*nb_rshift*/
1495 0, /*nb_and*/
1496 0, /*nb_xor*/
1497 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001498 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001499 float_trunc, /*nb_int*/
1500 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001501 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001502 0, /* nb_oct */
1503 0, /* nb_hex */
1504 0, /* nb_inplace_add */
1505 0, /* nb_inplace_subtract */
1506 0, /* nb_inplace_multiply */
1507 0, /* nb_inplace_divide */
1508 0, /* nb_inplace_remainder */
1509 0, /* nb_inplace_power */
1510 0, /* nb_inplace_lshift */
1511 0, /* nb_inplace_rshift */
1512 0, /* nb_inplace_and */
1513 0, /* nb_inplace_xor */
1514 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001515 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001516 float_div, /* nb_true_divide */
1517 0, /* nb_inplace_floor_divide */
1518 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001519};
1520
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001521PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001522 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001523 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001525 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526 (destructor)float_dealloc, /* tp_dealloc */
1527 (printfunc)float_print, /* tp_print */
1528 0, /* tp_getattr */
1529 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001530 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531 (reprfunc)float_repr, /* tp_repr */
1532 &float_as_number, /* tp_as_number */
1533 0, /* tp_as_sequence */
1534 0, /* tp_as_mapping */
1535 (hashfunc)float_hash, /* tp_hash */
1536 0, /* tp_call */
1537 (reprfunc)float_str, /* tp_str */
1538 PyObject_GenericGetAttr, /* tp_getattro */
1539 0, /* tp_setattro */
1540 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001541 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1542 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543 float_doc, /* tp_doc */
1544 0, /* tp_traverse */
1545 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001546 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 0, /* tp_weaklistoffset */
1548 0, /* tp_iter */
1549 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001550 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001552 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 0, /* tp_base */
1554 0, /* tp_dict */
1555 0, /* tp_descr_get */
1556 0, /* tp_descr_set */
1557 0, /* tp_dictoffset */
1558 0, /* tp_init */
1559 0, /* tp_alloc */
1560 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001561};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001562
1563void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001564_PyFloat_Init(void)
1565{
1566 /* We attempt to determine if this machine is using IEEE
1567 floating point formats by peering at the bits of some
1568 carefully chosen values. If it looks like we are on an
1569 IEEE platform, the float packing/unpacking routines can
1570 just copy bits, if not they resort to arithmetic & shifts
1571 and masks. The shifts & masks approach works on all finite
1572 values, but what happens to infinities, NaNs and signed
1573 zeroes on packing is an accident, and attempting to unpack
1574 a NaN or an infinity will raise an exception.
1575
1576 Note that if we're on some whacked-out platform which uses
1577 IEEE formats but isn't strictly little-endian or big-
1578 endian, we will fall back to the portable shifts & masks
1579 method. */
1580
1581#if SIZEOF_DOUBLE == 8
1582 {
1583 double x = 9006104071832581.0;
1584 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1585 detected_double_format = ieee_big_endian_format;
1586 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1587 detected_double_format = ieee_little_endian_format;
1588 else
1589 detected_double_format = unknown_format;
1590 }
1591#else
1592 detected_double_format = unknown_format;
1593#endif
1594
1595#if SIZEOF_FLOAT == 4
1596 {
1597 float y = 16711938.0;
1598 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1599 detected_float_format = ieee_big_endian_format;
1600 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1601 detected_float_format = ieee_little_endian_format;
1602 else
1603 detected_float_format = unknown_format;
1604 }
1605#else
1606 detected_float_format = unknown_format;
1607#endif
1608
1609 double_format = detected_double_format;
1610 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001611
1612#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001613 /* Initialize floating point repr */
1614 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001615#endif
Christian Heimes796fc312008-01-30 18:58:29 +00001616 /* Init float info */
1617 if (FloatInfoType.tp_name == 0)
1618 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001619}
1620
1621void
Fred Drakefd99de62000-07-09 05:02:18 +00001622PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001623{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001624 PyFloatObject *p;
1625 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001626 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001627 int bc, bf; /* block count, number of freed blocks */
1628 int frem, fsum; /* remaining unfreed floats per block, total */
1629
1630 bc = 0;
1631 bf = 0;
1632 fsum = 0;
1633 list = block_list;
1634 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001635 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001636 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001637 bc++;
1638 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001639 for (i = 0, p = &list->objects[0];
1640 i < N_FLOATOBJECTS;
1641 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001642 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001643 frem++;
1644 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001645 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001646 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001647 list->next = block_list;
1648 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001649 for (i = 0, p = &list->objects[0];
1650 i < N_FLOATOBJECTS;
1651 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001652 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001653 Py_REFCNT(p) == 0) {
1654 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001655 free_list;
1656 free_list = p;
1657 }
1658 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001659 }
1660 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001661 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001662 bf++;
1663 }
1664 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001665 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001666 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001667 if (!Py_VerboseFlag)
1668 return;
1669 fprintf(stderr, "# cleanup floats");
1670 if (!fsum) {
1671 fprintf(stderr, "\n");
1672 }
1673 else {
1674 fprintf(stderr,
1675 ": %d unfreed float%s in %d out of %d block%s\n",
1676 fsum, fsum == 1 ? "" : "s",
1677 bc - bf, bc, bc == 1 ? "" : "s");
1678 }
1679 if (Py_VerboseFlag > 1) {
1680 list = block_list;
1681 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001682 for (i = 0, p = &list->objects[0];
1683 i < N_FLOATOBJECTS;
1684 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001685 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001686 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001687 char buf[100];
1688 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001689 /* XXX(twouters) cast refcount to
1690 long until %zd is universally
1691 available
1692 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001693 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001694 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001695 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001696 }
1697 }
1698 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001699 }
1700 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001701}
Tim Peters9905b942003-03-20 20:53:32 +00001702
1703/*----------------------------------------------------------------------------
1704 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1705 *
1706 * TODO: On platforms that use the standard IEEE-754 single and double
1707 * formats natively, these routines could simply copy the bytes.
1708 */
1709int
1710_PyFloat_Pack4(double x, unsigned char *p, int le)
1711{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712 if (float_format == unknown_format) {
1713 unsigned char sign;
1714 int e;
1715 double f;
1716 unsigned int fbits;
1717 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001718
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001719 if (le) {
1720 p += 3;
1721 incr = -1;
1722 }
Tim Peters9905b942003-03-20 20:53:32 +00001723
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001724 if (x < 0) {
1725 sign = 1;
1726 x = -x;
1727 }
1728 else
1729 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001730
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001731 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001732
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001733 /* Normalize f to be in the range [1.0, 2.0) */
1734 if (0.5 <= f && f < 1.0) {
1735 f *= 2.0;
1736 e--;
1737 }
1738 else if (f == 0.0)
1739 e = 0;
1740 else {
1741 PyErr_SetString(PyExc_SystemError,
1742 "frexp() result out of range");
1743 return -1;
1744 }
1745
1746 if (e >= 128)
1747 goto Overflow;
1748 else if (e < -126) {
1749 /* Gradual underflow */
1750 f = ldexp(f, 126 + e);
1751 e = 0;
1752 }
1753 else if (!(e == 0 && f == 0.0)) {
1754 e += 127;
1755 f -= 1.0; /* Get rid of leading 1 */
1756 }
1757
1758 f *= 8388608.0; /* 2**23 */
1759 fbits = (unsigned int)(f + 0.5); /* Round */
1760 assert(fbits <= 8388608);
1761 if (fbits >> 23) {
1762 /* The carry propagated out of a string of 23 1 bits. */
1763 fbits = 0;
1764 ++e;
1765 if (e >= 255)
1766 goto Overflow;
1767 }
1768
1769 /* First byte */
1770 *p = (sign << 7) | (e >> 1);
1771 p += incr;
1772
1773 /* Second byte */
1774 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1775 p += incr;
1776
1777 /* Third byte */
1778 *p = (fbits >> 8) & 0xFF;
1779 p += incr;
1780
1781 /* Fourth byte */
1782 *p = fbits & 0xFF;
1783
1784 /* Done */
1785 return 0;
1786
1787 Overflow:
1788 PyErr_SetString(PyExc_OverflowError,
1789 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001790 return -1;
1791 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001792 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001793 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001794 const char *s = (char*)&y;
1795 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001796
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001797 if ((float_format == ieee_little_endian_format && !le)
1798 || (float_format == ieee_big_endian_format && le)) {
1799 p += 3;
1800 incr = -1;
1801 }
1802
1803 for (i = 0; i < 4; i++) {
1804 *p = *s++;
1805 p += incr;
1806 }
1807 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001808 }
Tim Peters9905b942003-03-20 20:53:32 +00001809}
1810
1811int
1812_PyFloat_Pack8(double x, unsigned char *p, int le)
1813{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001814 if (double_format == unknown_format) {
1815 unsigned char sign;
1816 int e;
1817 double f;
1818 unsigned int fhi, flo;
1819 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001820
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001821 if (le) {
1822 p += 7;
1823 incr = -1;
1824 }
Tim Peters9905b942003-03-20 20:53:32 +00001825
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001826 if (x < 0) {
1827 sign = 1;
1828 x = -x;
1829 }
1830 else
1831 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001832
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001833 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001834
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001835 /* Normalize f to be in the range [1.0, 2.0) */
1836 if (0.5 <= f && f < 1.0) {
1837 f *= 2.0;
1838 e--;
1839 }
1840 else if (f == 0.0)
1841 e = 0;
1842 else {
1843 PyErr_SetString(PyExc_SystemError,
1844 "frexp() result out of range");
1845 return -1;
1846 }
1847
1848 if (e >= 1024)
1849 goto Overflow;
1850 else if (e < -1022) {
1851 /* Gradual underflow */
1852 f = ldexp(f, 1022 + e);
1853 e = 0;
1854 }
1855 else if (!(e == 0 && f == 0.0)) {
1856 e += 1023;
1857 f -= 1.0; /* Get rid of leading 1 */
1858 }
1859
1860 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1861 f *= 268435456.0; /* 2**28 */
1862 fhi = (unsigned int)f; /* Truncate */
1863 assert(fhi < 268435456);
1864
1865 f -= (double)fhi;
1866 f *= 16777216.0; /* 2**24 */
1867 flo = (unsigned int)(f + 0.5); /* Round */
1868 assert(flo <= 16777216);
1869 if (flo >> 24) {
1870 /* The carry propagated out of a string of 24 1 bits. */
1871 flo = 0;
1872 ++fhi;
1873 if (fhi >> 28) {
1874 /* And it also progagated out of the next 28 bits. */
1875 fhi = 0;
1876 ++e;
1877 if (e >= 2047)
1878 goto Overflow;
1879 }
1880 }
1881
1882 /* First byte */
1883 *p = (sign << 7) | (e >> 4);
1884 p += incr;
1885
1886 /* Second byte */
1887 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1888 p += incr;
1889
1890 /* Third byte */
1891 *p = (fhi >> 16) & 0xFF;
1892 p += incr;
1893
1894 /* Fourth byte */
1895 *p = (fhi >> 8) & 0xFF;
1896 p += incr;
1897
1898 /* Fifth byte */
1899 *p = fhi & 0xFF;
1900 p += incr;
1901
1902 /* Sixth byte */
1903 *p = (flo >> 16) & 0xFF;
1904 p += incr;
1905
1906 /* Seventh byte */
1907 *p = (flo >> 8) & 0xFF;
1908 p += incr;
1909
1910 /* Eighth byte */
1911 *p = flo & 0xFF;
1912 p += incr;
1913
1914 /* Done */
1915 return 0;
1916
1917 Overflow:
1918 PyErr_SetString(PyExc_OverflowError,
1919 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001920 return -1;
1921 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001922 else {
1923 const char *s = (char*)&x;
1924 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001925
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001926 if ((double_format == ieee_little_endian_format && !le)
1927 || (double_format == ieee_big_endian_format && le)) {
1928 p += 7;
1929 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001930 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001931
1932 for (i = 0; i < 8; i++) {
1933 *p = *s++;
1934 p += incr;
1935 }
1936 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001937 }
Tim Peters9905b942003-03-20 20:53:32 +00001938}
1939
1940double
1941_PyFloat_Unpack4(const unsigned char *p, int le)
1942{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943 if (float_format == unknown_format) {
1944 unsigned char sign;
1945 int e;
1946 unsigned int f;
1947 double x;
1948 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001949
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001950 if (le) {
1951 p += 3;
1952 incr = -1;
1953 }
1954
1955 /* First byte */
1956 sign = (*p >> 7) & 1;
1957 e = (*p & 0x7F) << 1;
1958 p += incr;
1959
1960 /* Second byte */
1961 e |= (*p >> 7) & 1;
1962 f = (*p & 0x7F) << 16;
1963 p += incr;
1964
1965 if (e == 255) {
1966 PyErr_SetString(
1967 PyExc_ValueError,
1968 "can't unpack IEEE 754 special value "
1969 "on non-IEEE platform");
1970 return -1;
1971 }
1972
1973 /* Third byte */
1974 f |= *p << 8;
1975 p += incr;
1976
1977 /* Fourth byte */
1978 f |= *p;
1979
1980 x = (double)f / 8388608.0;
1981
1982 /* XXX This sadly ignores Inf/NaN issues */
1983 if (e == 0)
1984 e = -126;
1985 else {
1986 x += 1.0;
1987 e -= 127;
1988 }
1989 x = ldexp(x, e);
1990
1991 if (sign)
1992 x = -x;
1993
1994 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001995 }
Tim Peters9905b942003-03-20 20:53:32 +00001996 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001997 float x;
1998
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001999 if ((float_format == ieee_little_endian_format && !le)
2000 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002001 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002002 char *d = &buf[3];
2003 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002004
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002005 for (i = 0; i < 4; i++) {
2006 *d-- = *p++;
2007 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002008 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002009 }
2010 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002011 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002013
2014 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002015 }
Tim Peters9905b942003-03-20 20:53:32 +00002016}
2017
2018double
2019_PyFloat_Unpack8(const unsigned char *p, int le)
2020{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002021 if (double_format == unknown_format) {
2022 unsigned char sign;
2023 int e;
2024 unsigned int fhi, flo;
2025 double x;
2026 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002027
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002028 if (le) {
2029 p += 7;
2030 incr = -1;
2031 }
2032
2033 /* First byte */
2034 sign = (*p >> 7) & 1;
2035 e = (*p & 0x7F) << 4;
2036
2037 p += incr;
2038
2039 /* Second byte */
2040 e |= (*p >> 4) & 0xF;
2041 fhi = (*p & 0xF) << 24;
2042 p += incr;
2043
2044 if (e == 2047) {
2045 PyErr_SetString(
2046 PyExc_ValueError,
2047 "can't unpack IEEE 754 special value "
2048 "on non-IEEE platform");
2049 return -1.0;
2050 }
2051
2052 /* Third byte */
2053 fhi |= *p << 16;
2054 p += incr;
2055
2056 /* Fourth byte */
2057 fhi |= *p << 8;
2058 p += incr;
2059
2060 /* Fifth byte */
2061 fhi |= *p;
2062 p += incr;
2063
2064 /* Sixth byte */
2065 flo = *p << 16;
2066 p += incr;
2067
2068 /* Seventh byte */
2069 flo |= *p << 8;
2070 p += incr;
2071
2072 /* Eighth byte */
2073 flo |= *p;
2074
2075 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2076 x /= 268435456.0; /* 2**28 */
2077
2078 if (e == 0)
2079 e = -1022;
2080 else {
2081 x += 1.0;
2082 e -= 1023;
2083 }
2084 x = ldexp(x, e);
2085
2086 if (sign)
2087 x = -x;
2088
2089 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002090 }
Tim Peters9905b942003-03-20 20:53:32 +00002091 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002092 double x;
2093
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002094 if ((double_format == ieee_little_endian_format && !le)
2095 || (double_format == ieee_big_endian_format && le)) {
2096 char buf[8];
2097 char *d = &buf[7];
2098 int i;
2099
2100 for (i = 0; i < 8; i++) {
2101 *d-- = *p++;
2102 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002103 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002104 }
2105 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002106 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002108
2109 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002110 }
Tim Peters9905b942003-03-20 20:53:32 +00002111}