blob: 4f041f4820cce51d28dff0ec63ac85ceff515c7d [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;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000345 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000346 int i;
347
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348 /* Subroutine for float_repr and float_print.
349 We want float numbers to be recognizable as such,
350 i.e., they should contain a decimal point or an exponent.
351 However, %g may print the number as an integer;
352 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000353
354 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000355 PyOS_snprintf(format, 32, "%%.%ig", precision);
356 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357 cp = buf;
358 if (*cp == '-')
359 cp++;
360 for (; *cp != '\0'; cp++) {
361 /* Any non-digit means it's not an integer;
362 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000363 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364 break;
365 }
366 if (*cp == '\0') {
367 *cp++ = '.';
368 *cp++ = '0';
369 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000370 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000372 /* Checking the next three chars should be more than enough to
373 * detect inf or nan, even on Windows. We check for inf or nan
374 * at last because they are rare cases.
375 */
376 for (i=0; *cp != '\0' && i<3; cp++, i++) {
377 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
378 continue;
379 /* found something that is neither a digit nor point
380 * it might be a NaN or INF
381 */
382#ifdef Py_NAN
383 if (Py_IS_NAN(v->ob_fval)) {
384 strcpy(buf, "nan");
385 }
386 else
387#endif
388 if (Py_IS_INFINITY(v->ob_fval)) {
389 cp = buf;
390 if (*cp == '-')
391 cp++;
392 strcpy(cp, "inf");
393 }
394 break;
395 }
396
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397}
398
Tim Peters97019e42001-11-28 22:43:45 +0000399/* XXX PyFloat_AsStringEx should not be a public API function (for one
400 XXX thing, its signature passes a buffer without a length; for another,
401 XXX it isn't useful outside this file).
402*/
403void
404PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
405{
406 format_float(buf, 100, v, precision);
407}
408
Neil Schemenauer32117e52001-01-04 01:44:34 +0000409/* Macro and helper that convert PyObject obj to a C double and store
410 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000411 slot function. If conversion to double raises an exception, obj is
412 set to NULL, and the function invoking this macro returns NULL. If
413 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
414 stored in obj, and returned from the function invoking this macro.
415*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +0000416#define CONVERT_TO_DOUBLE(obj, dbl) \
417 if (PyFloat_Check(obj)) \
418 dbl = PyFloat_AS_DOUBLE(obj); \
419 else if (convert_to_double(&(obj), &(dbl)) < 0) \
420 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000421
422static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000423convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000424{
425 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000426
Neil Schemenauer32117e52001-01-04 01:44:34 +0000427 if (PyInt_Check(obj)) {
428 *dbl = (double)PyInt_AS_LONG(obj);
429 }
430 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000431 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000432 if (*dbl == -1.0 && PyErr_Occurred()) {
433 *v = NULL;
434 return -1;
435 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000436 }
437 else {
438 Py_INCREF(Py_NotImplemented);
439 *v = Py_NotImplemented;
440 return -1;
441 }
442 return 0;
443}
444
Guido van Rossum57072eb1999-12-23 19:00:28 +0000445/* Precisions used by repr() and str(), respectively.
446
447 The repr() precision (17 significant decimal digits) is the minimal number
448 that is guaranteed to have enough precision so that if the number is read
449 back in the exact same binary value is recreated. This is true for IEEE
450 floating point by design, and also happens to work for all other modern
451 hardware.
452
453 The str() precision is chosen so that in most cases, the rounding noise
454 created by various operations is suppressed, while giving plenty of
455 precision for practical use.
456
457*/
458
459#define PREC_REPR 17
460#define PREC_STR 12
461
Tim Peters97019e42001-11-28 22:43:45 +0000462/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
463 XXX they pass a char buffer without passing a length.
464*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000465void
Fred Drakefd99de62000-07-09 05:02:18 +0000466PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000467{
Tim Peters97019e42001-11-28 22:43:45 +0000468 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000469}
470
Tim Peters72f98e92001-05-08 15:19:57 +0000471void
472PyFloat_AsReprString(char *buf, PyFloatObject *v)
473{
Tim Peters97019e42001-11-28 22:43:45 +0000474 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000475}
476
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000477/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000478static int
Fred Drakefd99de62000-07-09 05:02:18 +0000479float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480{
481 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000482 format_float(buf, sizeof(buf), v,
483 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000484 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000486 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000487 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000488}
489
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000491float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000493 char buf[100];
494 format_float(buf, sizeof(buf), v, PREC_REPR);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000495
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000496 return PyString_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000497}
498
499static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000500float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000501{
502 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000503 format_float(buf, sizeof(buf), v, PREC_STR);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000504 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505}
506
Tim Peters307fa782004-09-23 08:06:40 +0000507/* Comparison is pretty much a nightmare. When comparing float to float,
508 * we do it as straightforwardly (and long-windedly) as conceivable, so
509 * that, e.g., Python x == y delivers the same result as the platform
510 * C x == y when x and/or y is a NaN.
511 * When mixing float with an integer type, there's no good *uniform* approach.
512 * Converting the double to an integer obviously doesn't work, since we
513 * may lose info from fractional bits. Converting the integer to a double
514 * also has two failure modes: (1) a long int may trigger overflow (too
515 * large to fit in the dynamic range of a C double); (2) even a C long may have
516 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
517 * 63 bits of precision, but a C double probably has only 53), and then
518 * we can falsely claim equality when low-order integer bits are lost by
519 * coercion to double. So this part is painful too.
520 */
521
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000522static PyObject*
523float_richcompare(PyObject *v, PyObject *w, int op)
524{
525 double i, j;
526 int r = 0;
527
Tim Peters307fa782004-09-23 08:06:40 +0000528 assert(PyFloat_Check(v));
529 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000530
Tim Peters307fa782004-09-23 08:06:40 +0000531 /* Switch on the type of w. Set i and j to doubles to be compared,
532 * and op to the richcomp to use.
533 */
534 if (PyFloat_Check(w))
535 j = PyFloat_AS_DOUBLE(w);
536
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000537 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000538 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000539 /* If i is an infinity, its magnitude exceeds any
540 * finite integer, so it doesn't matter which int we
541 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000542 */
543 j = 0.0;
544 else
545 goto Unimplemented;
546 }
547
548 else if (PyInt_Check(w)) {
549 long jj = PyInt_AS_LONG(w);
550 /* In the worst realistic case I can imagine, C double is a
551 * Cray single with 48 bits of precision, and long has 64
552 * bits.
553 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000554#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000555 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
556 if (abs >> 48) {
557 /* Needs more than 48 bits. Make it take the
558 * PyLong path.
559 */
560 PyObject *result;
561 PyObject *ww = PyLong_FromLong(jj);
562
563 if (ww == NULL)
564 return NULL;
565 result = float_richcompare(v, ww, op);
566 Py_DECREF(ww);
567 return result;
568 }
569#endif
570 j = (double)jj;
571 assert((long)j == jj);
572 }
573
574 else if (PyLong_Check(w)) {
575 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
576 int wsign = _PyLong_Sign(w);
577 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000578 int exponent;
579
580 if (vsign != wsign) {
581 /* Magnitudes are irrelevant -- the signs alone
582 * determine the outcome.
583 */
584 i = (double)vsign;
585 j = (double)wsign;
586 goto Compare;
587 }
588 /* The signs are the same. */
589 /* Convert w to a double if it fits. In particular, 0 fits. */
590 nbits = _PyLong_NumBits(w);
591 if (nbits == (size_t)-1 && PyErr_Occurred()) {
592 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000593 * to hold the # of bits. Replace with little doubles
594 * that give the same outcome -- w is so large that
595 * its magnitude must exceed the magnitude of any
596 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000597 */
598 PyErr_Clear();
599 i = (double)vsign;
600 assert(wsign != 0);
601 j = wsign * 2.0;
602 goto Compare;
603 }
604 if (nbits <= 48) {
605 j = PyLong_AsDouble(w);
606 /* It's impossible that <= 48 bits overflowed. */
607 assert(j != -1.0 || ! PyErr_Occurred());
608 goto Compare;
609 }
610 assert(wsign != 0); /* else nbits was 0 */
611 assert(vsign != 0); /* if vsign were 0, then since wsign is
612 * not 0, we would have taken the
613 * vsign != wsign branch at the start */
614 /* We want to work with non-negative numbers. */
615 if (vsign < 0) {
616 /* "Multiply both sides" by -1; this also swaps the
617 * comparator.
618 */
619 i = -i;
620 op = _Py_SwappedOp[op];
621 }
622 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000623 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000624 /* exponent is the # of bits in v before the radix point;
625 * we know that nbits (the # of bits in w) > 48 at this point
626 */
627 if (exponent < 0 || (size_t)exponent < nbits) {
628 i = 1.0;
629 j = 2.0;
630 goto Compare;
631 }
632 if ((size_t)exponent > nbits) {
633 i = 2.0;
634 j = 1.0;
635 goto Compare;
636 }
637 /* v and w have the same number of bits before the radix
638 * point. Construct two longs that have the same comparison
639 * outcome.
640 */
641 {
642 double fracpart;
643 double intpart;
644 PyObject *result = NULL;
645 PyObject *one = NULL;
646 PyObject *vv = NULL;
647 PyObject *ww = w;
648
649 if (wsign < 0) {
650 ww = PyNumber_Negative(w);
651 if (ww == NULL)
652 goto Error;
653 }
654 else
655 Py_INCREF(ww);
656
657 fracpart = modf(i, &intpart);
658 vv = PyLong_FromDouble(intpart);
659 if (vv == NULL)
660 goto Error;
661
662 if (fracpart != 0.0) {
663 /* Shift left, and or a 1 bit into vv
664 * to represent the lost fraction.
665 */
666 PyObject *temp;
667
668 one = PyInt_FromLong(1);
669 if (one == NULL)
670 goto Error;
671
672 temp = PyNumber_Lshift(ww, one);
673 if (temp == NULL)
674 goto Error;
675 Py_DECREF(ww);
676 ww = temp;
677
678 temp = PyNumber_Lshift(vv, one);
679 if (temp == NULL)
680 goto Error;
681 Py_DECREF(vv);
682 vv = temp;
683
684 temp = PyNumber_Or(vv, one);
685 if (temp == NULL)
686 goto Error;
687 Py_DECREF(vv);
688 vv = temp;
689 }
690
691 r = PyObject_RichCompareBool(vv, ww, op);
692 if (r < 0)
693 goto Error;
694 result = PyBool_FromLong(r);
695 Error:
696 Py_XDECREF(vv);
697 Py_XDECREF(ww);
698 Py_XDECREF(one);
699 return result;
700 }
701 } /* else if (PyLong_Check(w)) */
702
703 else /* w isn't float, int, or long */
704 goto Unimplemented;
705
706 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000707 PyFPE_START_PROTECT("richcompare", return NULL)
708 switch (op) {
709 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000710 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000711 break;
712 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000713 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000714 break;
715 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000716 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000717 break;
718 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000719 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000720 break;
721 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000722 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000723 break;
724 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000725 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000726 break;
727 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000728 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000729 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000730
731 Unimplemented:
732 Py_INCREF(Py_NotImplemented);
733 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000734}
735
Guido van Rossum9bfef441993-03-29 10:43:31 +0000736static long
Fred Drakefd99de62000-07-09 05:02:18 +0000737float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000738{
Tim Peters39dce292000-08-15 03:34:48 +0000739 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000740}
741
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000743float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000744{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000745 double a,b;
746 CONVERT_TO_DOUBLE(v, a);
747 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000748 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000749 a = a + b;
750 PyFPE_END_PROTECT(a)
751 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752}
753
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000755float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000757 double a,b;
758 CONVERT_TO_DOUBLE(v, a);
759 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000760 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000761 a = a - b;
762 PyFPE_END_PROTECT(a)
763 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764}
765
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000766static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000767float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000769 double a,b;
770 CONVERT_TO_DOUBLE(v, a);
771 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000772 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000773 a = a * b;
774 PyFPE_END_PROTECT(a)
775 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000779float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000781 double a,b;
782 CONVERT_TO_DOUBLE(v, a);
783 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000784#ifdef Py_NAN
Neil Schemenauer32117e52001-01-04 01:44:34 +0000785 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000786 PyErr_SetString(PyExc_ZeroDivisionError,
787 "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000788 return NULL;
789 }
Christian Heimes6f341092008-04-18 23:13:07 +0000790#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000791 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000792 a = a / b;
793 PyFPE_END_PROTECT(a)
794 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795}
796
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000798float_classic_div(PyObject *v, PyObject *w)
799{
800 double a,b;
801 CONVERT_TO_DOUBLE(v, a);
802 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000803 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000804 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
805 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000806#ifdef Py_NAN
Guido van Rossum393661d2001-08-31 17:40:15 +0000807 if (b == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000808 PyErr_SetString(PyExc_ZeroDivisionError,
809 "float division");
Guido van Rossum393661d2001-08-31 17:40:15 +0000810 return NULL;
811 }
Christian Heimes6f341092008-04-18 23:13:07 +0000812#endif
Guido van Rossum393661d2001-08-31 17:40:15 +0000813 PyFPE_START_PROTECT("divide", return 0)
814 a = a / b;
815 PyFPE_END_PROTECT(a)
816 return PyFloat_FromDouble(a);
817}
818
819static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000820float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000822 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000823 double mod;
Christian Heimes6f341092008-04-18 23:13:07 +0000824 CONVERT_TO_DOUBLE(v, vx);
825 CONVERT_TO_DOUBLE(w, wx);
826#ifdef Py_NAN
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000827 if (wx == 0.0) {
Christian Heimes6f341092008-04-18 23:13:07 +0000828 PyErr_SetString(PyExc_ZeroDivisionError,
829 "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830 return NULL;
831 }
Christian Heimes6f341092008-04-18 23:13:07 +0000832#endif
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000833 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000834 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000835 /* note: checking mod*wx < 0 is incorrect -- underflows to
836 0 if wx < sqrt(smallest nonzero double) */
837 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000838 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000839 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000840 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000841 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000842}
843
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000844static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000845float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000846{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000847 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000848 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000849 CONVERT_TO_DOUBLE(v, vx);
850 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000851 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000852 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000853 return NULL;
854 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000855 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000856 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000857 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000858 exact multiple of wx. But this is fp arithmetic, and fp
859 vx - mod is an approximation; the result is that div may
860 not be an exact integral value after the division, although
861 it will always be very close to one.
862 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000863 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000864 if (mod) {
865 /* ensure the remainder has the same sign as the denominator */
866 if ((wx < 0) != (mod < 0)) {
867 mod += wx;
868 div -= 1.0;
869 }
870 }
871 else {
872 /* the remainder is zero, and in the presence of signed zeroes
873 fmod returns different results across platforms; ensure
874 it has the same sign as the denominator; we'd like to do
875 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000876 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000877 if (wx < 0.0)
878 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000879 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000880 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000881 if (div) {
882 floordiv = floor(div);
883 if (div - floordiv > 0.5)
884 floordiv += 1.0;
885 }
886 else {
887 /* div is zero - get the same sign as the true quotient */
888 div *= div; /* hide "div = +0" from optimizers */
889 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
890 }
891 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000892 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000893}
894
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000895static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000896float_floor_div(PyObject *v, PyObject *w)
897{
898 PyObject *t, *r;
899
900 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000901 if (t == NULL || t == Py_NotImplemented)
902 return t;
903 assert(PyTuple_CheckExact(t));
904 r = PyTuple_GET_ITEM(t, 0);
905 Py_INCREF(r);
906 Py_DECREF(t);
907 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000908}
909
910static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000911float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000912{
913 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000914
915 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000916 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000917 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000918 return NULL;
919 }
920
Neil Schemenauer32117e52001-01-04 01:44:34 +0000921 CONVERT_TO_DOUBLE(v, iv);
922 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000923
924 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000925 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +0000926 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000927 }
Tim Peters96685bf2001-08-23 22:31:37 +0000928 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000929 if (iw < 0.0) {
930 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000931 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000932 return NULL;
933 }
934 return PyFloat_FromDouble(0.0);
935 }
Christian Heimes6f341092008-04-18 23:13:07 +0000936 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
937 return PyFloat_FromDouble(1.0);
938 }
Tim Peterse87568d2003-05-24 20:18:24 +0000939 if (iv < 0.0) {
940 /* Whether this is an error is a mess, and bumps into libm
941 * bugs so we have to figure it out ourselves.
942 */
943 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000944 PyErr_SetString(PyExc_ValueError, "negative number "
945 "cannot be raised to a fractional power");
946 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +0000947 }
948 /* iw is an exact integer, albeit perhaps a very large one.
949 * -1 raised to an exact integer should never be exceptional.
950 * Alas, some libms (chiefly glibc as of early 2003) return
951 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
952 * happen to be representable in a *C* integer. That's a
953 * bug; we let that slide in math.pow() (which currently
954 * reflects all platform accidents), but not for Python's **.
955 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000956 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000957 /* Return 1 if iw is even, -1 if iw is odd; there's
958 * no guarantee that any C integral type is big
959 * enough to hold iw, so we have to check this
960 * indirectly.
961 */
962 ix = floor(iw * 0.5) * 2.0;
963 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
964 }
965 /* Else iv != -1.0, and overflow or underflow are possible.
966 * Unless we're to write pow() ourselves, we have to trust
967 * the platform to do this correctly.
968 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000969 }
Tim Peters96685bf2001-08-23 22:31:37 +0000970 errno = 0;
971 PyFPE_START_PROTECT("pow", return NULL)
972 ix = pow(iv, iw);
973 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000974 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +0000975 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000976 /* We don't expect any errno value other than ERANGE, but
977 * the range of libm bugs appears unbounded.
978 */
Alex Martelli348dc882006-08-23 22:17:59 +0000979 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
980 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000981 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000982 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000984}
985
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000986static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000987float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000988{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000990}
991
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000993float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000994{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000995 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000996}
997
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000998static int
Fred Drakefd99de62000-07-09 05:02:18 +0000999float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001000{
1001 return v->ob_fval != 0.0;
1002}
1003
Guido van Rossum234f9421993-06-17 12:35:49 +00001004static int
Fred Drakefd99de62000-07-09 05:02:18 +00001005float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001006{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001007 if (PyInt_Check(*pw)) {
1008 long x = PyInt_AsLong(*pw);
1009 *pw = PyFloat_FromDouble((double)x);
1010 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001011 return 0;
1012 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001014 double x = PyLong_AsDouble(*pw);
1015 if (x == -1.0 && PyErr_Occurred())
1016 return -1;
1017 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001018 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001019 return 0;
1020 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001021 else if (PyFloat_Check(*pw)) {
1022 Py_INCREF(*pv);
1023 Py_INCREF(*pw);
1024 return 0;
1025 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001026 return 1; /* Can't do it */
1027}
1028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001029static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +00001030float_is_integer(PyObject *v)
1031{
1032 double x = PyFloat_AsDouble(v);
1033 PyObject *o;
1034
1035 if (x == -1.0 && PyErr_Occurred())
1036 return NULL;
1037 if (!Py_IS_FINITE(x))
1038 Py_RETURN_FALSE;
Mark Dickinsone81c3762008-05-09 16:14:15 +00001039 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +00001040 PyFPE_START_PROTECT("is_integer", return NULL)
1041 o = (floor(x) == x) ? Py_True : Py_False;
1042 PyFPE_END_PROTECT(x)
1043 if (errno != 0) {
1044 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1045 PyExc_ValueError);
1046 return NULL;
1047 }
1048 Py_INCREF(o);
1049 return o;
1050}
1051
1052#if 0
1053static PyObject *
1054float_is_inf(PyObject *v)
1055{
1056 double x = PyFloat_AsDouble(v);
1057 if (x == -1.0 && PyErr_Occurred())
1058 return NULL;
1059 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1060}
1061
1062static PyObject *
1063float_is_nan(PyObject *v)
1064{
1065 double x = PyFloat_AsDouble(v);
1066 if (x == -1.0 && PyErr_Occurred())
1067 return NULL;
1068 return PyBool_FromLong((long)Py_IS_NAN(x));
1069}
1070
1071static PyObject *
1072float_is_finite(PyObject *v)
1073{
1074 double x = PyFloat_AsDouble(v);
1075 if (x == -1.0 && PyErr_Occurred())
1076 return NULL;
1077 return PyBool_FromLong((long)Py_IS_FINITE(x));
1078}
1079#endif
1080
1081static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001082float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001083{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001084 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001085 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001086
1087 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001088 /* Try to get out cheap if this fits in a Python int. The attempt
1089 * to cast to long must be protected, as C doesn't define what
1090 * happens if the double is too big to fit in a long. Some rare
1091 * systems raise an exception then (RISCOS was mentioned as one,
1092 * and someone using a non-default option on Sun also bumped into
1093 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1094 * still be vulnerable: if a long has more bits of precision than
1095 * a double, casting MIN/MAX to double may yield an approximation,
1096 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1097 * yield true from the C expression wholepart<=LONG_MAX, despite
1098 * that wholepart is actually greater than LONG_MAX.
1099 */
1100 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1101 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001102 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001103 }
1104 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001105}
1106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001107static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001108float_long(PyObject *v)
1109{
1110 double x = PyFloat_AsDouble(v);
1111 return PyLong_FromDouble(x);
1112}
1113
1114static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001115float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001116{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001117 if (PyFloat_CheckExact(v))
1118 Py_INCREF(v);
1119 else
1120 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001121 return v;
1122}
1123
Mark Dickinson7103aa42008-07-15 19:08:33 +00001124/* turn ASCII hex characters into integer values and vice versa */
1125
1126static char
1127char_from_hex(int x)
1128{
1129 assert(0 <= x && x < 16);
1130 return "0123456789abcdef"[x];
1131}
1132
1133static int
1134hex_from_char(char c) {
1135 int x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001136 switch(c) {
1137 case '0':
1138 x = 0;
1139 break;
1140 case '1':
1141 x = 1;
1142 break;
1143 case '2':
1144 x = 2;
1145 break;
1146 case '3':
1147 x = 3;
1148 break;
1149 case '4':
1150 x = 4;
1151 break;
1152 case '5':
1153 x = 5;
1154 break;
1155 case '6':
1156 x = 6;
1157 break;
1158 case '7':
1159 x = 7;
1160 break;
1161 case '8':
1162 x = 8;
1163 break;
1164 case '9':
1165 x = 9;
1166 break;
1167 case 'a':
1168 case 'A':
1169 x = 10;
1170 break;
1171 case 'b':
1172 case 'B':
1173 x = 11;
1174 break;
1175 case 'c':
1176 case 'C':
1177 x = 12;
1178 break;
1179 case 'd':
1180 case 'D':
1181 x = 13;
1182 break;
1183 case 'e':
1184 case 'E':
1185 x = 14;
1186 break;
1187 case 'f':
1188 case 'F':
1189 x = 15;
1190 break;
1191 default:
1192 x = -1;
1193 break;
1194 }
1195 return x;
1196}
1197
1198/* convert a float to a hexadecimal string */
1199
1200/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1201 of the form 4k+1. */
1202#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1203
1204static PyObject *
1205float_hex(PyObject *v)
1206{
1207 double x, m;
1208 int e, shift, i, si, esign;
1209 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1210 trailing NUL byte. */
1211 char s[(TOHEX_NBITS-1)/4+3];
1212
1213 CONVERT_TO_DOUBLE(v, x);
1214
1215 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1216 return float_str((PyFloatObject *)v);
1217
1218 if (x == 0.0) {
1219 if(copysign(1.0, x) == -1.0)
1220 return PyString_FromString("-0x0.0p+0");
1221 else
1222 return PyString_FromString("0x0.0p+0");
1223 }
1224
1225 m = frexp(fabs(x), &e);
1226 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1227 m = ldexp(m, shift);
1228 e -= shift;
1229
1230 si = 0;
1231 s[si] = char_from_hex((int)m);
1232 si++;
1233 m -= (int)m;
1234 s[si] = '.';
1235 si++;
1236 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1237 m *= 16.0;
1238 s[si] = char_from_hex((int)m);
1239 si++;
1240 m -= (int)m;
1241 }
1242 s[si] = '\0';
1243
1244 if (e < 0) {
1245 esign = (int)'-';
1246 e = -e;
1247 }
1248 else
1249 esign = (int)'+';
1250
1251 if (x < 0.0)
1252 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1253 else
1254 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
1255}
1256
1257PyDoc_STRVAR(float_hex_doc,
1258"float.hex() -> string\n\
1259\n\
1260Return a hexadecimal representation of a floating-point number.\n\
1261>>> (-0.1).hex()\n\
1262'-0x1.999999999999ap-4'\n\
1263>>> 3.14159.hex()\n\
1264'0x1.921f9f01b866ep+1'");
1265
1266/* Convert a hexadecimal string to a float. */
1267
1268static PyObject *
1269float_fromhex(PyObject *cls, PyObject *arg)
1270{
1271 PyObject *result_as_float, *result;
1272 double x;
1273 long exp, top_exp, lsb, key_digit;
1274 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1275 int half_eps, digit, round_up, sign=1;
1276 Py_ssize_t length, ndigits, fdigits, i;
1277
1278 /*
1279 * For the sake of simplicity and correctness, we impose an artificial
1280 * limit on ndigits, the total number of hex digits in the coefficient
1281 * The limit is chosen to ensure that, writing exp for the exponent,
1282 *
1283 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1284 * guaranteed to overflow (provided it's nonzero)
1285 *
1286 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1287 * guaranteed to underflow to 0.
1288 *
1289 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1290 * overflow in the calculation of exp and top_exp below.
1291 *
1292 * More specifically, ndigits is assumed to satisfy the following
1293 * inequalities:
1294 *
1295 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1296 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1297 *
1298 * If either of these inequalities is not satisfied, a ValueError is
1299 * raised. Otherwise, write x for the value of the hex string, and
1300 * assume x is nonzero. Then
1301 *
1302 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1303 *
1304 * Now if exp > LONG_MAX/2 then:
1305 *
1306 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1307 * = DBL_MAX_EXP
1308 *
1309 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1310 * double, so overflows. If exp < LONG_MIN/2, then
1311 *
1312 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1313 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1314 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1315 *
1316 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1317 * when converted to a C double.
1318 *
1319 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1320 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1321 */
1322
1323 if (PyString_AsStringAndSize(arg, &s, &length))
1324 return NULL;
1325 s_end = s + length;
1326
1327 /********************
1328 * Parse the string *
1329 ********************/
1330
1331 /* leading whitespace and optional sign */
1332 while (isspace(*s))
1333 s++;
1334 if (*s == '-') {
1335 s++;
1336 sign = -1;
1337 }
1338 else if (*s == '+')
1339 s++;
1340
1341 /* infinities and nans */
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001342 if (PyOS_strnicmp(s, "nan", 4) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001343 x = Py_NAN;
1344 goto finished;
1345 }
Andrew MacIntyre8c47cab2008-09-22 14:10:54 +00001346 if (PyOS_strnicmp(s, "inf", 4) == 0 ||
1347 PyOS_strnicmp(s, "infinity", 9) == 0) {
Mark Dickinson7103aa42008-07-15 19:08:33 +00001348 x = sign*Py_HUGE_VAL;
1349 goto finished;
1350 }
1351
1352 /* [0x] */
1353 s_store = s;
1354 if (*s == '0') {
1355 s++;
1356 if (tolower(*s) == (int)'x')
1357 s++;
1358 else
1359 s = s_store;
1360 }
1361
1362 /* coefficient: <integer> [. <fraction>] */
1363 coeff_start = s;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001364 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001365 s++;
1366 s_store = s;
1367 if (*s == '.') {
1368 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001369 while (hex_from_char(*s) >= 0)
Mark Dickinson7103aa42008-07-15 19:08:33 +00001370 s++;
1371 coeff_end = s-1;
1372 }
1373 else
1374 coeff_end = s;
1375
1376 /* ndigits = total # of hex digits; fdigits = # after point */
1377 ndigits = coeff_end - coeff_start;
1378 fdigits = coeff_end - s_store;
1379 if (ndigits == 0)
1380 goto parse_error;
1381 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1382 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1383 goto insane_length_error;
1384
1385 /* [p <exponent>] */
1386 if (tolower(*s) == (int)'p') {
1387 s++;
1388 exp_start = s;
1389 if (*s == '-' || *s == '+')
1390 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001391 if (!('0' <= *s && *s <= '9'))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001392 goto parse_error;
1393 s++;
Mark Dickinson5c2bb1a2008-08-21 21:38:38 +00001394 while ('0' <= *s && *s <= '9')
Mark Dickinson7103aa42008-07-15 19:08:33 +00001395 s++;
1396 exp = strtol(exp_start, NULL, 10);
1397 }
1398 else
1399 exp = 0;
1400
1401 /* optional trailing whitespace leading to the end of the string */
1402 while (isspace(*s))
1403 s++;
1404 if (s != s_end)
1405 goto parse_error;
1406
1407/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
1408#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1409 coeff_end-(j) : \
1410 coeff_end-1-(j)))
1411
1412 /*******************************************
1413 * Compute rounded value of the hex string *
1414 *******************************************/
1415
1416 /* Discard leading zeros, and catch extreme overflow and underflow */
1417 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1418 ndigits--;
1419 if (ndigits == 0 || exp < LONG_MIN/2) {
1420 x = sign * 0.0;
1421 goto finished;
1422 }
1423 if (exp > LONG_MAX/2)
1424 goto overflow_error;
1425
1426 /* Adjust exponent for fractional part. */
1427 exp = exp - 4*((long)fdigits);
1428
1429 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1430 top_exp = exp + 4*((long)ndigits - 1);
1431 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1432 top_exp++;
1433
1434 /* catch almost all nonextreme cases of overflow and underflow here */
1435 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1436 x = sign * 0.0;
1437 goto finished;
1438 }
1439 if (top_exp > DBL_MAX_EXP)
1440 goto overflow_error;
1441
1442 /* lsb = exponent of least significant bit of the *rounded* value.
1443 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1444 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
1445
1446 x = 0.0;
1447 if (exp >= lsb) {
1448 /* no rounding required */
1449 for (i = ndigits-1; i >= 0; i--)
1450 x = 16.0*x + HEX_DIGIT(i);
1451 x = sign * ldexp(x, (int)(exp));
1452 goto finished;
1453 }
1454 /* rounding required. key_digit is the index of the hex digit
1455 containing the first bit to be rounded away. */
1456 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1457 key_digit = (lsb - exp - 1) / 4;
1458 for (i = ndigits-1; i > key_digit; i--)
1459 x = 16.0*x + HEX_DIGIT(i);
1460 digit = HEX_DIGIT(key_digit);
1461 x = 16.0*x + (double)(digit & (16-2*half_eps));
1462
1463 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1464 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1465 if ((digit & half_eps) != 0) {
1466 round_up = 0;
1467 if ((digit & (3*half_eps-1)) != 0 ||
1468 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1469 round_up = 1;
1470 else
1471 for (i = key_digit-1; i >= 0; i--)
1472 if (HEX_DIGIT(i) != 0) {
1473 round_up = 1;
1474 break;
1475 }
1476 if (round_up == 1) {
1477 x += 2*half_eps;
1478 if (top_exp == DBL_MAX_EXP &&
1479 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1480 /* overflow corner case: pre-rounded value <
1481 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1482 goto overflow_error;
1483 }
1484 }
1485 x = sign * ldexp(x, (int)(exp+4*key_digit));
1486
1487 finished:
1488 result_as_float = Py_BuildValue("(d)", x);
1489 if (result_as_float == NULL)
1490 return NULL;
1491 result = PyObject_CallObject(cls, result_as_float);
1492 Py_DECREF(result_as_float);
1493 return result;
1494
1495 overflow_error:
1496 PyErr_SetString(PyExc_OverflowError,
1497 "hexadecimal value too large to represent as a float");
1498 return NULL;
1499
1500 parse_error:
1501 PyErr_SetString(PyExc_ValueError,
1502 "invalid hexadecimal floating-point string");
1503 return NULL;
1504
1505 insane_length_error:
1506 PyErr_SetString(PyExc_ValueError,
1507 "hexadecimal string too long to convert");
1508 return NULL;
1509}
1510
1511PyDoc_STRVAR(float_fromhex_doc,
1512"float.fromhex(string) -> float\n\
1513\n\
1514Create a floating-point number from a hexadecimal string.\n\
1515>>> float.fromhex('0x1.ffffp10')\n\
15162047.984375\n\
1517>>> float.fromhex('-0x1p-1074')\n\
1518-4.9406564584124654e-324");
1519
1520
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001521static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001522float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001523{
1524 double self;
1525 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001526 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001527 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001528
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001529 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001530 PyObject *py_exponent = NULL;
1531 PyObject *numerator = NULL;
1532 PyObject *denominator = NULL;
1533 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001534 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001535
1536#define INPLACE_UPDATE(obj, call) \
1537 prev = obj; \
1538 obj = call; \
1539 Py_DECREF(prev); \
1540
1541 CONVERT_TO_DOUBLE(v, self);
1542
1543 if (Py_IS_INFINITY(self)) {
1544 PyErr_SetString(PyExc_OverflowError,
1545 "Cannot pass infinity to float.as_integer_ratio.");
1546 return NULL;
1547 }
1548#ifdef Py_NAN
1549 if (Py_IS_NAN(self)) {
1550 PyErr_SetString(PyExc_ValueError,
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001551 "Cannot pass NaN to float.as_integer_ratio.");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001552 return NULL;
1553 }
1554#endif
1555
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001556 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001557 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001558 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001559
Raymond Hettingerf9859032008-02-01 23:45:44 +00001560 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001561 float_part *= 2.0;
1562 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001563 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001564 /* self == float_part * 2**exponent exactly and float_part is integral.
1565 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1566 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001567
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001568 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001569 if (numerator == NULL) goto error;
1570
Raymond Hettingerf9859032008-02-01 23:45:44 +00001571 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001572 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001573 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001574 if (py_exponent == NULL) goto error;
1575 INPLACE_UPDATE(py_exponent,
1576 long_methods->nb_lshift(denominator, py_exponent));
1577 if (py_exponent == NULL) goto error;
1578 if (exponent > 0) {
1579 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001580 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001581 if (numerator == NULL) goto error;
1582 }
1583 else {
1584 Py_DECREF(denominator);
1585 denominator = py_exponent;
1586 py_exponent = NULL;
1587 }
1588
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001589 /* Returns ints instead of longs where possible */
1590 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1591 if (numerator == NULL) goto error;
1592 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1593 if (denominator == NULL) goto error;
1594
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001595 result_pair = PyTuple_Pack(2, numerator, denominator);
1596
1597#undef INPLACE_UPDATE
1598error:
1599 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001600 Py_XDECREF(denominator);
1601 Py_XDECREF(numerator);
1602 return result_pair;
1603}
1604
1605PyDoc_STRVAR(float_as_integer_ratio_doc,
1606"float.as_integer_ratio() -> (int, int)\n"
1607"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001608"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1609"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001610"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001611"\n"
1612">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001613"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001614">>> (0.0).as_integer_ratio()\n"
1615"(0, 1)\n"
1616">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001617"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001618
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001619
Jeremy Hylton938ace62002-07-17 16:30:39 +00001620static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001621float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1622
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623static PyObject *
1624float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1625{
1626 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001627 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628
Guido van Rossumbef14172001-08-29 15:47:46 +00001629 if (type != &PyFloat_Type)
1630 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1632 return NULL;
Benjamin Peterson99d36f12009-04-15 21:26:36 +00001633 /* If it's a string, but not a string subclass, use
1634 PyFloat_FromString. */
1635 if (PyString_CheckExact(x))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 return PyFloat_FromString(x, NULL);
1637 return PyNumber_Float(x);
1638}
1639
Guido van Rossumbef14172001-08-29 15:47:46 +00001640/* Wimpy, slow approach to tp_new calls for subtypes of float:
1641 first create a regular float from whatever arguments we got,
1642 then allocate a subtype instance and initialize its ob_fval
1643 from the regular float. The regular float is then thrown away.
1644*/
1645static PyObject *
1646float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1647{
Anthony Baxter377be112006-04-11 06:54:30 +00001648 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001649
1650 assert(PyType_IsSubtype(type, &PyFloat_Type));
1651 tmp = float_new(&PyFloat_Type, args, kwds);
1652 if (tmp == NULL)
1653 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001654 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001655 newobj = type->tp_alloc(type, 0);
1656 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001657 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001658 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001659 }
Anthony Baxter377be112006-04-11 06:54:30 +00001660 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001661 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001662 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001663}
1664
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001665static PyObject *
1666float_getnewargs(PyFloatObject *v)
1667{
1668 return Py_BuildValue("(d)", v->ob_fval);
1669}
1670
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671/* this is for the benefit of the pack/unpack routines below */
1672
1673typedef enum {
1674 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1675} float_format_type;
1676
1677static float_format_type double_format, float_format;
1678static float_format_type detected_double_format, detected_float_format;
1679
1680static PyObject *
1681float_getformat(PyTypeObject *v, PyObject* arg)
1682{
1683 char* s;
1684 float_format_type r;
1685
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001686 if (!PyString_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001687 PyErr_Format(PyExc_TypeError,
1688 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001689 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001690 return NULL;
1691 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001692 s = PyString_AS_STRING(arg);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001693 if (strcmp(s, "double") == 0) {
1694 r = double_format;
1695 }
1696 else if (strcmp(s, "float") == 0) {
1697 r = float_format;
1698 }
1699 else {
1700 PyErr_SetString(PyExc_ValueError,
1701 "__getformat__() argument 1 must be "
1702 "'double' or 'float'");
1703 return NULL;
1704 }
1705
1706 switch (r) {
1707 case unknown_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001708 return PyString_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001709 case ieee_little_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001710 return PyString_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001711 case ieee_big_endian_format:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001712 return PyString_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001713 default:
1714 Py_FatalError("insane float_format or double_format");
1715 return NULL;
1716 }
1717}
1718
1719PyDoc_STRVAR(float_getformat_doc,
1720"float.__getformat__(typestr) -> string\n"
1721"\n"
1722"You probably don't want to use this function. It exists mainly to be\n"
1723"used in Python's test suite.\n"
1724"\n"
1725"typestr must be 'double' or 'float'. This function returns whichever of\n"
1726"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1727"format of floating point numbers used by the C type named by typestr.");
1728
1729static PyObject *
1730float_setformat(PyTypeObject *v, PyObject* args)
1731{
1732 char* typestr;
1733 char* format;
1734 float_format_type f;
1735 float_format_type detected;
1736 float_format_type *p;
1737
1738 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1739 return NULL;
1740
1741 if (strcmp(typestr, "double") == 0) {
1742 p = &double_format;
1743 detected = detected_double_format;
1744 }
1745 else if (strcmp(typestr, "float") == 0) {
1746 p = &float_format;
1747 detected = detected_float_format;
1748 }
1749 else {
1750 PyErr_SetString(PyExc_ValueError,
1751 "__setformat__() argument 1 must "
1752 "be 'double' or 'float'");
1753 return NULL;
1754 }
1755
1756 if (strcmp(format, "unknown") == 0) {
1757 f = unknown_format;
1758 }
1759 else if (strcmp(format, "IEEE, little-endian") == 0) {
1760 f = ieee_little_endian_format;
1761 }
1762 else if (strcmp(format, "IEEE, big-endian") == 0) {
1763 f = ieee_big_endian_format;
1764 }
1765 else {
1766 PyErr_SetString(PyExc_ValueError,
1767 "__setformat__() argument 2 must be "
1768 "'unknown', 'IEEE, little-endian' or "
1769 "'IEEE, big-endian'");
1770 return NULL;
1771
1772 }
1773
1774 if (f != unknown_format && f != detected) {
1775 PyErr_Format(PyExc_ValueError,
1776 "can only set %s format to 'unknown' or the "
1777 "detected platform value", typestr);
1778 return NULL;
1779 }
1780
1781 *p = f;
1782 Py_RETURN_NONE;
1783}
1784
1785PyDoc_STRVAR(float_setformat_doc,
1786"float.__setformat__(typestr, fmt) -> None\n"
1787"\n"
1788"You probably don't want to use this function. It exists mainly to be\n"
1789"used in Python's test suite.\n"
1790"\n"
1791"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1792"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1793"one of the latter two if it appears to match the underlying C reality.\n"
1794"\n"
1795"Overrides the automatic determination of C-level floating point type.\n"
1796"This affects how floats are converted to and from binary strings.");
1797
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001798static PyObject *
1799float_getzero(PyObject *v, void *closure)
1800{
1801 return PyFloat_FromDouble(0.0);
1802}
1803
Eric Smitha9f7d622008-02-17 19:46:49 +00001804static PyObject *
1805float__format__(PyObject *self, PyObject *args)
1806{
1807 PyObject *format_spec;
1808
1809 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1810 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001811 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00001812 return _PyFloat_FormatAdvanced(self,
1813 PyBytes_AS_STRING(format_spec),
1814 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001815 if (PyUnicode_Check(format_spec)) {
1816 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00001817 PyObject *result;
1818 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001819
Eric Smithdc13b792008-05-30 18:10:04 +00001820 if (str_spec == NULL)
1821 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001822
Eric Smithdc13b792008-05-30 18:10:04 +00001823 result = _PyFloat_FormatAdvanced(self,
1824 PyBytes_AS_STRING(str_spec),
1825 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001826
Eric Smithdc13b792008-05-30 18:10:04 +00001827 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001828 return result;
1829 }
1830 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1831 return NULL;
1832}
1833
1834PyDoc_STRVAR(float__format__doc,
1835"float.__format__(format_spec) -> string\n"
1836"\n"
1837"Formats the float according to format_spec.");
1838
1839
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001840static PyMethodDef float_methods[] = {
Christian Heimes6f341092008-04-18 23:13:07 +00001841 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001842 "Returns self, the complex conjugate of any float."},
1843 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1844 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001845 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1846 float_as_integer_ratio_doc},
Mark Dickinson7103aa42008-07-15 19:08:33 +00001847 {"fromhex", (PyCFunction)float_fromhex,
1848 METH_O|METH_CLASS, float_fromhex_doc},
1849 {"hex", (PyCFunction)float_hex,
1850 METH_NOARGS, float_hex_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001851 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1852 "Returns True if the float is an integer."},
1853#if 0
1854 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1855 "Returns True if the float is positive or negative infinite."},
1856 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1857 "Returns True if the float is finite, neither infinite nor NaN."},
1858 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1859 "Returns True if the float is not a number (NaN)."},
1860#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001861 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001862 {"__getformat__", (PyCFunction)float_getformat,
1863 METH_O|METH_CLASS, float_getformat_doc},
1864 {"__setformat__", (PyCFunction)float_setformat,
1865 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001866 {"__format__", (PyCFunction)float__format__,
1867 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001868 {NULL, NULL} /* sentinel */
1869};
1870
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001871static PyGetSetDef float_getset[] = {
1872 {"real",
1873 (getter)float_float, (setter)NULL,
1874 "the real part of a complex number",
1875 NULL},
1876 {"imag",
1877 (getter)float_getzero, (setter)NULL,
1878 "the imaginary part of a complex number",
1879 NULL},
1880 {NULL} /* Sentinel */
1881};
1882
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001883PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884"float(x) -> floating point number\n\
1885\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001886Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887
1888
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001889static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001890 float_add, /*nb_add*/
1891 float_sub, /*nb_subtract*/
1892 float_mul, /*nb_multiply*/
1893 float_classic_div, /*nb_divide*/
1894 float_rem, /*nb_remainder*/
1895 float_divmod, /*nb_divmod*/
1896 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001897 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001898 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001899 (unaryfunc)float_abs, /*nb_absolute*/
1900 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001901 0, /*nb_invert*/
1902 0, /*nb_lshift*/
1903 0, /*nb_rshift*/
1904 0, /*nb_and*/
1905 0, /*nb_xor*/
1906 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001907 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001908 float_trunc, /*nb_int*/
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001909 float_long, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001910 float_float, /*nb_float*/
Raymond Hettinger9c437af2008-06-24 22:46:07 +00001911 0, /* nb_oct */
1912 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001913 0, /* nb_inplace_add */
1914 0, /* nb_inplace_subtract */
1915 0, /* nb_inplace_multiply */
1916 0, /* nb_inplace_divide */
1917 0, /* nb_inplace_remainder */
1918 0, /* nb_inplace_power */
1919 0, /* nb_inplace_lshift */
1920 0, /* nb_inplace_rshift */
1921 0, /* nb_inplace_and */
1922 0, /* nb_inplace_xor */
1923 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001924 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001925 float_div, /* nb_true_divide */
1926 0, /* nb_inplace_floor_divide */
1927 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001928};
1929
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001930PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001931 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001932 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001933 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001934 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935 (destructor)float_dealloc, /* tp_dealloc */
1936 (printfunc)float_print, /* tp_print */
1937 0, /* tp_getattr */
1938 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001939 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 (reprfunc)float_repr, /* tp_repr */
1941 &float_as_number, /* tp_as_number */
1942 0, /* tp_as_sequence */
1943 0, /* tp_as_mapping */
1944 (hashfunc)float_hash, /* tp_hash */
1945 0, /* tp_call */
1946 (reprfunc)float_str, /* tp_str */
1947 PyObject_GenericGetAttr, /* tp_getattro */
1948 0, /* tp_setattro */
1949 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001950 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1951 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 float_doc, /* tp_doc */
1953 0, /* tp_traverse */
1954 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001955 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 0, /* tp_weaklistoffset */
1957 0, /* tp_iter */
1958 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001959 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001961 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962 0, /* tp_base */
1963 0, /* tp_dict */
1964 0, /* tp_descr_get */
1965 0, /* tp_descr_set */
1966 0, /* tp_dictoffset */
1967 0, /* tp_init */
1968 0, /* tp_alloc */
1969 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001970};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001971
1972void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001973_PyFloat_Init(void)
1974{
1975 /* We attempt to determine if this machine is using IEEE
1976 floating point formats by peering at the bits of some
1977 carefully chosen values. If it looks like we are on an
1978 IEEE platform, the float packing/unpacking routines can
1979 just copy bits, if not they resort to arithmetic & shifts
1980 and masks. The shifts & masks approach works on all finite
1981 values, but what happens to infinities, NaNs and signed
1982 zeroes on packing is an accident, and attempting to unpack
1983 a NaN or an infinity will raise an exception.
1984
1985 Note that if we're on some whacked-out platform which uses
1986 IEEE formats but isn't strictly little-endian or big-
1987 endian, we will fall back to the portable shifts & masks
1988 method. */
1989
1990#if SIZEOF_DOUBLE == 8
1991 {
1992 double x = 9006104071832581.0;
1993 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1994 detected_double_format = ieee_big_endian_format;
1995 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1996 detected_double_format = ieee_little_endian_format;
1997 else
1998 detected_double_format = unknown_format;
1999 }
2000#else
2001 detected_double_format = unknown_format;
2002#endif
2003
2004#if SIZEOF_FLOAT == 4
2005 {
2006 float y = 16711938.0;
2007 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2008 detected_float_format = ieee_big_endian_format;
2009 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2010 detected_float_format = ieee_little_endian_format;
2011 else
2012 detected_float_format = unknown_format;
2013 }
2014#else
2015 detected_float_format = unknown_format;
2016#endif
2017
2018 double_format = detected_double_format;
2019 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00002020
Christian Heimes796fc312008-01-30 18:58:29 +00002021 /* Init float info */
2022 if (FloatInfoType.tp_name == 0)
2023 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024}
2025
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002026int
2027PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002028{
Guido van Rossum3fce8831999-03-12 19:43:17 +00002029 PyFloatObject *p;
2030 PyFloatBlock *list, *next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002031 int i;
2032 int u; /* remaining unfreed ints per block */
2033 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002034
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002035 list = block_list;
2036 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002037 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002038 while (list != NULL) {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002039 u = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002040 for (i = 0, p = &list->objects[0];
2041 i < N_FLOATOBJECTS;
2042 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00002043 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002044 u++;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002045 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00002046 next = list->next;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002047 if (u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002048 list->next = block_list;
2049 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002050 for (i = 0, p = &list->objects[0];
2051 i < N_FLOATOBJECTS;
2052 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002053 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00002054 Py_REFCNT(p) == 0) {
2055 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002056 free_list;
2057 free_list = p;
2058 }
2059 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002060 }
2061 else {
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002062 PyMem_FREE(list);
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002063 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002064 freelist_size += u;
Guido van Rossum3fce8831999-03-12 19:43:17 +00002065 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002066 }
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002067 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002068}
2069
2070void
2071PyFloat_Fini(void)
2072{
2073 PyFloatObject *p;
2074 PyFloatBlock *list;
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002075 int i;
2076 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002077
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002078 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002079
Guido van Rossum3fce8831999-03-12 19:43:17 +00002080 if (!Py_VerboseFlag)
2081 return;
2082 fprintf(stderr, "# cleanup floats");
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002083 if (!u) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002084 fprintf(stderr, "\n");
2085 }
2086 else {
2087 fprintf(stderr,
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002088 ": %d unfreed float%s\n",
2089 u, u == 1 ? "" : "s");
Guido van Rossum3fce8831999-03-12 19:43:17 +00002090 }
2091 if (Py_VerboseFlag > 1) {
2092 list = block_list;
2093 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00002094 for (i = 0, p = &list->objects[0];
2095 i < N_FLOATOBJECTS;
2096 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00002097 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00002098 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00002099 char buf[100];
2100 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002101 /* XXX(twouters) cast refcount to
2102 long until %zd is universally
2103 available
2104 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00002105 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00002106 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00002107 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00002108 }
2109 }
2110 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002111 }
2112 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002113}
Tim Peters9905b942003-03-20 20:53:32 +00002114
2115/*----------------------------------------------------------------------------
2116 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002117 */
2118int
2119_PyFloat_Pack4(double x, unsigned char *p, int le)
2120{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002121 if (float_format == unknown_format) {
2122 unsigned char sign;
2123 int e;
2124 double f;
2125 unsigned int fbits;
2126 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002127
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002128 if (le) {
2129 p += 3;
2130 incr = -1;
2131 }
Tim Peters9905b942003-03-20 20:53:32 +00002132
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002133 if (x < 0) {
2134 sign = 1;
2135 x = -x;
2136 }
2137 else
2138 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002139
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002140 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002141
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002142 /* Normalize f to be in the range [1.0, 2.0) */
2143 if (0.5 <= f && f < 1.0) {
2144 f *= 2.0;
2145 e--;
2146 }
2147 else if (f == 0.0)
2148 e = 0;
2149 else {
2150 PyErr_SetString(PyExc_SystemError,
2151 "frexp() result out of range");
2152 return -1;
2153 }
2154
2155 if (e >= 128)
2156 goto Overflow;
2157 else if (e < -126) {
2158 /* Gradual underflow */
2159 f = ldexp(f, 126 + e);
2160 e = 0;
2161 }
2162 else if (!(e == 0 && f == 0.0)) {
2163 e += 127;
2164 f -= 1.0; /* Get rid of leading 1 */
2165 }
2166
2167 f *= 8388608.0; /* 2**23 */
2168 fbits = (unsigned int)(f + 0.5); /* Round */
2169 assert(fbits <= 8388608);
2170 if (fbits >> 23) {
2171 /* The carry propagated out of a string of 23 1 bits. */
2172 fbits = 0;
2173 ++e;
2174 if (e >= 255)
2175 goto Overflow;
2176 }
2177
2178 /* First byte */
2179 *p = (sign << 7) | (e >> 1);
2180 p += incr;
2181
2182 /* Second byte */
2183 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2184 p += incr;
2185
2186 /* Third byte */
2187 *p = (fbits >> 8) & 0xFF;
2188 p += incr;
2189
2190 /* Fourth byte */
2191 *p = fbits & 0xFF;
2192
2193 /* Done */
2194 return 0;
2195
Tim Peters9905b942003-03-20 20:53:32 +00002196 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002197 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00002198 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002199 const char *s = (char*)&y;
2200 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002201
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002202 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2203 goto Overflow;
2204
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002205 if ((float_format == ieee_little_endian_format && !le)
2206 || (float_format == ieee_big_endian_format && le)) {
2207 p += 3;
2208 incr = -1;
2209 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002210
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002211 for (i = 0; i < 4; i++) {
2212 *p = *s++;
2213 p += incr;
2214 }
2215 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002216 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002217 Overflow:
2218 PyErr_SetString(PyExc_OverflowError,
2219 "float too large to pack with f format");
2220 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002221}
2222
2223int
2224_PyFloat_Pack8(double x, unsigned char *p, int le)
2225{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002226 if (double_format == unknown_format) {
2227 unsigned char sign;
2228 int e;
2229 double f;
2230 unsigned int fhi, flo;
2231 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002232
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233 if (le) {
2234 p += 7;
2235 incr = -1;
2236 }
Tim Peters9905b942003-03-20 20:53:32 +00002237
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002238 if (x < 0) {
2239 sign = 1;
2240 x = -x;
2241 }
2242 else
2243 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002244
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002245 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002246
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002247 /* Normalize f to be in the range [1.0, 2.0) */
2248 if (0.5 <= f && f < 1.0) {
2249 f *= 2.0;
2250 e--;
2251 }
2252 else if (f == 0.0)
2253 e = 0;
2254 else {
2255 PyErr_SetString(PyExc_SystemError,
2256 "frexp() result out of range");
2257 return -1;
2258 }
2259
2260 if (e >= 1024)
2261 goto Overflow;
2262 else if (e < -1022) {
2263 /* Gradual underflow */
2264 f = ldexp(f, 1022 + e);
2265 e = 0;
2266 }
2267 else if (!(e == 0 && f == 0.0)) {
2268 e += 1023;
2269 f -= 1.0; /* Get rid of leading 1 */
2270 }
2271
2272 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2273 f *= 268435456.0; /* 2**28 */
2274 fhi = (unsigned int)f; /* Truncate */
2275 assert(fhi < 268435456);
2276
2277 f -= (double)fhi;
2278 f *= 16777216.0; /* 2**24 */
2279 flo = (unsigned int)(f + 0.5); /* Round */
2280 assert(flo <= 16777216);
2281 if (flo >> 24) {
2282 /* The carry propagated out of a string of 24 1 bits. */
2283 flo = 0;
2284 ++fhi;
2285 if (fhi >> 28) {
2286 /* And it also progagated out of the next 28 bits. */
2287 fhi = 0;
2288 ++e;
2289 if (e >= 2047)
2290 goto Overflow;
2291 }
2292 }
2293
2294 /* First byte */
2295 *p = (sign << 7) | (e >> 4);
2296 p += incr;
2297
2298 /* Second byte */
2299 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2300 p += incr;
2301
2302 /* Third byte */
2303 *p = (fhi >> 16) & 0xFF;
2304 p += incr;
2305
2306 /* Fourth byte */
2307 *p = (fhi >> 8) & 0xFF;
2308 p += incr;
2309
2310 /* Fifth byte */
2311 *p = fhi & 0xFF;
2312 p += incr;
2313
2314 /* Sixth byte */
2315 *p = (flo >> 16) & 0xFF;
2316 p += incr;
2317
2318 /* Seventh byte */
2319 *p = (flo >> 8) & 0xFF;
2320 p += incr;
2321
2322 /* Eighth byte */
2323 *p = flo & 0xFF;
2324 p += incr;
2325
2326 /* Done */
2327 return 0;
2328
2329 Overflow:
2330 PyErr_SetString(PyExc_OverflowError,
2331 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00002332 return -1;
2333 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002334 else {
2335 const char *s = (char*)&x;
2336 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002337
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002338 if ((double_format == ieee_little_endian_format && !le)
2339 || (double_format == ieee_big_endian_format && le)) {
2340 p += 7;
2341 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00002342 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002343
2344 for (i = 0; i < 8; i++) {
2345 *p = *s++;
2346 p += incr;
2347 }
2348 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00002349 }
Tim Peters9905b942003-03-20 20:53:32 +00002350}
2351
2352double
2353_PyFloat_Unpack4(const unsigned char *p, int le)
2354{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002355 if (float_format == unknown_format) {
2356 unsigned char sign;
2357 int e;
2358 unsigned int f;
2359 double x;
2360 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002361
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362 if (le) {
2363 p += 3;
2364 incr = -1;
2365 }
2366
2367 /* First byte */
2368 sign = (*p >> 7) & 1;
2369 e = (*p & 0x7F) << 1;
2370 p += incr;
2371
2372 /* Second byte */
2373 e |= (*p >> 7) & 1;
2374 f = (*p & 0x7F) << 16;
2375 p += incr;
2376
2377 if (e == 255) {
2378 PyErr_SetString(
2379 PyExc_ValueError,
2380 "can't unpack IEEE 754 special value "
2381 "on non-IEEE platform");
2382 return -1;
2383 }
2384
2385 /* Third byte */
2386 f |= *p << 8;
2387 p += incr;
2388
2389 /* Fourth byte */
2390 f |= *p;
2391
2392 x = (double)f / 8388608.0;
2393
2394 /* XXX This sadly ignores Inf/NaN issues */
2395 if (e == 0)
2396 e = -126;
2397 else {
2398 x += 1.0;
2399 e -= 127;
2400 }
2401 x = ldexp(x, e);
2402
2403 if (sign)
2404 x = -x;
2405
2406 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002407 }
Tim Peters9905b942003-03-20 20:53:32 +00002408 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002409 float x;
2410
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002411 if ((float_format == ieee_little_endian_format && !le)
2412 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002413 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002414 char *d = &buf[3];
2415 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002416
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002417 for (i = 0; i < 4; i++) {
2418 *d-- = *p++;
2419 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002420 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002421 }
2422 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002423 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002424 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002425
2426 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002427 }
Tim Peters9905b942003-03-20 20:53:32 +00002428}
2429
2430double
2431_PyFloat_Unpack8(const unsigned char *p, int le)
2432{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002433 if (double_format == unknown_format) {
2434 unsigned char sign;
2435 int e;
2436 unsigned int fhi, flo;
2437 double x;
2438 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002439
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002440 if (le) {
2441 p += 7;
2442 incr = -1;
2443 }
2444
2445 /* First byte */
2446 sign = (*p >> 7) & 1;
2447 e = (*p & 0x7F) << 4;
2448
2449 p += incr;
2450
2451 /* Second byte */
2452 e |= (*p >> 4) & 0xF;
2453 fhi = (*p & 0xF) << 24;
2454 p += incr;
2455
2456 if (e == 2047) {
2457 PyErr_SetString(
2458 PyExc_ValueError,
2459 "can't unpack IEEE 754 special value "
2460 "on non-IEEE platform");
2461 return -1.0;
2462 }
2463
2464 /* Third byte */
2465 fhi |= *p << 16;
2466 p += incr;
2467
2468 /* Fourth byte */
2469 fhi |= *p << 8;
2470 p += incr;
2471
2472 /* Fifth byte */
2473 fhi |= *p;
2474 p += incr;
2475
2476 /* Sixth byte */
2477 flo = *p << 16;
2478 p += incr;
2479
2480 /* Seventh byte */
2481 flo |= *p << 8;
2482 p += incr;
2483
2484 /* Eighth byte */
2485 flo |= *p;
2486
2487 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2488 x /= 268435456.0; /* 2**28 */
2489
2490 if (e == 0)
2491 e = -1022;
2492 else {
2493 x += 1.0;
2494 e -= 1023;
2495 }
2496 x = ldexp(x, e);
2497
2498 if (sign)
2499 x = -x;
2500
2501 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002502 }
Tim Peters9905b942003-03-20 20:53:32 +00002503 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002504 double x;
2505
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002506 if ((double_format == ieee_little_endian_format && !le)
2507 || (double_format == ieee_big_endian_format && le)) {
2508 char buf[8];
2509 char *d = &buf[7];
2510 int i;
2511
2512 for (i = 0; i < 8; i++) {
2513 *d-- = *p++;
2514 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002515 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002516 }
2517 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002518 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002519 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002520
2521 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002522 }
Tim Peters9905b942003-03-20 20:53:32 +00002523}