blob: 382b991bdfb419804fef4e102960df2eb65fcf41 [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
Mark Dickinson7103aa42008-07-15 19:08:33 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000018#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
Neal Norwitz5f95a792008-01-25 08:04:16 +000022#ifdef _OSF_SOURCE
23/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
24extern int finite(double);
25#endif
26
Guido van Rossum93ad0df1997-05-13 21:00:42 +000027/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000028#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000029#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000030#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000031
Guido van Rossum3fce8831999-03-12 19:43:17 +000032struct _floatblock {
33 struct _floatblock *next;
34 PyFloatObject objects[N_FLOATOBJECTS];
35};
36
37typedef struct _floatblock PyFloatBlock;
38
39static PyFloatBlock *block_list = NULL;
40static PyFloatObject *free_list = NULL;
41
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000043fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044{
45 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
47 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000048 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000049 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000050 ((PyFloatBlock *)p)->next = block_list;
51 block_list = (PyFloatBlock *)p;
52 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053 q = p + N_FLOATOBJECTS;
54 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000055 Py_TYPE(q) = (struct _typeobject *)(q-1);
56 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000057 return p + N_FLOATOBJECTS - 1;
58}
59
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060double
61PyFloat_GetMax(void)
62{
63 return DBL_MAX;
64}
65
66double
67PyFloat_GetMin(void)
68{
69 return DBL_MIN;
70}
71
Christian Heimes796fc312008-01-30 18:58:29 +000072static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000073
74PyDoc_STRVAR(floatinfo__doc__,
75"sys.floatinfo\n\
76\n\
77A structseq holding information about the float type. It contains low level\n\
78information about the precision and internal representation. Please study\n\
79your system's :file:`float.h` for more information.");
80
81static PyStructSequence_Field floatinfo_fields[] = {
82 {"max", "DBL_MAX -- maximum representable finite float"},
83 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
84 "is representable"},
85 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
86 "is representable"},
87 {"min", "DBL_MIN -- Minimum positive normalizer float"},
88 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
89 "is a normalized float"},
90 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
91 "a normalized"},
92 {"dig", "DBL_DIG -- digits"},
93 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
94 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
95 "representable float"},
96 {"radix", "FLT_RADIX -- radix of exponent"},
97 {"rounds", "FLT_ROUNDS -- addition rounds"},
98 {0}
99};
100
101static PyStructSequence_Desc floatinfo_desc = {
102 "sys.floatinfo", /* name */
103 floatinfo__doc__, /* doc */
104 floatinfo_fields, /* fields */
105 11
106};
107
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108PyObject *
109PyFloat_GetInfo(void)
110{
Christian Heimes796fc312008-01-30 18:58:29 +0000111 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000112 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114 floatinfo = PyStructSequence_New(&FloatInfoType);
115 if (floatinfo == NULL) {
116 return NULL;
117 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Christian Heimesc94e2b52008-01-14 04:13:37 +0000119#define SetIntFlag(flag) \
120 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
121#define SetDblFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000123
Christian Heimesc94e2b52008-01-14 04:13:37 +0000124 SetDblFlag(DBL_MAX);
125 SetIntFlag(DBL_MAX_EXP);
126 SetIntFlag(DBL_MAX_10_EXP);
127 SetDblFlag(DBL_MIN);
128 SetIntFlag(DBL_MIN_EXP);
129 SetIntFlag(DBL_MIN_10_EXP);
130 SetIntFlag(DBL_DIG);
131 SetIntFlag(DBL_MANT_DIG);
132 SetDblFlag(DBL_EPSILON);
133 SetIntFlag(FLT_RADIX);
134 SetIntFlag(FLT_ROUNDS);
135#undef SetIntFlag
136#undef SetDblFlag
137
138 if (PyErr_Occurred()) {
139 Py_CLEAR(floatinfo);
140 return NULL;
141 }
Christian Heimesc94e2b52008-01-14 04:13:37 +0000142 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000148 register PyFloatObject *op;
149 if (free_list == NULL) {
150 if ((free_list = fill_free_list()) == NULL)
151 return NULL;
152 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000153 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000154 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000155 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Tim Petersef14d732000-09-23 03:39:17 +0000161/**************************************************************************
162RED_FLAG 22-Sep-2000 tim
163PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
164
1651. If v was a regular string, *pend was set to point to its terminating
166 null byte. That's useless (the caller can find that without any
167 help from this function!).
168
1692. If v was a Unicode string, or an object convertible to a character
170 buffer, *pend was set to point into stack trash (the auto temp
171 vector holding the character buffer). That was downright dangerous.
172
173Since we can't change the interface of a public API function, pend is
174still supported but now *officially* useless: if pend is not NULL,
175*pend is set to NULL.
176**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000177PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000178PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000180 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000182 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000183#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000184 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000185#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000187
Tim Petersef14d732000-09-23 03:39:17 +0000188 if (pend)
189 *pend = NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000190 if (PyString_Check(v)) {
191 s = PyString_AS_STRING(v);
192 len = PyString_GET_SIZE(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000194#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000195 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000196 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000198 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 return NULL;
200 }
Tim Petersef14d732000-09-23 03:39:17 +0000201 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000202 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000203 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 NULL))
205 return NULL;
206 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000207 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000208 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000210 else if (PyObject_AsCharBuffer(v, &s, &len)) {
211 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000212 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000213 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215
Guido van Rossum4c08d552000-03-10 22:55:18 +0000216 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 while (*s && isspace(Py_CHARMASK(*s)))
218 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000219 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000220 PyErr_SetString(PyExc_ValueError, "empty string for float()");
221 return NULL;
222 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000223 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000224 /* We don't care about overflow or underflow. If the platform supports
225 * them, infinities and signed zeroes (on underflow) are fine.
226 * However, strtod can return 0 for denormalized numbers, where atof
227 * does not. So (alas!) we special-case a zero result. Note that
228 * whether strtod sets errno on underflow is not defined, so we can't
229 * key off errno.
230 */
Tim Peters858346e2000-09-25 21:01:28 +0000231 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000232 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000233 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000234 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000235 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000236 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237 if (end > last)
238 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000239 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000240 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000241 char *p = (char*)sp;
242 int sign = 1;
243
244 if (*p == '-') {
245 sign = -1;
246 p++;
247 }
248 if (*p == '+') {
249 p++;
250 }
251 if (PyOS_strnicmp(p, "inf", 4) == 0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000252 Py_RETURN_INF(sign);
Christian Heimes0a8143f2007-12-18 23:22:54 +0000253 }
Mark Dickinsonbf9f4d82008-07-05 11:33:52 +0000254 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
255 Py_RETURN_INF(sign);
256 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000257#ifdef Py_NAN
258 if(PyOS_strnicmp(p, "nan", 4) == 0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000259 Py_RETURN_NAN;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000260 }
261#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000262 PyOS_snprintf(buffer, sizeof(buffer),
263 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000264 PyErr_SetString(PyExc_ValueError, buffer);
265 return NULL;
266 }
267 /* Since end != s, the platform made *some* kind of sense out
268 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000269 while (*end && isspace(Py_CHARMASK(*end)))
270 end++;
271 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000272 PyOS_snprintf(buffer, sizeof(buffer),
273 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000274 PyErr_SetString(PyExc_ValueError, buffer);
275 return NULL;
276 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000277 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000278 PyErr_SetString(PyExc_ValueError,
279 "null byte in argument for float()");
280 return NULL;
281 }
Tim Petersef14d732000-09-23 03:39:17 +0000282 if (x == 0.0) {
283 /* See above -- may have been strtod being anal
284 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000285 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000286 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000287 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000288 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000289 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000290 return PyFloat_FromDouble(x);
291}
292
Guido van Rossum234f9421993-06-17 12:35:49 +0000293static void
Fred Drakefd99de62000-07-09 05:02:18 +0000294float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000295{
Guido van Rossum9475a232001-10-05 20:51:39 +0000296 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000297 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000298 free_list = op;
299 }
300 else
Christian Heimese93237d2007-12-19 02:37:44 +0000301 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000302}
303
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304double
Fred Drakefd99de62000-07-09 05:02:18 +0000305PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 PyNumberMethods *nb;
308 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311 if (op && PyFloat_Check(op))
312 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000313
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000314 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316 return -1;
317 }
Tim Petersd2364e82001-11-01 20:09:42 +0000318
Christian Heimese93237d2007-12-19 02:37:44 +0000319 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000320 PyErr_SetString(PyExc_TypeError, "a float is required");
321 return -1;
322 }
323
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000325 if (fo == NULL)
326 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 if (!PyFloat_Check(fo)) {
328 PyErr_SetString(PyExc_TypeError,
329 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000330 return -1;
331 }
Tim Petersd2364e82001-11-01 20:09:42 +0000332
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333 val = PyFloat_AS_DOUBLE(fo);
334 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000335
Guido van Rossumb6775db1994-08-01 11:34:53 +0000336 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337}
338
339/* Methods */
340
Tim Peters97019e42001-11-28 22:43:45 +0000341static void
342format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
344 register char *cp;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000345 int i;
346
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 /* Subroutine for float_repr and float_print.
348 We want float numbers to be recognizable as such,
349 i.e., they should contain a decimal point or an exponent.
350 However, %g may print the number as an integer;
351 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000352
353 assert(PyFloat_Check(v));
Eric Smith068f0652009-04-25 21:40:15 +0000354 _PyOS_double_to_string(buf, buflen, v->ob_fval, 'g', precision,
355 0, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356 cp = buf;
357 if (*cp == '-')
358 cp++;
359 for (; *cp != '\0'; cp++) {
360 /* Any non-digit means it's not an integer;
361 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000362 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363 break;
364 }
365 if (*cp == '\0') {
366 *cp++ = '.';
367 *cp++ = '0';
368 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000369 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000371 /* Checking the next three chars should be more than enough to
372 * detect inf or nan, even on Windows. We check for inf or nan
373 * at last because they are rare cases.
374 */
375 for (i=0; *cp != '\0' && i<3; cp++, i++) {
376 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
377 continue;
378 /* found something that is neither a digit nor point
379 * it might be a NaN or INF
380 */
381#ifdef Py_NAN
382 if (Py_IS_NAN(v->ob_fval)) {
383 strcpy(buf, "nan");
384 }
385 else
386#endif
387 if (Py_IS_INFINITY(v->ob_fval)) {
388 cp = buf;
389 if (*cp == '-')
390 cp++;
391 strcpy(cp, "inf");
392 }
393 break;
394 }
395
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Tim Peters97019e42001-11-28 22:43:45 +0000398/* XXX PyFloat_AsStringEx should not be a public API function (for one
399 XXX thing, its signature passes a buffer without a length; for another,
400 XXX it isn't useful outside this file).
401*/
402void
403PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
404{
405 format_float(buf, 100, v, precision);
406}
407
Neil Schemenauer32117e52001-01-04 01:44:34 +0000408/* Macro and helper that convert PyObject obj to a C double and store
409 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000410 slot function. If conversion to double raises an exception, obj is
411 set to NULL, and the function invoking this macro returns NULL. If
412 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
413 stored in obj, and returned from the function invoking this macro.
414*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000415#define CONVERT_TO_DOUBLE(obj, dbl) \
416 if (PyFloat_Check(obj)) \
417 dbl = PyFloat_AS_DOUBLE(obj); \
418 else if (convert_to_double(&(obj), &(dbl)) < 0) \
419 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000420
421static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000422convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000423{
424 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000425
Neil Schemenauer32117e52001-01-04 01:44:34 +0000426 if (PyInt_Check(obj)) {
427 *dbl = (double)PyInt_AS_LONG(obj);
428 }
429 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000430 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000431 if (*dbl == -1.0 && PyErr_Occurred()) {
432 *v = NULL;
433 return -1;
434 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000435 }
436 else {
437 Py_INCREF(Py_NotImplemented);
438 *v = Py_NotImplemented;
439 return -1;
440 }
441 return 0;
442}
443
Guido van Rossum57072eb1999-12-23 19:00:28 +0000444/* Precisions used by repr() and str(), respectively.
445
446 The repr() precision (17 significant decimal digits) is the minimal number
447 that is guaranteed to have enough precision so that if the number is read
448 back in the exact same binary value is recreated. This is true for IEEE
449 floating point by design, and also happens to work for all other modern
450 hardware.
451
452 The str() precision is chosen so that in most cases, the rounding noise
453 created by various operations is suppressed, while giving plenty of
454 precision for practical use.
455
456*/
457
458#define PREC_REPR 17
459#define PREC_STR 12
460
Tim Peters97019e42001-11-28 22:43:45 +0000461/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
462 XXX they pass a char buffer without passing a length.
463*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000464void
Fred Drakefd99de62000-07-09 05:02:18 +0000465PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000466{
Tim Peters97019e42001-11-28 22:43:45 +0000467 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000468}
469
Tim Peters72f98e92001-05-08 15:19:57 +0000470void
471PyFloat_AsReprString(char *buf, PyFloatObject *v)
472{
Tim Peters97019e42001-11-28 22:43:45 +0000473 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000474}
475
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000476/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000477static int
Fred Drakefd99de62000-07-09 05:02:18 +0000478float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000479{
480 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000481 format_float(buf, sizeof(buf), v,
482 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000483 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000485 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000486 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487}
488
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000490float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000491{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000492 char buf[100];
493 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000494
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000495 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000496}
497
498static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000499float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000500{
501 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000502 format_float(buf, sizeof(buf), v, PREC_STR);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000503 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000504}
505
Tim Peters307fa782004-09-23 08:06:40 +0000506/* Comparison is pretty much a nightmare. When comparing float to float,
507 * we do it as straightforwardly (and long-windedly) as conceivable, so
508 * that, e.g., Python x == y delivers the same result as the platform
509 * C x == y when x and/or y is a NaN.
510 * When mixing float with an integer type, there's no good *uniform* approach.
511 * Converting the double to an integer obviously doesn't work, since we
512 * may lose info from fractional bits. Converting the integer to a double
513 * also has two failure modes: (1) a long int may trigger overflow (too
514 * large to fit in the dynamic range of a C double); (2) even a C long may have
515 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
516 * 63 bits of precision, but a C double probably has only 53), and then
517 * we can falsely claim equality when low-order integer bits are lost by
518 * coercion to double. So this part is painful too.
519 */
520
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000521static PyObject*
522float_richcompare(PyObject *v, PyObject *w, int op)
523{
524 double i, j;
525 int r = 0;
526
Tim Peters307fa782004-09-23 08:06:40 +0000527 assert(PyFloat_Check(v));
528 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000529
Tim Peters307fa782004-09-23 08:06:40 +0000530 /* Switch on the type of w. Set i and j to doubles to be compared,
531 * and op to the richcomp to use.
532 */
533 if (PyFloat_Check(w))
534 j = PyFloat_AS_DOUBLE(w);
535
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000536 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000537 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000538 /* If i is an infinity, its magnitude exceeds any
539 * finite integer, so it doesn't matter which int we
540 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000541 */
542 j = 0.0;
543 else
544 goto Unimplemented;
545 }
546
547 else if (PyInt_Check(w)) {
548 long jj = PyInt_AS_LONG(w);
549 /* In the worst realistic case I can imagine, C double is a
550 * Cray single with 48 bits of precision, and long has 64
551 * bits.
552 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000553#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000554 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
555 if (abs >> 48) {
556 /* Needs more than 48 bits. Make it take the
557 * PyLong path.
558 */
559 PyObject *result;
560 PyObject *ww = PyLong_FromLong(jj);
561
562 if (ww == NULL)
563 return NULL;
564 result = float_richcompare(v, ww, op);
565 Py_DECREF(ww);
566 return result;
567 }
568#endif
569 j = (double)jj;
570 assert((long)j == jj);
571 }
572
573 else if (PyLong_Check(w)) {
574 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
575 int wsign = _PyLong_Sign(w);
576 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000577 int exponent;
578
579 if (vsign != wsign) {
580 /* Magnitudes are irrelevant -- the signs alone
581 * determine the outcome.
582 */
583 i = (double)vsign;
584 j = (double)wsign;
585 goto Compare;
586 }
587 /* The signs are the same. */
588 /* Convert w to a double if it fits. In particular, 0 fits. */
589 nbits = _PyLong_NumBits(w);
590 if (nbits == (size_t)-1 && PyErr_Occurred()) {
591 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000592 * to hold the # of bits. Replace with little doubles
593 * that give the same outcome -- w is so large that
594 * its magnitude must exceed the magnitude of any
595 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000596 */
597 PyErr_Clear();
598 i = (double)vsign;
599 assert(wsign != 0);
600 j = wsign * 2.0;
601 goto Compare;
602 }
603 if (nbits <= 48) {
604 j = PyLong_AsDouble(w);
605 /* It's impossible that <= 48 bits overflowed. */
606 assert(j != -1.0 || ! PyErr_Occurred());
607 goto Compare;
608 }
609 assert(wsign != 0); /* else nbits was 0 */
610 assert(vsign != 0); /* if vsign were 0, then since wsign is
611 * not 0, we would have taken the
612 * vsign != wsign branch at the start */
613 /* We want to work with non-negative numbers. */
614 if (vsign < 0) {
615 /* "Multiply both sides" by -1; this also swaps the
616 * comparator.
617 */
618 i = -i;
619 op = _Py_SwappedOp[op];
620 }
621 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000622 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000623 /* exponent is the # of bits in v before the radix point;
624 * we know that nbits (the # of bits in w) > 48 at this point
625 */
626 if (exponent < 0 || (size_t)exponent < nbits) {
627 i = 1.0;
628 j = 2.0;
629 goto Compare;
630 }
631 if ((size_t)exponent > nbits) {
632 i = 2.0;
633 j = 1.0;
634 goto Compare;
635 }
636 /* v and w have the same number of bits before the radix
637 * point. Construct two longs that have the same comparison
638 * outcome.
639 */
640 {
641 double fracpart;
642 double intpart;
643 PyObject *result = NULL;
644 PyObject *one = NULL;
645 PyObject *vv = NULL;
646 PyObject *ww = w;
647
648 if (wsign < 0) {
649 ww = PyNumber_Negative(w);
650 if (ww == NULL)
651 goto Error;
652 }
653 else
654 Py_INCREF(ww);
655
656 fracpart = modf(i, &intpart);
657 vv = PyLong_FromDouble(intpart);
658 if (vv == NULL)
659 goto Error;
660
661 if (fracpart != 0.0) {
662 /* Shift left, and or a 1 bit into vv
663 * to represent the lost fraction.
664 */
665 PyObject *temp;
666
667 one = PyInt_FromLong(1);
668 if (one == NULL)
669 goto Error;
670
671 temp = PyNumber_Lshift(ww, one);
672 if (temp == NULL)
673 goto Error;
674 Py_DECREF(ww);
675 ww = temp;
676
677 temp = PyNumber_Lshift(vv, one);
678 if (temp == NULL)
679 goto Error;
680 Py_DECREF(vv);
681 vv = temp;
682
683 temp = PyNumber_Or(vv, one);
684 if (temp == NULL)
685 goto Error;
686 Py_DECREF(vv);
687 vv = temp;
688 }
689
690 r = PyObject_RichCompareBool(vv, ww, op);
691 if (r < 0)
692 goto Error;
693 result = PyBool_FromLong(r);
694 Error:
695 Py_XDECREF(vv);
696 Py_XDECREF(ww);
697 Py_XDECREF(one);
698 return result;
699 }
700 } /* else if (PyLong_Check(w)) */
701
702 else /* w isn't float, int, or long */
703 goto Unimplemented;
704
705 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000706 PyFPE_START_PROTECT("richcompare", return NULL)
707 switch (op) {
708 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000709 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000710 break;
711 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000712 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000713 break;
714 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000715 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000716 break;
717 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000718 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000719 break;
720 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000721 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000722 break;
723 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000724 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000725 break;
726 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000727 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000728 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000729
730 Unimplemented:
731 Py_INCREF(Py_NotImplemented);
732 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000733}
734
Guido van Rossum9bfef441993-03-29 10:43:31 +0000735static long
Fred Drakefd99de62000-07-09 05:02:18 +0000736float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000737{
Tim Peters39dce292000-08-15 03:34:48 +0000738 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000739}
740
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000742float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000743{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000744 double a,b;
745 CONVERT_TO_DOUBLE(v, a);
746 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000747 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000748 a = a + b;
749 PyFPE_END_PROTECT(a)
750 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751}
752
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000753static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000754float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000756 double a,b;
757 CONVERT_TO_DOUBLE(v, a);
758 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000759 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000760 a = a - b;
761 PyFPE_END_PROTECT(a)
762 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763}
764
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000766float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000768 double a,b;
769 CONVERT_TO_DOUBLE(v, a);
770 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000771 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000772 a = a * b;
773 PyFPE_END_PROTECT(a)
774 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775}
776
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000777static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000778float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000780 double a,b;
781 CONVERT_TO_DOUBLE(v, a);
782 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000783#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000784 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000785 PyErr_SetString(PyExc_ZeroDivisionError,
786 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787 return NULL;
788 }
Christian Heimes6f341092008-04-18 23:13:07 +0000789#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000790 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000791 a = a / b;
792 PyFPE_END_PROTECT(a)
793 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000794}
795
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000797float_classic_div(PyObject *v, PyObject *w)
798{
799 double a,b;
800 CONVERT_TO_DOUBLE(v, a);
801 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000802 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000803 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
804 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000805#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000806 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000807 PyErr_SetString(PyExc_ZeroDivisionError,
808 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000809 return NULL;
810 }
Christian Heimes6f341092008-04-18 23:13:07 +0000811#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000812 PyFPE_START_PROTECT("divide", return 0)
813 a = a / b;
814 PyFPE_END_PROTECT(a)
815 return PyFloat_FromDouble(a);
816}
817
818static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000819float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000821 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000822 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000823 CONVERT_TO_DOUBLE(v, vx);
824 CONVERT_TO_DOUBLE(w, wx);
825#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000826 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000827 PyErr_SetString(PyExc_ZeroDivisionError,
828 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000829 return NULL;
830 }
Christian Heimes6f341092008-04-18 23:13:07 +0000831#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000832 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000833 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000834 /* note: checking mod*wx < 0 is incorrect -- underflows to
835 0 if wx < sqrt(smallest nonzero double) */
836 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000837 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000838 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000839 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000841}
842
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000844float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000845{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000846 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000847 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000848 CONVERT_TO_DOUBLE(v, vx);
849 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000850 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000851 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000852 return NULL;
853 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000854 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000855 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000856 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000857 exact multiple of wx. But this is fp arithmetic, and fp
858 vx - mod is an approximation; the result is that div may
859 not be an exact integral value after the division, although
860 it will always be very close to one.
861 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000862 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000863 if (mod) {
864 /* ensure the remainder has the same sign as the denominator */
865 if ((wx < 0) != (mod < 0)) {
866 mod += wx;
867 div -= 1.0;
868 }
869 }
870 else {
871 /* the remainder is zero, and in the presence of signed zeroes
872 fmod returns different results across platforms; ensure
873 it has the same sign as the denominator; we'd like to do
874 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000875 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000876 if (wx < 0.0)
877 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000878 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000879 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000880 if (div) {
881 floordiv = floor(div);
882 if (div - floordiv > 0.5)
883 floordiv += 1.0;
884 }
885 else {
886 /* div is zero - get the same sign as the true quotient */
887 div *= div; /* hide "div = +0" from optimizers */
888 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
889 }
890 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000891 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000892}
893
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000894static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000895float_floor_div(PyObject *v, PyObject *w)
896{
897 PyObject *t, *r;
898
899 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000900 if (t == NULL || t == Py_NotImplemented)
901 return t;
902 assert(PyTuple_CheckExact(t));
903 r = PyTuple_GET_ITEM(t, 0);
904 Py_INCREF(r);
905 Py_DECREF(t);
906 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000907}
908
909static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000910float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000911{
912 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000913
914 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000915 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000916 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000917 return NULL;
918 }
919
Neil Schemenauer32117e52001-01-04 01:44:34 +0000920 CONVERT_TO_DOUBLE(v, iv);
921 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000922
923 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000924 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000925 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000926 }
Tim Peters96685bf2001-08-23 22:31:37 +0000927 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000928 if (iw < 0.0) {
929 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000930 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000931 return NULL;
932 }
933 return PyFloat_FromDouble(0.0);
934 }
Christian Heimes6f341092008-04-18 23:13:07 +0000935 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
936 return PyFloat_FromDouble(1.0);
937 }
Tim Peterse87568d2003-05-24 20:18:24 +0000938 if (iv < 0.0) {
939 /* Whether this is an error is a mess, and bumps into libm
940 * bugs so we have to figure it out ourselves.
941 */
942 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000943 PyErr_SetString(PyExc_ValueError, "negative number "
944 "cannot be raised to a fractional power");
945 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000946 }
947 /* iw is an exact integer, albeit perhaps a very large one.
948 * -1 raised to an exact integer should never be exceptional.
949 * Alas, some libms (chiefly glibc as of early 2003) return
950 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
951 * happen to be representable in a *C* integer. That's a
952 * bug; we let that slide in math.pow() (which currently
953 * reflects all platform accidents), but not for Python's **.
954 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000955 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000956 /* Return 1 if iw is even, -1 if iw is odd; there's
957 * no guarantee that any C integral type is big
958 * enough to hold iw, so we have to check this
959 * indirectly.
960 */
961 ix = floor(iw * 0.5) * 2.0;
962 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
963 }
964 /* Else iv != -1.0, and overflow or underflow are possible.
965 * Unless we're to write pow() ourselves, we have to trust
966 * the platform to do this correctly.
967 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000968 }
Tim Peters96685bf2001-08-23 22:31:37 +0000969 errno = 0;
970 PyFPE_START_PROTECT("pow", return NULL)
971 ix = pow(iv, iw);
972 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000973 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000974 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000975 /* We don't expect any errno value other than ERANGE, but
976 * the range of libm bugs appears unbounded.
977 */
Alex Martelli348dc882006-08-23 22:17:59 +0000978 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
979 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000980 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000981 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000982 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000983}
984
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000985static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000986float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000987{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000988 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000989}
990
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000991static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000992float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000993{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000994 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000995}
996
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000997static int
Fred Drakefd99de62000-07-09 05:02:18 +0000998float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000999{
1000 return v->ob_fval != 0.0;
1001}
1002
Guido van Rossum234f9421993-06-17 12:35:49 +00001003static int
Fred Drakefd99de62000-07-09 05:02:18 +00001004float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001005{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006 if (PyInt_Check(*pw)) {
1007 long x = PyInt_AsLong(*pw);
1008 *pw = PyFloat_FromDouble((double)x);
1009 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001010 return 0;
1011 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001012 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001013 double x = PyLong_AsDouble(*pw);
1014 if (x == -1.0 && PyErr_Occurred())
1015 return -1;
1016 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001017 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001018 return 0;
1019 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001020 else if (PyFloat_Check(*pw)) {
1021 Py_INCREF(*pv);
1022 Py_INCREF(*pw);
1023 return 0;
1024 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001025 return 1; /* Can't do it */
1026}
1027
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +00001029float_is_integer(PyObject *v)
1030{
1031 double x = PyFloat_AsDouble(v);
1032 PyObject *o;
1033
1034 if (x == -1.0 && PyErr_Occurred())
1035 return NULL;
1036 if (!Py_IS_FINITE(x))
1037 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +00001038 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +00001039 PyFPE_START_PROTECT("is_integer", return NULL)
1040 o = (floor(x) == x) ? Py_True : Py_False;
1041 PyFPE_END_PROTECT(x)
1042 if (errno != 0) {
1043 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1044 PyExc_ValueError);
1045 return NULL;
1046 }
1047 Py_INCREF(o);
1048 return o;
1049}
1050
1051#if 0
1052static PyObject *
1053float_is_inf(PyObject *v)
1054{
1055 double x = PyFloat_AsDouble(v);
1056 if (x == -1.0 && PyErr_Occurred())
1057 return NULL;
1058 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1059}
1060
1061static PyObject *
1062float_is_nan(PyObject *v)
1063{
1064 double x = PyFloat_AsDouble(v);
1065 if (x == -1.0 && PyErr_Occurred())
1066 return NULL;
1067 return PyBool_FromLong((long)Py_IS_NAN(x));
1068}
1069
1070static PyObject *
1071float_is_finite(PyObject *v)
1072{
1073 double x = PyFloat_AsDouble(v);
1074 if (x == -1.0 && PyErr_Occurred())
1075 return NULL;
1076 return PyBool_FromLong((long)Py_IS_FINITE(x));
1077}
1078#endif
1079
1080static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001081float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001082{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001083 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001084 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001085
1086 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001087 /* Try to get out cheap if this fits in a Python int. The attempt
1088 * to cast to long must be protected, as C doesn't define what
1089 * happens if the double is too big to fit in a long. Some rare
1090 * systems raise an exception then (RISCOS was mentioned as one,
1091 * and someone using a non-default option on Sun also bumped into
1092 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1093 * still be vulnerable: if a long has more bits of precision than
1094 * a double, casting MIN/MAX to double may yield an approximation,
1095 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1096 * yield true from the C expression wholepart<=LONG_MAX, despite
1097 * that wholepart is actually greater than LONG_MAX.
1098 */
1099 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1100 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001101 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001102 }
1103 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001104}
1105
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001106static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001107float_long(PyObject *v)
1108{
1109 double x = PyFloat_AsDouble(v);
1110 return PyLong_FromDouble(x);
1111}
1112
1113static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001114float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001115{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001116 if (PyFloat_CheckExact(v))
1117 Py_INCREF(v);
1118 else
1119 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001120 return v;
1121}
1122
Mark Dickinson7103aa42008-07-15 19:08:33 +00001123/* turn ASCII hex characters into integer values and vice versa */
1124
1125static char
1126char_from_hex(int x)
1127{
1128 assert(0 <= x && x < 16);
1129 return "0123456789abcdef"[x];
1130}
1131
1132static int
1133hex_from_char(char c) {
1134 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001135 switch(c) {
1136 case '0':
1137 x = 0;
1138 break;
1139 case '1':
1140 x = 1;
1141 break;
1142 case '2':
1143 x = 2;
1144 break;
1145 case '3':
1146 x = 3;
1147 break;
1148 case '4':
1149 x = 4;
1150 break;
1151 case '5':
1152 x = 5;
1153 break;
1154 case '6':
1155 x = 6;
1156 break;
1157 case '7':
1158 x = 7;
1159 break;
1160 case '8':
1161 x = 8;
1162 break;
1163 case '9':
1164 x = 9;
1165 break;
1166 case 'a':
1167 case 'A':
1168 x = 10;
1169 break;
1170 case 'b':
1171 case 'B':
1172 x = 11;
1173 break;
1174 case 'c':
1175 case 'C':
1176 x = 12;
1177 break;
1178 case 'd':
1179 case 'D':
1180 x = 13;
1181 break;
1182 case 'e':
1183 case 'E':
1184 x = 14;
1185 break;
1186 case 'f':
1187 case 'F':
1188 x = 15;
1189 break;
1190 default:
1191 x = -1;
1192 break;
1193 }
1194 return x;
1195}
1196
1197/* convert a float to a hexadecimal string */
1198
1199/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1200 of the form 4k+1. */
1201#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1202
1203static PyObject *
1204float_hex(PyObject *v)
1205{
1206 double x, m;
1207 int e, shift, i, si, esign;
1208 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1209 trailing NUL byte. */
1210 char s[(TOHEX_NBITS-1)/4+3];
1211
1212 CONVERT_TO_DOUBLE(v, x);
1213
1214 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1215 return float_str((PyFloatObject *)v);
1216
1217 if (x == 0.0) {
1218 if(copysign(1.0, x) == -1.0)
1219 return PyString_FromString("-0x0.0p+0");
1220 else
1221 return PyString_FromString("0x0.0p+0");
1222 }
1223
1224 m = frexp(fabs(x), &e);
1225 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1226 m = ldexp(m, shift);
1227 e -= shift;
1228
1229 si = 0;
1230 s[si] = char_from_hex((int)m);
1231 si++;
1232 m -= (int)m;
1233 s[si] = '.';
1234 si++;
1235 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1236 m *= 16.0;
1237 s[si] = char_from_hex((int)m);
1238 si++;
1239 m -= (int)m;
1240 }
1241 s[si] = '\0';
1242
1243 if (e < 0) {
1244 esign = (int)'-';
1245 e = -e;
1246 }
1247 else
1248 esign = (int)'+';
1249
1250 if (x < 0.0)
1251 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1252 else
1253 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1254}
1255
1256PyDoc_STRVAR(float_hex_doc,
1257"float.hex() -> string\n\
1258\n\
1259Return a hexadecimal representation of a floating-point number.\n\
1260>>> (-0.1).hex()\n\
1261'-0x1.999999999999ap-4'\n\
1262>>> 3.14159.hex()\n\
1263'0x1.921f9f01b866ep+1'");
1264
1265/* Convert a hexadecimal string to a float. */
1266
1267static PyObject *
1268float_fromhex(PyObject *cls, PyObject *arg)
1269{
1270 PyObject *result_as_float, *result;
1271 double x;
1272 long exp, top_exp, lsb, key_digit;
1273 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1274 int half_eps, digit, round_up, sign=1;
1275 Py_ssize_t length, ndigits, fdigits, i;
1276
1277 /*
1278 * For the sake of simplicity and correctness, we impose an artificial
1279 * limit on ndigits, the total number of hex digits in the coefficient
1280 * The limit is chosen to ensure that, writing exp for the exponent,
1281 *
1282 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1283 * guaranteed to overflow (provided it's nonzero)
1284 *
1285 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1286 * guaranteed to underflow to 0.
1287 *
1288 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1289 * overflow in the calculation of exp and top_exp below.
1290 *
1291 * More specifically, ndigits is assumed to satisfy the following
1292 * inequalities:
1293 *
1294 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1295 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1296 *
1297 * If either of these inequalities is not satisfied, a ValueError is
1298 * raised. Otherwise, write x for the value of the hex string, and
1299 * assume x is nonzero. Then
1300 *
1301 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1302 *
1303 * Now if exp > LONG_MAX/2 then:
1304 *
1305 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1306 * = DBL_MAX_EXP
1307 *
1308 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1309 * double, so overflows. If exp < LONG_MIN/2, then
1310 *
1311 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1312 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1313 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1314 *
1315 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1316 * when converted to a C double.
1317 *
1318 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1319 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1320 */
1321
1322 if (PyString_AsStringAndSize(arg, &s, &length))
1323 return NULL;
1324 s_end = s + length;
1325
1326 /********************
1327 * Parse the string *
1328 ********************/
1329
1330 /* leading whitespace and optional sign */
1331 while (isspace(*s))
1332 s++;
1333 if (*s == '-') {
1334 s++;
1335 sign = -1;
1336 }
1337 else if (*s == '+')
1338 s++;
1339
1340 /* infinities and nans */
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001341 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001342 x = Py_NAN;
1343 goto finished;
1344 }
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001345 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1346 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001347 x = sign*Py_HUGE_VAL;
1348 goto finished;
1349 }
1350
1351 /* [0x] */
1352 s_store = s;
1353 if (*s == '0') {
1354 s++;
1355 if (tolower(*s) == (int)'x')
1356 s++;
1357 else
1358 s = s_store;
1359 }
1360
1361 /* coefficient: <integer> [. <fraction>] */
1362 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001363 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001364 s++;
1365 s_store = s;
1366 if (*s == '.') {
1367 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001368 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001369 s++;
1370 coeff_end = s-1;
1371 }
1372 else
1373 coeff_end = s;
1374
1375 /* ndigits = total # of hex digits; fdigits = # after point */
1376 ndigits = coeff_end - coeff_start;
1377 fdigits = coeff_end - s_store;
1378 if (ndigits == 0)
1379 goto parse_error;
1380 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1381 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1382 goto insane_length_error;
1383
1384 /* [p <exponent>] */
1385 if (tolower(*s) == (int)'p') {
1386 s++;
1387 exp_start = s;
1388 if (*s == '-' || *s == '+')
1389 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001390 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001391 goto parse_error;
1392 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001393 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001394 s++;
1395 exp = strtol(exp_start, NULL, 10);
1396 }
1397 else
1398 exp = 0;
1399
1400 /* optional trailing whitespace leading to the end of the string */
1401 while (isspace(*s))
1402 s++;
1403 if (s != s_end)
1404 goto parse_error;
1405
1406/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1407#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1408 coeff_end-(j) : \
1409 coeff_end-1-(j)))
1410
1411 /*******************************************
1412 * Compute rounded value of the hex string *
1413 *******************************************/
1414
1415 /* Discard leading zeros, and catch extreme overflow and underflow */
1416 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1417 ndigits--;
1418 if (ndigits == 0 || exp < LONG_MIN/2) {
1419 x = sign * 0.0;
1420 goto finished;
1421 }
1422 if (exp > LONG_MAX/2)
1423 goto overflow_error;
1424
1425 /* Adjust exponent for fractional part. */
1426 exp = exp - 4*((long)fdigits);
1427
1428 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1429 top_exp = exp + 4*((long)ndigits - 1);
1430 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1431 top_exp++;
1432
1433 /* catch almost all nonextreme cases of overflow and underflow here */
1434 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1435 x = sign * 0.0;
1436 goto finished;
1437 }
1438 if (top_exp > DBL_MAX_EXP)
1439 goto overflow_error;
1440
1441 /* lsb = exponent of least significant bit of the *rounded* value.
1442 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1443 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1444
1445 x = 0.0;
1446 if (exp >= lsb) {
1447 /* no rounding required */
1448 for (i = ndigits-1; i >= 0; i--)
1449 x = 16.0*x + HEX_DIGIT(i);
1450 x = sign * ldexp(x, (int)(exp));
1451 goto finished;
1452 }
1453 /* rounding required. key_digit is the index of the hex digit
1454 containing the first bit to be rounded away. */
1455 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1456 key_digit = (lsb - exp - 1) / 4;
1457 for (i = ndigits-1; i > key_digit; i--)
1458 x = 16.0*x + HEX_DIGIT(i);
1459 digit = HEX_DIGIT(key_digit);
1460 x = 16.0*x + (double)(digit & (16-2*half_eps));
1461
1462 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1463 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1464 if ((digit & half_eps) != 0) {
1465 round_up = 0;
1466 if ((digit & (3*half_eps-1)) != 0 ||
1467 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1468 round_up = 1;
1469 else
1470 for (i = key_digit-1; i >= 0; i--)
1471 if (HEX_DIGIT(i) != 0) {
1472 round_up = 1;
1473 break;
1474 }
1475 if (round_up == 1) {
1476 x += 2*half_eps;
1477 if (top_exp == DBL_MAX_EXP &&
1478 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1479 /* overflow corner case: pre-rounded value <
1480 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1481 goto overflow_error;
1482 }
1483 }
1484 x = sign * ldexp(x, (int)(exp+4*key_digit));
1485
1486 finished:
1487 result_as_float = Py_BuildValue("(d)", x);
1488 if (result_as_float == NULL)
1489 return NULL;
1490 result = PyObject_CallObject(cls, result_as_float);
1491 Py_DECREF(result_as_float);
1492 return result;
1493
1494 overflow_error:
1495 PyErr_SetString(PyExc_OverflowError,
1496 "hexadecimal value too large to represent as a float");
1497 return NULL;
1498
1499 parse_error:
1500 PyErr_SetString(PyExc_ValueError,
1501 "invalid hexadecimal floating-point string");
1502 return NULL;
1503
1504 insane_length_error:
1505 PyErr_SetString(PyExc_ValueError,
1506 "hexadecimal string too long to convert");
1507 return NULL;
1508}
1509
1510PyDoc_STRVAR(float_fromhex_doc,
1511"float.fromhex(string) -> float\n\
1512\n\
1513Create a floating-point number from a hexadecimal string.\n\
1514>>> float.fromhex('0x1.ffffp10')\n\
15152047.984375\n\
1516>>> float.fromhex('-0x1p-1074')\n\
1517-4.9406564584124654e-324");
1518
1519
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001520static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001521float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001522{
1523 double self;
1524 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001525 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001526 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001527
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001528 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001529 PyObject *py_exponent = NULL;
1530 PyObject *numerator = NULL;
1531 PyObject *denominator = NULL;
1532 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001533 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001534
1535#define INPLACE_UPDATE(obj, call) \
1536 prev = obj; \
1537 obj = call; \
1538 Py_DECREF(prev); \
1539
1540 CONVERT_TO_DOUBLE(v, self);
1541
1542 if (Py_IS_INFINITY(self)) {
1543 PyErr_SetString(PyExc_OverflowError,
1544 "Cannot pass infinity to float.as_integer_ratio.");
1545 return NULL;
1546 }
1547#ifdef Py_NAN
1548 if (Py_IS_NAN(self)) {
1549 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001550 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001551 return NULL;
1552 }
1553#endif
1554
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001555 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001556 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001557 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001558
Raymond Hettingerf9859032008-02-01 23:45:44 +00001559 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001560 float_part *= 2.0;
1561 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001562 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001563 /* self == float_part * 2**exponent exactly and float_part is integral.
1564 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1565 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001566
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001567 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001568 if (numerator == NULL) goto error;
1569
Raymond Hettingerf9859032008-02-01 23:45:44 +00001570 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001571 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001572 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001573 if (py_exponent == NULL) goto error;
1574 INPLACE_UPDATE(py_exponent,
1575 long_methods->nb_lshift(denominator, py_exponent));
1576 if (py_exponent == NULL) goto error;
1577 if (exponent > 0) {
1578 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001579 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001580 if (numerator == NULL) goto error;
1581 }
1582 else {
1583 Py_DECREF(denominator);
1584 denominator = py_exponent;
1585 py_exponent = NULL;
1586 }
1587
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001588 /* Returns ints instead of longs where possible */
1589 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1590 if (numerator == NULL) goto error;
1591 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1592 if (denominator == NULL) goto error;
1593
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001594 result_pair = PyTuple_Pack(2, numerator, denominator);
1595
1596#undef INPLACE_UPDATE
1597error:
1598 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001599 Py_XDECREF(denominator);
1600 Py_XDECREF(numerator);
1601 return result_pair;
1602}
1603
1604PyDoc_STRVAR(float_as_integer_ratio_doc,
1605"float.as_integer_ratio() -> (int, int)\n"
1606"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001607"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1608"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001609"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001610"\n"
1611">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001612"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001613">>> (0.0).as_integer_ratio()\n"
1614"(0, 1)\n"
1615">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001616"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001617
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001618
Jeremy Hylton938ace62002-07-17 16:30:39 +00001619static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001620float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1621
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622static PyObject *
1623float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1624{
1625 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001626 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627
Guido van Rossumbef14172001-08-29 15:47:46 +00001628 if (type != &PyFloat_Type)
1629 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1631 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001632 /* If it's a string, but not a string subclass, use
1633 PyFloat_FromString. */
1634 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001635 return PyFloat_FromString(x, NULL);
1636 return PyNumber_Float(x);
1637}
1638
Guido van Rossumbef14172001-08-29 15:47:46 +00001639/* Wimpy, slow approach to tp_new calls for subtypes of float:
1640 first create a regular float from whatever arguments we got,
1641 then allocate a subtype instance and initialize its ob_fval
1642 from the regular float. The regular float is then thrown away.
1643*/
1644static PyObject *
1645float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1646{
Anthony Baxter377be112006-04-11 06:54:30 +00001647 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001648
1649 assert(PyType_IsSubtype(type, &PyFloat_Type));
1650 tmp = float_new(&PyFloat_Type, args, kwds);
1651 if (tmp == NULL)
1652 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001653 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001654 newobj = type->tp_alloc(type, 0);
1655 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001656 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001657 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001658 }
Anthony Baxter377be112006-04-11 06:54:30 +00001659 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001660 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001661 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001662}
1663
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001664static PyObject *
1665float_getnewargs(PyFloatObject *v)
1666{
1667 return Py_BuildValue("(d)", v->ob_fval);
1668}
1669
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001670/* this is for the benefit of the pack/unpack routines below */
1671
1672typedef enum {
1673 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1674} float_format_type;
1675
1676static float_format_type double_format, float_format;
1677static float_format_type detected_double_format, detected_float_format;
1678
1679static PyObject *
1680float_getformat(PyTypeObject *v, PyObject* arg)
1681{
1682 char* s;
1683 float_format_type r;
1684
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001685 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001686 PyErr_Format(PyExc_TypeError,
1687 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001688 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001689 return NULL;
1690 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001691 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001692 if (strcmp(s, "double") == 0) {
1693 r = double_format;
1694 }
1695 else if (strcmp(s, "float") == 0) {
1696 r = float_format;
1697 }
1698 else {
1699 PyErr_SetString(PyExc_ValueError,
1700 "__getformat__() argument 1 must be "
1701 "'double' or 'float'");
1702 return NULL;
1703 }
1704
1705 switch (r) {
1706 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001707 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001708 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001709 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001710 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001711 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001712 default:
1713 Py_FatalError("insane float_format or double_format");
1714 return NULL;
1715 }
1716}
1717
1718PyDoc_STRVAR(float_getformat_doc,
1719"float.__getformat__(typestr) -> string\n"
1720"\n"
1721"You probably don't want to use this function. It exists mainly to be\n"
1722"used in Python's test suite.\n"
1723"\n"
1724"typestr must be 'double' or 'float'. This function returns whichever of\n"
1725"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1726"format of floating point numbers used by the C type named by typestr.");
1727
1728static PyObject *
1729float_setformat(PyTypeObject *v, PyObject* args)
1730{
1731 char* typestr;
1732 char* format;
1733 float_format_type f;
1734 float_format_type detected;
1735 float_format_type *p;
1736
1737 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1738 return NULL;
1739
1740 if (strcmp(typestr, "double") == 0) {
1741 p = &double_format;
1742 detected = detected_double_format;
1743 }
1744 else if (strcmp(typestr, "float") == 0) {
1745 p = &float_format;
1746 detected = detected_float_format;
1747 }
1748 else {
1749 PyErr_SetString(PyExc_ValueError,
1750 "__setformat__() argument 1 must "
1751 "be 'double' or 'float'");
1752 return NULL;
1753 }
1754
1755 if (strcmp(format, "unknown") == 0) {
1756 f = unknown_format;
1757 }
1758 else if (strcmp(format, "IEEE, little-endian") == 0) {
1759 f = ieee_little_endian_format;
1760 }
1761 else if (strcmp(format, "IEEE, big-endian") == 0) {
1762 f = ieee_big_endian_format;
1763 }
1764 else {
1765 PyErr_SetString(PyExc_ValueError,
1766 "__setformat__() argument 2 must be "
1767 "'unknown', 'IEEE, little-endian' or "
1768 "'IEEE, big-endian'");
1769 return NULL;
1770
1771 }
1772
1773 if (f != unknown_format && f != detected) {
1774 PyErr_Format(PyExc_ValueError,
1775 "can only set %s format to 'unknown' or the "
1776 "detected platform value", typestr);
1777 return NULL;
1778 }
1779
1780 *p = f;
1781 Py_RETURN_NONE;
1782}
1783
1784PyDoc_STRVAR(float_setformat_doc,
1785"float.__setformat__(typestr, fmt) -> None\n"
1786"\n"
1787"You probably don't want to use this function. It exists mainly to be\n"
1788"used in Python's test suite.\n"
1789"\n"
1790"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1791"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1792"one of the latter two if it appears to match the underlying C reality.\n"
1793"\n"
1794"Overrides the automatic determination of C-level floating point type.\n"
1795"This affects how floats are converted to and from binary strings.");
1796
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001797static PyObject *
1798float_getzero(PyObject *v, void *closure)
1799{
1800 return PyFloat_FromDouble(0.0);
1801}
1802
Eric Smitha9f7d622008-02-17 19:46:49 +00001803static PyObject *
1804float__format__(PyObject *self, PyObject *args)
1805{
1806 PyObject *format_spec;
1807
1808 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1809 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001810 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001811 return _PyFloat_FormatAdvanced(self,
1812 PyBytes_AS_STRING(format_spec),
1813 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001814 if (PyUnicode_Check(format_spec)) {
1815 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001816 PyObject *result;
1817 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001818
Eric Smithdc13b792008-05-30 18:10:04 +00001819 if (str_spec == NULL)
1820 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001821
Eric Smithdc13b792008-05-30 18:10:04 +00001822 result = _PyFloat_FormatAdvanced(self,
1823 PyBytes_AS_STRING(str_spec),
1824 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001825
Eric Smithdc13b792008-05-30 18:10:04 +00001826 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001827 return result;
1828 }
1829 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1830 return NULL;
1831}
1832
1833PyDoc_STRVAR(float__format__doc,
1834"float.__format__(format_spec) -> string\n"
1835"\n"
1836"Formats the float according to format_spec.");
1837
1838
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001839static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001840 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001841 "Returns self, the complex conjugate of any float."},
1842 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1843 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001844 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1845 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001846 {"fromhex", (PyCFunction)float_fromhex,
1847 METH_O|METH_CLASS, float_fromhex_doc},
1848 {"hex", (PyCFunction)float_hex,
1849 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001850 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1851 "Returns True if the float is an integer."},
1852#if 0
1853 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1854 "Returns True if the float is positive or negative infinite."},
1855 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1856 "Returns True if the float is finite, neither infinite nor NaN."},
1857 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1858 "Returns True if the float is not a number (NaN)."},
1859#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001860 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001861 {"__getformat__", (PyCFunction)float_getformat,
1862 METH_O|METH_CLASS, float_getformat_doc},
1863 {"__setformat__", (PyCFunction)float_setformat,
1864 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001865 {"__format__", (PyCFunction)float__format__,
1866 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001867 {NULL, NULL} /* sentinel */
1868};
1869
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001870static PyGetSetDef float_getset[] = {
1871 {"real",
1872 (getter)float_float, (setter)NULL,
1873 "the real part of a complex number",
1874 NULL},
1875 {"imag",
1876 (getter)float_getzero, (setter)NULL,
1877 "the imaginary part of a complex number",
1878 NULL},
1879 {NULL} /* Sentinel */
1880};
1881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001882PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001883"float(x) -> floating point number\n\
1884\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001885Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886
1887
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001888static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001889 float_add, /*nb_add*/
1890 float_sub, /*nb_subtract*/
1891 float_mul, /*nb_multiply*/
1892 float_classic_div, /*nb_divide*/
1893 float_rem, /*nb_remainder*/
1894 float_divmod, /*nb_divmod*/
1895 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001896 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001897 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001898 (unaryfunc)float_abs, /*nb_absolute*/
1899 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001900 0, /*nb_invert*/
1901 0, /*nb_lshift*/
1902 0, /*nb_rshift*/
1903 0, /*nb_and*/
1904 0, /*nb_xor*/
1905 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001906 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001907 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001908 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001909 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001910 0, /* nb_oct */
1911 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001912 0, /* nb_inplace_add */
1913 0, /* nb_inplace_subtract */
1914 0, /* nb_inplace_multiply */
1915 0, /* nb_inplace_divide */
1916 0, /* nb_inplace_remainder */
1917 0, /* nb_inplace_power */
1918 0, /* nb_inplace_lshift */
1919 0, /* nb_inplace_rshift */
1920 0, /* nb_inplace_and */
1921 0, /* nb_inplace_xor */
1922 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001923 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001924 float_div, /* nb_true_divide */
1925 0, /* nb_inplace_floor_divide */
1926 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001927};
1928
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001929PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001930 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001931 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001932 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001933 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 (destructor)float_dealloc, /* tp_dealloc */
1935 (printfunc)float_print, /* tp_print */
1936 0, /* tp_getattr */
1937 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001938 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939 (reprfunc)float_repr, /* tp_repr */
1940 &float_as_number, /* tp_as_number */
1941 0, /* tp_as_sequence */
1942 0, /* tp_as_mapping */
1943 (hashfunc)float_hash, /* tp_hash */
1944 0, /* tp_call */
1945 (reprfunc)float_str, /* tp_str */
1946 PyObject_GenericGetAttr, /* tp_getattro */
1947 0, /* tp_setattro */
1948 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001949 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1950 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951 float_doc, /* tp_doc */
1952 0, /* tp_traverse */
1953 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001954 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955 0, /* tp_weaklistoffset */
1956 0, /* tp_iter */
1957 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001958 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001960 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 0, /* tp_base */
1962 0, /* tp_dict */
1963 0, /* tp_descr_get */
1964 0, /* tp_descr_set */
1965 0, /* tp_dictoffset */
1966 0, /* tp_init */
1967 0, /* tp_alloc */
1968 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001969};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001970
1971void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001972_PyFloat_Init(void)
1973{
1974 /* We attempt to determine if this machine is using IEEE
1975 floating point formats by peering at the bits of some
1976 carefully chosen values. If it looks like we are on an
1977 IEEE platform, the float packing/unpacking routines can
1978 just copy bits, if not they resort to arithmetic & shifts
1979 and masks. The shifts & masks approach works on all finite
1980 values, but what happens to infinities, NaNs and signed
1981 zeroes on packing is an accident, and attempting to unpack
1982 a NaN or an infinity will raise an exception.
1983
1984 Note that if we're on some whacked-out platform which uses
1985 IEEE formats but isn't strictly little-endian or big-
1986 endian, we will fall back to the portable shifts & masks
1987 method. */
1988
1989#if SIZEOF_DOUBLE == 8
1990 {
1991 double x = 9006104071832581.0;
1992 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1993 detected_double_format = ieee_big_endian_format;
1994 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1995 detected_double_format = ieee_little_endian_format;
1996 else
1997 detected_double_format = unknown_format;
1998 }
1999#else
2000 detected_double_format = unknown_format;
2001#endif
2002
2003#if SIZEOF_FLOAT == 4
2004 {
2005 float y = 16711938.0;
2006 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2007 detected_float_format = ieee_big_endian_format;
2008 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2009 detected_float_format = ieee_little_endian_format;
2010 else
2011 detected_float_format = unknown_format;
2012 }
2013#else
2014 detected_float_format = unknown_format;
2015#endif
2016
2017 double_format = detected_double_format;
2018 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00002019
Christian Heimes796fc312008-01-30 18:58:29 +00002020 /* Init float info */
2021 if (FloatInfoType.tp_name == 0)
2022 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002023}
2024
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002025int
2026PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002027{
Guido van Rossum3fce8831999-03-12 19:43:17 +00002028 PyFloatObject *p;
2029 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002030 int i;
2031 int u; /* remaining unfreed ints per block */
2032 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002033
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002034 list = block_list;
2035 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002036 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002037 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002038 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002039 for (i = 0, p = &list->objects[0];
2040 i < N_FLOATOBJECTS;
2041 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00002042 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002043 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002044 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002045 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002046 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002047 list->next = block_list;
2048 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002049 for (i = 0, p = &list->objects[0];
2050 i < N_FLOATOBJECTS;
2051 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002052 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00002053 Py_REFCNT(p) == 0) {
2054 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002055 free_list;
2056 free_list = p;
2057 }
2058 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002059 }
2060 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002061 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002062 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002063 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00002064 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002065 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002066 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002067}
2068
2069void
2070PyFloat_Fini(void)
2071{
2072 PyFloatObject *p;
2073 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002074 int i;
2075 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002076
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002077 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002078
Guido van Rossum3fce8831999-03-12 19:43:17 +00002079 if (!Py_VerboseFlag)
2080 return;
2081 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002082 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002083 fprintf(stderr, "\n");
2084 }
2085 else {
2086 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002087 ": %d unfreed float%s\n",
2088 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002089 }
2090 if (Py_VerboseFlag > 1) {
2091 list = block_list;
2092 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002093 for (i = 0, p = &list->objects[0];
2094 i < N_FLOATOBJECTS;
2095 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002096 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00002097 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002098 char buf[100];
2099 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002100 /* XXX(twouters) cast refcount to
2101 long until %zd is universally
2102 available
2103 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00002104 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002105 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002106 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00002107 }
2108 }
2109 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002110 }
2111 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002112}
Tim Peters9905b942003-03-20 20:53:32 +00002113
2114/*----------------------------------------------------------------------------
2115 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002116 */
2117int
2118_PyFloat_Pack4(double x, unsigned char *p, int le)
2119{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002120 if (float_format == unknown_format) {
2121 unsigned char sign;
2122 int e;
2123 double f;
2124 unsigned int fbits;
2125 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002126
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002127 if (le) {
2128 p += 3;
2129 incr = -1;
2130 }
Tim Peters9905b942003-03-20 20:53:32 +00002131
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002132 if (x < 0) {
2133 sign = 1;
2134 x = -x;
2135 }
2136 else
2137 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002138
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002139 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002140
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002141 /* Normalize f to be in the range [1.0, 2.0) */
2142 if (0.5 <= f && f < 1.0) {
2143 f *= 2.0;
2144 e--;
2145 }
2146 else if (f == 0.0)
2147 e = 0;
2148 else {
2149 PyErr_SetString(PyExc_SystemError,
2150 "frexp() result out of range");
2151 return -1;
2152 }
2153
2154 if (e >= 128)
2155 goto Overflow;
2156 else if (e < -126) {
2157 /* Gradual underflow */
2158 f = ldexp(f, 126 + e);
2159 e = 0;
2160 }
2161 else if (!(e == 0 && f == 0.0)) {
2162 e += 127;
2163 f -= 1.0; /* Get rid of leading 1 */
2164 }
2165
2166 f *= 8388608.0; /* 2**23 */
2167 fbits = (unsigned int)(f + 0.5); /* Round */
2168 assert(fbits <= 8388608);
2169 if (fbits >> 23) {
2170 /* The carry propagated out of a string of 23 1 bits. */
2171 fbits = 0;
2172 ++e;
2173 if (e >= 255)
2174 goto Overflow;
2175 }
2176
2177 /* First byte */
2178 *p = (sign << 7) | (e >> 1);
2179 p += incr;
2180
2181 /* Second byte */
2182 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2183 p += incr;
2184
2185 /* Third byte */
2186 *p = (fbits >> 8) & 0xFF;
2187 p += incr;
2188
2189 /* Fourth byte */
2190 *p = fbits & 0xFF;
2191
2192 /* Done */
2193 return 0;
2194
Tim Peters9905b942003-03-20 20:53:32 +00002195 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002197 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002198 const char *s = (char*)&y;
2199 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002200
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002201 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2202 goto Overflow;
2203
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204 if ((float_format == ieee_little_endian_format && !le)
2205 || (float_format == ieee_big_endian_format && le)) {
2206 p += 3;
2207 incr = -1;
2208 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002209
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002210 for (i = 0; i < 4; i++) {
2211 *p = *s++;
2212 p += incr;
2213 }
2214 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002215 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002216 Overflow:
2217 PyErr_SetString(PyExc_OverflowError,
2218 "float too large to pack with f format");
2219 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002220}
2221
2222int
2223_PyFloat_Pack8(double x, unsigned char *p, int le)
2224{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002225 if (double_format == unknown_format) {
2226 unsigned char sign;
2227 int e;
2228 double f;
2229 unsigned int fhi, flo;
2230 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002231
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002232 if (le) {
2233 p += 7;
2234 incr = -1;
2235 }
Tim Peters9905b942003-03-20 20:53:32 +00002236
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002237 if (x < 0) {
2238 sign = 1;
2239 x = -x;
2240 }
2241 else
2242 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002243
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002244 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002245
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002246 /* Normalize f to be in the range [1.0, 2.0) */
2247 if (0.5 <= f && f < 1.0) {
2248 f *= 2.0;
2249 e--;
2250 }
2251 else if (f == 0.0)
2252 e = 0;
2253 else {
2254 PyErr_SetString(PyExc_SystemError,
2255 "frexp() result out of range");
2256 return -1;
2257 }
2258
2259 if (e >= 1024)
2260 goto Overflow;
2261 else if (e < -1022) {
2262 /* Gradual underflow */
2263 f = ldexp(f, 1022 + e);
2264 e = 0;
2265 }
2266 else if (!(e == 0 && f == 0.0)) {
2267 e += 1023;
2268 f -= 1.0; /* Get rid of leading 1 */
2269 }
2270
2271 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2272 f *= 268435456.0; /* 2**28 */
2273 fhi = (unsigned int)f; /* Truncate */
2274 assert(fhi < 268435456);
2275
2276 f -= (double)fhi;
2277 f *= 16777216.0; /* 2**24 */
2278 flo = (unsigned int)(f + 0.5); /* Round */
2279 assert(flo <= 16777216);
2280 if (flo >> 24) {
2281 /* The carry propagated out of a string of 24 1 bits. */
2282 flo = 0;
2283 ++fhi;
2284 if (fhi >> 28) {
2285 /* And it also progagated out of the next 28 bits. */
2286 fhi = 0;
2287 ++e;
2288 if (e >= 2047)
2289 goto Overflow;
2290 }
2291 }
2292
2293 /* First byte */
2294 *p = (sign << 7) | (e >> 4);
2295 p += incr;
2296
2297 /* Second byte */
2298 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2299 p += incr;
2300
2301 /* Third byte */
2302 *p = (fhi >> 16) & 0xFF;
2303 p += incr;
2304
2305 /* Fourth byte */
2306 *p = (fhi >> 8) & 0xFF;
2307 p += incr;
2308
2309 /* Fifth byte */
2310 *p = fhi & 0xFF;
2311 p += incr;
2312
2313 /* Sixth byte */
2314 *p = (flo >> 16) & 0xFF;
2315 p += incr;
2316
2317 /* Seventh byte */
2318 *p = (flo >> 8) & 0xFF;
2319 p += incr;
2320
2321 /* Eighth byte */
2322 *p = flo & 0xFF;
2323 p += incr;
2324
2325 /* Done */
2326 return 0;
2327
2328 Overflow:
2329 PyErr_SetString(PyExc_OverflowError,
2330 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002331 return -1;
2332 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002333 else {
2334 const char *s = (char*)&x;
2335 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002336
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002337 if ((double_format == ieee_little_endian_format && !le)
2338 || (double_format == ieee_big_endian_format && le)) {
2339 p += 7;
2340 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002341 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002342
2343 for (i = 0; i < 8; i++) {
2344 *p = *s++;
2345 p += incr;
2346 }
2347 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002348 }
Tim Peters9905b942003-03-20 20:53:32 +00002349}
2350
2351double
2352_PyFloat_Unpack4(const unsigned char *p, int le)
2353{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002354 if (float_format == unknown_format) {
2355 unsigned char sign;
2356 int e;
2357 unsigned int f;
2358 double x;
2359 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002360
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002361 if (le) {
2362 p += 3;
2363 incr = -1;
2364 }
2365
2366 /* First byte */
2367 sign = (*p >> 7) & 1;
2368 e = (*p & 0x7F) << 1;
2369 p += incr;
2370
2371 /* Second byte */
2372 e |= (*p >> 7) & 1;
2373 f = (*p & 0x7F) << 16;
2374 p += incr;
2375
2376 if (e == 255) {
2377 PyErr_SetString(
2378 PyExc_ValueError,
2379 "can't unpack IEEE 754 special value "
2380 "on non-IEEE platform");
2381 return -1;
2382 }
2383
2384 /* Third byte */
2385 f |= *p << 8;
2386 p += incr;
2387
2388 /* Fourth byte */
2389 f |= *p;
2390
2391 x = (double)f / 8388608.0;
2392
2393 /* XXX This sadly ignores Inf/NaN issues */
2394 if (e == 0)
2395 e = -126;
2396 else {
2397 x += 1.0;
2398 e -= 127;
2399 }
2400 x = ldexp(x, e);
2401
2402 if (sign)
2403 x = -x;
2404
2405 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002406 }
Tim Peters9905b942003-03-20 20:53:32 +00002407 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002408 float x;
2409
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002410 if ((float_format == ieee_little_endian_format && !le)
2411 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002412 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002413 char *d = &buf[3];
2414 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002415
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002416 for (i = 0; i < 4; i++) {
2417 *d-- = *p++;
2418 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002419 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002420 }
2421 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002422 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002423 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002424
2425 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002426 }
Tim Peters9905b942003-03-20 20:53:32 +00002427}
2428
2429double
2430_PyFloat_Unpack8(const unsigned char *p, int le)
2431{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002432 if (double_format == unknown_format) {
2433 unsigned char sign;
2434 int e;
2435 unsigned int fhi, flo;
2436 double x;
2437 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002438
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002439 if (le) {
2440 p += 7;
2441 incr = -1;
2442 }
2443
2444 /* First byte */
2445 sign = (*p >> 7) & 1;
2446 e = (*p & 0x7F) << 4;
2447
2448 p += incr;
2449
2450 /* Second byte */
2451 e |= (*p >> 4) & 0xF;
2452 fhi = (*p & 0xF) << 24;
2453 p += incr;
2454
2455 if (e == 2047) {
2456 PyErr_SetString(
2457 PyExc_ValueError,
2458 "can't unpack IEEE 754 special value "
2459 "on non-IEEE platform");
2460 return -1.0;
2461 }
2462
2463 /* Third byte */
2464 fhi |= *p << 16;
2465 p += incr;
2466
2467 /* Fourth byte */
2468 fhi |= *p << 8;
2469 p += incr;
2470
2471 /* Fifth byte */
2472 fhi |= *p;
2473 p += incr;
2474
2475 /* Sixth byte */
2476 flo = *p << 16;
2477 p += incr;
2478
2479 /* Seventh byte */
2480 flo |= *p << 8;
2481 p += incr;
2482
2483 /* Eighth byte */
2484 flo |= *p;
2485
2486 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2487 x /= 268435456.0; /* 2**28 */
2488
2489 if (e == 0)
2490 e = -1022;
2491 else {
2492 x += 1.0;
2493 e -= 1023;
2494 }
2495 x = ldexp(x, e);
2496
2497 if (sign)
2498 x = -x;
2499
2500 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002501 }
Tim Peters9905b942003-03-20 20:53:32 +00002502 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002503 double x;
2504
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002505 if ((double_format == ieee_little_endian_format && !le)
2506 || (double_format == ieee_big_endian_format && le)) {
2507 char buf[8];
2508 char *d = &buf[7];
2509 int i;
2510
2511 for (i = 0; i < 8; i++) {
2512 *d-- = *p++;
2513 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002514 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002515 }
2516 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002517 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002518 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002519
2520 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002521 }
Tim Peters9905b942003-03-20 20:53:32 +00002522}