blob: 30f7b3489da11b7e9a9726e26b8944ffddd42df9 [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 Norwitz5f95a792008-01-25 08:04:16 +000018#ifdef _OSF_SOURCE
19/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20extern int finite(double);
21#endif
22
Guido van Rossum93ad0df1997-05-13 21:00:42 +000023/* Special free list -- see comments for same code in intobject.c. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000024#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
25#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
26#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000027
Guido van Rossum3fce8831999-03-12 19:43:17 +000028struct _floatblock {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000029 struct _floatblock *next;
30 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000031};
32
33typedef struct _floatblock PyFloatBlock;
34
35static PyFloatBlock *block_list = NULL;
36static PyFloatObject *free_list = NULL;
37
Guido van Rossum93ad0df1997-05-13 21:00:42 +000038static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000039fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000041 PyFloatObject *p, *q;
42 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
43 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
44 if (p == NULL)
45 return (PyFloatObject *) PyErr_NoMemory();
46 ((PyFloatBlock *)p)->next = block_list;
47 block_list = (PyFloatBlock *)p;
48 p = &((PyFloatBlock *)p)->objects[0];
49 q = p + N_FLOATOBJECTS;
50 while (--q > p)
51 Py_TYPE(q) = (struct _typeobject *)(q-1);
52 Py_TYPE(q) = NULL;
53 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054}
55
Christian Heimesdfdfaab2007-12-01 11:20:10 +000056double
57PyFloat_GetMax(void)
58{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000059 return DBL_MAX;
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060}
61
62double
63PyFloat_GetMin(void)
64{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000065 return DBL_MIN;
Christian Heimesdfdfaab2007-12-01 11:20:10 +000066}
67
Christian Heimes796fc312008-01-30 18:58:29 +000068static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000069
70PyDoc_STRVAR(floatinfo__doc__,
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +000071"sys.float_info\n\
Christian Heimesc94e2b52008-01-14 04:13:37 +000072\n\
73A structseq holding information about the float type. It contains low level\n\
74information about the precision and internal representation. Please study\n\
75your system's :file:`float.h` for more information.");
76
77static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000078 {"max", "DBL_MAX -- maximum representable finite float"},
79 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
80 "is representable"},
81 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
82 "is representable"},
83 {"min", "DBL_MIN -- Minimum positive normalizer float"},
84 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
85 "is a normalized float"},
86 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
87 "a normalized"},
88 {"dig", "DBL_DIG -- digits"},
89 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
90 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
91 "representable float"},
92 {"radix", "FLT_RADIX -- radix of exponent"},
93 {"rounds", "FLT_ROUNDS -- addition rounds"},
94 {0}
Christian Heimesc94e2b52008-01-14 04:13:37 +000095};
96
97static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000098 "sys.float_info", /* name */
99 floatinfo__doc__, /* doc */
100 floatinfo_fields, /* fields */
101 11
Christian Heimesc94e2b52008-01-14 04:13:37 +0000102};
103
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000104PyObject *
105PyFloat_GetInfo(void)
106{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000107 PyObject* floatinfo;
108 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000109
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000110 floatinfo = PyStructSequence_New(&FloatInfoType);
111 if (floatinfo == NULL) {
112 return NULL;
113 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000114
Christian Heimesc94e2b52008-01-14 04:13:37 +0000115#define SetIntFlag(flag) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000116 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
Christian Heimesc94e2b52008-01-14 04:13:37 +0000117#define SetDblFlag(flag) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000119
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000120 SetDblFlag(DBL_MAX);
121 SetIntFlag(DBL_MAX_EXP);
122 SetIntFlag(DBL_MAX_10_EXP);
123 SetDblFlag(DBL_MIN);
124 SetIntFlag(DBL_MIN_EXP);
125 SetIntFlag(DBL_MIN_10_EXP);
126 SetIntFlag(DBL_DIG);
127 SetIntFlag(DBL_MANT_DIG);
128 SetDblFlag(DBL_EPSILON);
129 SetIntFlag(FLT_RADIX);
130 SetIntFlag(FLT_ROUNDS);
Christian Heimesc94e2b52008-01-14 04:13:37 +0000131#undef SetIntFlag
132#undef SetDblFlag
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133
134 if (PyErr_Occurred()) {
135 Py_CLEAR(floatinfo);
136 return NULL;
137 }
138 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000139}
140
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 register PyFloatObject *op;
145 if (free_list == NULL) {
146 if ((free_list = fill_free_list()) == NULL)
147 return NULL;
148 }
149 /* Inline PyObject_New */
150 op = free_list;
151 free_list = (PyFloatObject *)Py_TYPE(op);
152 PyObject_INIT(op, &PyFloat_Type);
153 op->ob_fval = fval;
154 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
156
Tim Petersef14d732000-09-23 03:39:17 +0000157/**************************************************************************
158RED_FLAG 22-Sep-2000 tim
159PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
160
1611. If v was a regular string, *pend was set to point to its terminating
162 null byte. That's useless (the caller can find that without any
163 help from this function!).
164
1652. If v was a Unicode string, or an object convertible to a character
166 buffer, *pend was set to point into stack trash (the auto temp
167 vector holding the character buffer). That was downright dangerous.
168
169Since we can't change the interface of a public API function, pend is
170still supported but now *officially* useless: if pend is not NULL,
171*pend is set to NULL.
172**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000174PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000176 const char *s, *last, *end;
177 double x;
178 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000179#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000180 char *s_buffer = NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000181#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000182 Py_ssize_t len;
183 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000185 if (pend)
186 *pend = NULL;
187 if (PyString_Check(v)) {
188 s = PyString_AS_STRING(v);
189 len = PyString_GET_SIZE(v);
190 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000191#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000192 else if (PyUnicode_Check(v)) {
193 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
194 if (s_buffer == NULL)
195 return PyErr_NoMemory();
196 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
197 PyUnicode_GET_SIZE(v),
198 s_buffer,
199 NULL))
200 goto error;
201 s = s_buffer;
202 len = strlen(s);
203 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000204#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000205 else if (PyObject_AsCharBuffer(v, &s, &len)) {
206 PyErr_SetString(PyExc_TypeError,
207 "float() argument must be a string or a number");
208 return NULL;
209 }
210 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000211
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000212 while (Py_ISSPACE(*s))
213 s++;
214 /* We don't care about overflow or underflow. If the platform
215 * supports them, infinities and signed zeroes (on underflow) are
216 * fine. */
217 x = PyOS_string_to_double(s, (char **)&end, NULL);
218 if (x == -1.0 && PyErr_Occurred())
219 goto error;
220 while (Py_ISSPACE(*end))
221 end++;
222 if (end == last)
223 result = PyFloat_FromDouble(x);
224 else {
225 PyOS_snprintf(buffer, sizeof(buffer),
226 "invalid literal for float(): %.200s", s);
227 PyErr_SetString(PyExc_ValueError, buffer);
228 result = NULL;
229 }
Mark Dickinson8568b192009-10-26 21:11:20 +0000230
231 error:
232#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 if (s_buffer)
234 PyMem_FREE(s_buffer);
Mark Dickinson8568b192009-10-26 21:11:20 +0000235#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237}
238
Guido van Rossum234f9421993-06-17 12:35:49 +0000239static void
Fred Drakefd99de62000-07-09 05:02:18 +0000240float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000241{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000242 if (PyFloat_CheckExact(op)) {
243 Py_TYPE(op) = (struct _typeobject *)free_list;
244 free_list = op;
245 }
246 else
247 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000248}
249
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250double
Fred Drakefd99de62000-07-09 05:02:18 +0000251PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 PyNumberMethods *nb;
254 PyFloatObject *fo;
255 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000256
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 if (op && PyFloat_Check(op))
258 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000259
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 if (op == NULL) {
261 PyErr_BadArgument();
262 return -1;
263 }
Tim Petersd2364e82001-11-01 20:09:42 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
266 PyErr_SetString(PyExc_TypeError, "a float is required");
267 return -1;
268 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000269
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000270 fo = (PyFloatObject*) (*nb->nb_float) (op);
271 if (fo == NULL)
272 return -1;
273 if (!PyFloat_Check(fo)) {
274 PyErr_SetString(PyExc_TypeError,
275 "nb_float should return float object");
276 return -1;
277 }
Tim Petersd2364e82001-11-01 20:09:42 +0000278
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279 val = PyFloat_AS_DOUBLE(fo);
280 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000281
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000282 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283}
284
285/* Methods */
286
Neil Schemenauer32117e52001-01-04 01:44:34 +0000287/* Macro and helper that convert PyObject obj to a C double and store
288 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000289 slot function. If conversion to double raises an exception, obj is
290 set to NULL, and the function invoking this macro returns NULL. If
291 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
292 stored in obj, and returned from the function invoking this macro.
293*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000294#define CONVERT_TO_DOUBLE(obj, dbl) \
295 if (PyFloat_Check(obj)) \
296 dbl = PyFloat_AS_DOUBLE(obj); \
297 else if (convert_to_double(&(obj), &(dbl)) < 0) \
298 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000299
300static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000301convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000302{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000304
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000305 if (PyInt_Check(obj)) {
306 *dbl = (double)PyInt_AS_LONG(obj);
307 }
308 else if (PyLong_Check(obj)) {
309 *dbl = PyLong_AsDouble(obj);
310 if (*dbl == -1.0 && PyErr_Occurred()) {
311 *v = NULL;
312 return -1;
313 }
314 }
315 else {
316 Py_INCREF(Py_NotImplemented);
317 *v = Py_NotImplemented;
318 return -1;
319 }
320 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000321}
322
Eric Smithcfaf79c2009-10-26 14:48:55 +0000323/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
Tim Peters97019e42001-11-28 22:43:45 +0000324 XXX they pass a char buffer without passing a length.
325*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000326void
Fred Drakefd99de62000-07-09 05:02:18 +0000327PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000328{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000329 char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
330 PyFloat_STR_PRECISION,
331 Py_DTSF_ADD_DOT_0, NULL);
332 strcpy(buf, tmp);
333 PyMem_Free(tmp);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000334}
335
Tim Peters72f98e92001-05-08 15:19:57 +0000336void
337PyFloat_AsReprString(char *buf, PyFloatObject *v)
338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
340 Py_DTSF_ADD_DOT_0, NULL);
341 strcpy(buf, tmp);
342 PyMem_Free(tmp);
Tim Peters72f98e92001-05-08 15:19:57 +0000343}
344
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000345/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000346static int
Fred Drakefd99de62000-07-09 05:02:18 +0000347float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 char *buf;
350 if (flags & Py_PRINT_RAW)
351 buf = PyOS_double_to_string(v->ob_fval,
352 'g', PyFloat_STR_PRECISION,
353 Py_DTSF_ADD_DOT_0, NULL);
354 else
355 buf = PyOS_double_to_string(v->ob_fval,
356 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
357 Py_BEGIN_ALLOW_THREADS
358 fputs(buf, fp);
359 Py_END_ALLOW_THREADS
360 PyMem_Free(buf);
361 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Eric Smithcfaf79c2009-10-26 14:48:55 +0000365float_str_or_repr(PyFloatObject *v, int precision, char format_code)
366{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 PyObject *result;
368 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
369 format_code, precision,
370 Py_DTSF_ADD_DOT_0,
371 NULL);
372 if (!buf)
373 return PyErr_NoMemory();
374 result = PyString_FromString(buf);
375 PyMem_Free(buf);
376 return result;
Eric Smithcfaf79c2009-10-26 14:48:55 +0000377}
378
379static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000380float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000381{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000383}
384
385static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000386float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000387{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000388 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389}
390
Tim Peters307fa782004-09-23 08:06:40 +0000391/* Comparison is pretty much a nightmare. When comparing float to float,
392 * we do it as straightforwardly (and long-windedly) as conceivable, so
393 * that, e.g., Python x == y delivers the same result as the platform
394 * C x == y when x and/or y is a NaN.
395 * When mixing float with an integer type, there's no good *uniform* approach.
396 * Converting the double to an integer obviously doesn't work, since we
397 * may lose info from fractional bits. Converting the integer to a double
398 * also has two failure modes: (1) a long int may trigger overflow (too
399 * large to fit in the dynamic range of a C double); (2) even a C long may have
400 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
401 * 63 bits of precision, but a C double probably has only 53), and then
402 * we can falsely claim equality when low-order integer bits are lost by
403 * coercion to double. So this part is painful too.
404 */
405
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000406static PyObject*
407float_richcompare(PyObject *v, PyObject *w, int op)
408{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000409 double i, j;
410 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000411
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000412 assert(PyFloat_Check(v));
413 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000414
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 /* Switch on the type of w. Set i and j to doubles to be compared,
416 * and op to the richcomp to use.
417 */
418 if (PyFloat_Check(w))
419 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000420
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 else if (!Py_IS_FINITE(i)) {
422 if (PyInt_Check(w) || PyLong_Check(w))
423 /* If i is an infinity, its magnitude exceeds any
424 * finite integer, so it doesn't matter which int we
425 * compare i with. If i is a NaN, similarly.
426 */
427 j = 0.0;
428 else
429 goto Unimplemented;
430 }
Tim Peters307fa782004-09-23 08:06:40 +0000431
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432 else if (PyInt_Check(w)) {
433 long jj = PyInt_AS_LONG(w);
434 /* In the worst realistic case I can imagine, C double is a
435 * Cray single with 48 bits of precision, and long has 64
436 * bits.
437 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000438#if SIZEOF_LONG > 6
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000439 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
440 if (abs >> 48) {
441 /* Needs more than 48 bits. Make it take the
442 * PyLong path.
443 */
444 PyObject *result;
445 PyObject *ww = PyLong_FromLong(jj);
Tim Peters307fa782004-09-23 08:06:40 +0000446
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000447 if (ww == NULL)
448 return NULL;
449 result = float_richcompare(v, ww, op);
450 Py_DECREF(ww);
451 return result;
452 }
Tim Peters307fa782004-09-23 08:06:40 +0000453#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000454 j = (double)jj;
455 assert((long)j == jj);
456 }
Tim Peters307fa782004-09-23 08:06:40 +0000457
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000458 else if (PyLong_Check(w)) {
459 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
460 int wsign = _PyLong_Sign(w);
461 size_t nbits;
462 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000463
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 if (vsign != wsign) {
465 /* Magnitudes are irrelevant -- the signs alone
466 * determine the outcome.
467 */
468 i = (double)vsign;
469 j = (double)wsign;
470 goto Compare;
471 }
472 /* The signs are the same. */
473 /* Convert w to a double if it fits. In particular, 0 fits. */
474 nbits = _PyLong_NumBits(w);
475 if (nbits == (size_t)-1 && PyErr_Occurred()) {
476 /* This long is so large that size_t isn't big enough
477 * to hold the # of bits. Replace with little doubles
478 * that give the same outcome -- w is so large that
479 * its magnitude must exceed the magnitude of any
480 * finite float.
481 */
482 PyErr_Clear();
483 i = (double)vsign;
484 assert(wsign != 0);
485 j = wsign * 2.0;
486 goto Compare;
487 }
488 if (nbits <= 48) {
489 j = PyLong_AsDouble(w);
490 /* It's impossible that <= 48 bits overflowed. */
491 assert(j != -1.0 || ! PyErr_Occurred());
492 goto Compare;
493 }
494 assert(wsign != 0); /* else nbits was 0 */
495 assert(vsign != 0); /* if vsign were 0, then since wsign is
496 * not 0, we would have taken the
497 * vsign != wsign branch at the start */
498 /* We want to work with non-negative numbers. */
499 if (vsign < 0) {
500 /* "Multiply both sides" by -1; this also swaps the
501 * comparator.
502 */
503 i = -i;
504 op = _Py_SwappedOp[op];
505 }
506 assert(i > 0.0);
507 (void) frexp(i, &exponent);
508 /* exponent is the # of bits in v before the radix point;
509 * we know that nbits (the # of bits in w) > 48 at this point
510 */
511 if (exponent < 0 || (size_t)exponent < nbits) {
512 i = 1.0;
513 j = 2.0;
514 goto Compare;
515 }
516 if ((size_t)exponent > nbits) {
517 i = 2.0;
518 j = 1.0;
519 goto Compare;
520 }
521 /* v and w have the same number of bits before the radix
522 * point. Construct two longs that have the same comparison
523 * outcome.
524 */
525 {
526 double fracpart;
527 double intpart;
528 PyObject *result = NULL;
529 PyObject *one = NULL;
530 PyObject *vv = NULL;
531 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 if (wsign < 0) {
534 ww = PyNumber_Negative(w);
535 if (ww == NULL)
536 goto Error;
537 }
538 else
539 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000540
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 fracpart = modf(i, &intpart);
542 vv = PyLong_FromDouble(intpart);
543 if (vv == NULL)
544 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000545
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 if (fracpart != 0.0) {
547 /* Shift left, and or a 1 bit into vv
548 * to represent the lost fraction.
549 */
550 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000551
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000552 one = PyInt_FromLong(1);
553 if (one == NULL)
554 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000555
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000556 temp = PyNumber_Lshift(ww, one);
557 if (temp == NULL)
558 goto Error;
559 Py_DECREF(ww);
560 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000561
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000562 temp = PyNumber_Lshift(vv, one);
563 if (temp == NULL)
564 goto Error;
565 Py_DECREF(vv);
566 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000567
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 temp = PyNumber_Or(vv, one);
569 if (temp == NULL)
570 goto Error;
571 Py_DECREF(vv);
572 vv = temp;
573 }
Tim Peters307fa782004-09-23 08:06:40 +0000574
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000575 r = PyObject_RichCompareBool(vv, ww, op);
576 if (r < 0)
577 goto Error;
578 result = PyBool_FromLong(r);
579 Error:
580 Py_XDECREF(vv);
581 Py_XDECREF(ww);
582 Py_XDECREF(one);
583 return result;
584 }
585 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000586
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 else /* w isn't float, int, or long */
588 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000589
590 Compare:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000591 PyFPE_START_PROTECT("richcompare", return NULL)
592 switch (op) {
593 case Py_EQ:
594 r = i == j;
595 break;
596 case Py_NE:
597 r = i != j;
598 break;
599 case Py_LE:
600 r = i <= j;
601 break;
602 case Py_GE:
603 r = i >= j;
604 break;
605 case Py_LT:
606 r = i < j;
607 break;
608 case Py_GT:
609 r = i > j;
610 break;
611 }
612 PyFPE_END_PROTECT(r)
613 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000614
615 Unimplemented:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 Py_INCREF(Py_NotImplemented);
617 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000618}
619
Guido van Rossum9bfef441993-03-29 10:43:31 +0000620static long
Fred Drakefd99de62000-07-09 05:02:18 +0000621float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000624}
625
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000627float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000628{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000629 double a,b;
630 CONVERT_TO_DOUBLE(v, a);
631 CONVERT_TO_DOUBLE(w, b);
632 PyFPE_START_PROTECT("add", return 0)
633 a = a + b;
634 PyFPE_END_PROTECT(a)
635 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636}
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000639float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000641 double a,b;
642 CONVERT_TO_DOUBLE(v, a);
643 CONVERT_TO_DOUBLE(w, b);
644 PyFPE_START_PROTECT("subtract", return 0)
645 a = a - b;
646 PyFPE_END_PROTECT(a)
647 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000648}
649
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000651float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000652{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000653 double a,b;
654 CONVERT_TO_DOUBLE(v, a);
655 CONVERT_TO_DOUBLE(w, b);
656 PyFPE_START_PROTECT("multiply", return 0)
657 a = a * b;
658 PyFPE_END_PROTECT(a)
659 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660}
661
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000663float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000665 double a,b;
666 CONVERT_TO_DOUBLE(v, a);
667 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000668#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 if (b == 0.0) {
670 PyErr_SetString(PyExc_ZeroDivisionError,
671 "float division by zero");
672 return NULL;
673 }
Christian Heimes6f341092008-04-18 23:13:07 +0000674#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 PyFPE_START_PROTECT("divide", return 0)
676 a = a / b;
677 PyFPE_END_PROTECT(a)
678 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679}
680
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000682float_classic_div(PyObject *v, PyObject *w)
683{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 double a,b;
685 CONVERT_TO_DOUBLE(v, a);
686 CONVERT_TO_DOUBLE(w, b);
687 if (Py_DivisionWarningFlag >= 2 &&
688 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
689 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000690#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000691 if (b == 0.0) {
692 PyErr_SetString(PyExc_ZeroDivisionError,
693 "float division by zero");
694 return NULL;
695 }
Christian Heimes6f341092008-04-18 23:13:07 +0000696#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000697 PyFPE_START_PROTECT("divide", return 0)
698 a = a / b;
699 PyFPE_END_PROTECT(a)
700 return PyFloat_FromDouble(a);
Guido van Rossum393661d2001-08-31 17:40:15 +0000701}
702
703static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000704float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000705{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 double vx, wx;
707 double mod;
708 CONVERT_TO_DOUBLE(v, vx);
709 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes6f341092008-04-18 23:13:07 +0000710#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000711 if (wx == 0.0) {
712 PyErr_SetString(PyExc_ZeroDivisionError,
713 "float modulo");
714 return NULL;
715 }
Christian Heimes6f341092008-04-18 23:13:07 +0000716#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 PyFPE_START_PROTECT("modulo", return 0)
718 mod = fmod(vx, wx);
Mark Dickinsonecf8ec62010-12-04 12:30:41 +0000719 if (mod) {
720 /* ensure the remainder has the same sign as the denominator */
721 if ((wx < 0) != (mod < 0)) {
722 mod += wx;
723 }
724 }
725 else {
726 /* the remainder is zero, and in the presence of signed zeroes
727 fmod returns different results across platforms; ensure
728 it has the same sign as the denominator; we'd like to do
729 "mod = wx * 0.0", but that may get optimized away */
730 mod *= mod; /* hide "mod = +0" from optimizer */
731 if (wx < 0.0)
732 mod = -mod;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 }
734 PyFPE_END_PROTECT(mod)
735 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736}
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000739float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000740{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 double vx, wx;
742 double div, mod, floordiv;
743 CONVERT_TO_DOUBLE(v, vx);
744 CONVERT_TO_DOUBLE(w, wx);
745 if (wx == 0.0) {
746 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
747 return NULL;
748 }
749 PyFPE_START_PROTECT("divmod", return 0)
750 mod = fmod(vx, wx);
751 /* fmod is typically exact, so vx-mod is *mathematically* an
752 exact multiple of wx. But this is fp arithmetic, and fp
753 vx - mod is an approximation; the result is that div may
754 not be an exact integral value after the division, although
755 it will always be very close to one.
756 */
757 div = (vx - mod) / wx;
758 if (mod) {
759 /* ensure the remainder has the same sign as the denominator */
760 if ((wx < 0) != (mod < 0)) {
761 mod += wx;
762 div -= 1.0;
763 }
764 }
765 else {
766 /* the remainder is zero, and in the presence of signed zeroes
767 fmod returns different results across platforms; ensure
768 it has the same sign as the denominator; we'd like to do
769 "mod = wx * 0.0", but that may get optimized away */
770 mod *= mod; /* hide "mod = +0" from optimizer */
771 if (wx < 0.0)
772 mod = -mod;
773 }
774 /* snap quotient to nearest integral value */
775 if (div) {
776 floordiv = floor(div);
777 if (div - floordiv > 0.5)
778 floordiv += 1.0;
779 }
780 else {
781 /* div is zero - get the same sign as the true quotient */
782 div *= div; /* hide "div = +0" from optimizers */
783 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
784 }
785 PyFPE_END_PROTECT(floordiv)
786 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000787}
788
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000790float_floor_div(PyObject *v, PyObject *w)
791{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000793
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 t = float_divmod(v, w);
795 if (t == NULL || t == Py_NotImplemented)
796 return t;
797 assert(PyTuple_CheckExact(t));
798 r = PyTuple_GET_ITEM(t, 0);
799 Py_INCREF(r);
800 Py_DECREF(t);
801 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000802}
803
Mark Dickinson99d652e2009-12-30 12:12:23 +0000804/* determine whether x is an odd integer or not; assumes that
805 x is not an infinity or nan. */
806#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
807
Tim Peters63a35712001-12-11 19:57:24 +0000808static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000809float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 double iv, iw, ix;
812 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000813
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000814 if ((PyObject *)z != Py_None) {
815 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
816 "allowed unless all arguments are integers");
817 return NULL;
818 }
Tim Peters32f453e2001-09-03 08:35:41 +0000819
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000820 CONVERT_TO_DOUBLE(v, iv);
821 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000822
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 /* Sort out special cases here instead of relying on pow() */
824 if (iw == 0) { /* v**0 is 1, even 0**0 */
825 return PyFloat_FromDouble(1.0);
826 }
827 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
828 return PyFloat_FromDouble(iv);
829 }
830 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
831 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
832 }
833 if (Py_IS_INFINITY(iw)) {
834 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
835 * abs(v) > 1 (including case where v infinite)
836 *
837 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
838 * abs(v) > 1 (including case where v infinite)
839 */
840 iv = fabs(iv);
841 if (iv == 1.0)
842 return PyFloat_FromDouble(1.0);
843 else if ((iw > 0.0) == (iv > 1.0))
844 return PyFloat_FromDouble(fabs(iw)); /* return inf */
845 else
846 return PyFloat_FromDouble(0.0);
847 }
848 if (Py_IS_INFINITY(iv)) {
849 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
850 * both cases, we need to add the appropriate sign if w is
851 * an odd integer.
852 */
853 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
854 if (iw > 0.0)
855 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
856 else
857 return PyFloat_FromDouble(iw_is_odd ?
858 copysign(0.0, iv) : 0.0);
859 }
860 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
861 (already dealt with above), and an error
862 if w is negative. */
863 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
864 if (iw < 0.0) {
865 PyErr_SetString(PyExc_ZeroDivisionError,
866 "0.0 cannot be raised to a "
867 "negative power");
868 return NULL;
869 }
870 /* use correct sign if iw is odd */
871 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
872 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 if (iv < 0.0) {
875 /* Whether this is an error is a mess, and bumps into libm
876 * bugs so we have to figure it out ourselves.
877 */
878 if (iw != floor(iw)) {
879 PyErr_SetString(PyExc_ValueError, "negative number "
880 "cannot be raised to a fractional power");
881 return NULL;
882 }
883 /* iw is an exact integer, albeit perhaps a very large
884 * one. Replace iv by its absolute value and remember
885 * to negate the pow result if iw is odd.
886 */
887 iv = -iv;
888 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
889 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000890
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000891 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
892 /* (-1) ** large_integer also ends up here. Here's an
893 * extract from the comments for the previous
894 * implementation explaining why this special case is
895 * necessary:
896 *
897 * -1 raised to an exact integer should never be exceptional.
898 * Alas, some libms (chiefly glibc as of early 2003) return
899 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
900 * happen to be representable in a *C* integer. That's a
901 * bug.
902 */
903 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
904 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000905
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 /* Now iv and iw are finite, iw is nonzero, and iv is
907 * positive and not equal to 1.0. We finally allow
908 * the platform pow to step in and do the rest.
909 */
910 errno = 0;
911 PyFPE_START_PROTECT("pow", return NULL)
912 ix = pow(iv, iw);
913 PyFPE_END_PROTECT(ix)
914 Py_ADJUST_ERANGE1(ix);
915 if (negate_result)
916 ix = -ix;
Mark Dickinson99d652e2009-12-30 12:12:23 +0000917
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 if (errno != 0) {
919 /* We don't expect any errno value other than ERANGE, but
920 * the range of libm bugs appears unbounded.
921 */
922 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
923 PyExc_ValueError);
924 return NULL;
925 }
926 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000927}
928
Mark Dickinson99d652e2009-12-30 12:12:23 +0000929#undef DOUBLE_IS_ODD_INTEGER
930
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000932float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000934 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000935}
936
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000937static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000938float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000939{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000940 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000941}
942
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000943static int
Fred Drakefd99de62000-07-09 05:02:18 +0000944float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000945{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000947}
948
Guido van Rossum234f9421993-06-17 12:35:49 +0000949static int
Fred Drakefd99de62000-07-09 05:02:18 +0000950float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000951{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000952 if (PyInt_Check(*pw)) {
953 long x = PyInt_AsLong(*pw);
954 *pw = PyFloat_FromDouble((double)x);
955 Py_INCREF(*pv);
956 return 0;
957 }
958 else if (PyLong_Check(*pw)) {
959 double x = PyLong_AsDouble(*pw);
960 if (x == -1.0 && PyErr_Occurred())
961 return -1;
962 *pw = PyFloat_FromDouble(x);
963 Py_INCREF(*pv);
964 return 0;
965 }
966 else if (PyFloat_Check(*pw)) {
967 Py_INCREF(*pv);
968 Py_INCREF(*pw);
969 return 0;
970 }
971 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +0000972}
973
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000974static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000975float_is_integer(PyObject *v)
976{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 double x = PyFloat_AsDouble(v);
978 PyObject *o;
979
980 if (x == -1.0 && PyErr_Occurred())
981 return NULL;
982 if (!Py_IS_FINITE(x))
983 Py_RETURN_FALSE;
984 errno = 0;
985 PyFPE_START_PROTECT("is_integer", return NULL)
986 o = (floor(x) == x) ? Py_True : Py_False;
987 PyFPE_END_PROTECT(x)
988 if (errno != 0) {
989 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
990 PyExc_ValueError);
991 return NULL;
992 }
993 Py_INCREF(o);
994 return o;
Christian Heimes6f341092008-04-18 23:13:07 +0000995}
996
997#if 0
998static PyObject *
999float_is_inf(PyObject *v)
1000{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 double x = PyFloat_AsDouble(v);
1002 if (x == -1.0 && PyErr_Occurred())
1003 return NULL;
1004 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001005}
1006
1007static PyObject *
1008float_is_nan(PyObject *v)
1009{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 double x = PyFloat_AsDouble(v);
1011 if (x == -1.0 && PyErr_Occurred())
1012 return NULL;
1013 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001014}
1015
1016static PyObject *
1017float_is_finite(PyObject *v)
1018{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001019 double x = PyFloat_AsDouble(v);
1020 if (x == -1.0 && PyErr_Occurred())
1021 return NULL;
1022 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001023}
1024#endif
1025
1026static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001027float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 double x = PyFloat_AsDouble(v);
1030 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032 (void)modf(x, &wholepart);
1033 /* Try to get out cheap if this fits in a Python int. The attempt
1034 * to cast to long must be protected, as C doesn't define what
1035 * happens if the double is too big to fit in a long. Some rare
1036 * systems raise an exception then (RISCOS was mentioned as one,
1037 * and someone using a non-default option on Sun also bumped into
Mark Dickinson874d59e2011-03-26 12:18:00 +00001038 * that). Note that checking for <= LONG_MAX is unsafe: if a long
1039 * has more bits of precision than a double, casting LONG_MAX to
1040 * double may yield an approximation, and if that's rounded up,
1041 * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
1042 * expression wholepart<=LONG_MAX, despite that wholepart is
1043 * actually greater than LONG_MAX. However, assuming a two's complement
1044 * machine with no trap representation, LONG_MIN will be a power of 2 (and
1045 * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
1046 * the comparisons with (double)LONG_MIN below should be safe.
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 */
Mark Dickinson874d59e2011-03-26 12:18:00 +00001048 if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001049 const long aslong = (long)wholepart;
1050 return PyInt_FromLong(aslong);
1051 }
1052 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001053}
1054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001055static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001056float_long(PyObject *v)
1057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 double x = PyFloat_AsDouble(v);
1059 return PyLong_FromDouble(x);
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001060}
1061
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001062/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
1063 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1064 ndigits <= 323). Returns a Python float, or sets a Python error and
1065 returns NULL on failure (OverflowError and memory errors are possible). */
1066
1067#ifndef PY_NO_SHORT_FLOAT_REPR
1068/* version of _Py_double_round that uses the correctly-rounded string<->double
1069 conversions from Python/dtoa.c */
1070
1071/* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1072 a double. Since we're using the code in Python/dtoa.c, it should be safe
1073 to assume that C doubles are IEEE 754 binary64 format. To be on the safe
1074 side, we check this. */
1075#if DBL_MANT_DIG == 53
1076#define FIVE_POW_LIMIT 22
1077#else
1078#error "C doubles do not appear to be IEEE 754 binary64 format"
1079#endif
1080
1081PyObject *
1082_Py_double_round(double x, int ndigits) {
1083
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001084 double rounded, m;
1085 Py_ssize_t buflen, mybuflen=100;
1086 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
1087 int decpt, sign, val, halfway_case;
1088 PyObject *result = NULL;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001089 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 /* The basic idea is very simple: convert and round the double to a
1092 decimal string using _Py_dg_dtoa, then convert that decimal string
1093 back to a double with _Py_dg_strtod. There's one minor difficulty:
1094 Python 2.x expects round to do round-half-away-from-zero, while
1095 _Py_dg_dtoa does round-half-to-even. So we need some way to detect
1096 and correct the halfway cases.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001097
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001098 Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1099 some odd integer k. Or in other words, a rational number x is
1100 exactly halfway between two multiples of 10**-ndigits if its
1101 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1102 -ndigits. For ndigits >= 0 the latter condition is automatically
1103 satisfied for a binary float x, since any such float has
1104 nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
1105 integral multiple of 5**-ndigits; we can check this using fmod.
1106 For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1107 to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1108 23 takes at least 54 bits of precision to represent exactly.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001109
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001110 Correction: a simple strategy for dealing with halfway cases is to
1111 (for the halfway cases only) call _Py_dg_dtoa with an argument of
1112 ndigits+1 instead of ndigits (thus doing an exact conversion to
1113 decimal), round the resulting string manually, and then convert
1114 back using _Py_dg_strtod.
1115 */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001116
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 /* nans, infinities and zeros should have already been dealt
1118 with by the caller (in this case, builtin_round) */
1119 assert(Py_IS_FINITE(x) && x != 0.0);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001120
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001121 /* find 2-valuation val of x */
1122 m = frexp(x, &val);
1123 while (m != floor(m)) {
1124 m *= 2.0;
1125 val--;
1126 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001127
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001128 /* determine whether this is a halfway case */
1129 if (val == -ndigits-1) {
1130 if (ndigits >= 0)
1131 halfway_case = 1;
1132 else if (ndigits >= -FIVE_POW_LIMIT) {
1133 double five_pow = 1.0;
1134 int i;
1135 for (i=0; i < -ndigits; i++)
1136 five_pow *= 5.0;
1137 halfway_case = fmod(x, five_pow) == 0.0;
1138 }
1139 else
1140 halfway_case = 0;
1141 }
1142 else
1143 halfway_case = 0;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001145 /* round to a decimal string; use an extra place for halfway case */
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001146 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001148 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 if (buf == NULL) {
1150 PyErr_NoMemory();
1151 return NULL;
1152 }
1153 buflen = buf_end - buf;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001155 /* in halfway case, do the round-half-away-from-zero manually */
1156 if (halfway_case) {
1157 int i, carry;
1158 /* sanity check: _Py_dg_dtoa should not have stripped
1159 any zeros from the result: there should be exactly
1160 ndigits+1 places following the decimal point, and
1161 the last digit in the buffer should be a '5'.*/
1162 assert(buflen - decpt == ndigits+1);
1163 assert(buf[buflen-1] == '5');
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001164
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001165 /* increment and shift right at the same time. */
1166 decpt += 1;
1167 carry = 1;
1168 for (i=buflen-1; i-- > 0;) {
1169 carry += buf[i] - '0';
1170 buf[i+1] = carry % 10 + '0';
1171 carry /= 10;
1172 }
1173 buf[0] = carry + '0';
1174 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001175
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001176 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
1177 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1178 if (buflen + 8 > mybuflen) {
1179 mybuflen = buflen+8;
1180 mybuf = (char *)PyMem_Malloc(mybuflen);
1181 if (mybuf == NULL) {
1182 PyErr_NoMemory();
1183 goto exit;
1184 }
1185 }
1186 /* copy buf to mybuf, adding exponent, sign and leading 0 */
1187 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
1188 buf, decpt - (int)buflen);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001189
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001190 /* and convert the resulting string back to a double */
1191 errno = 0;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001192 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001194 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001195 if (errno == ERANGE && fabs(rounded) >= 1.)
1196 PyErr_SetString(PyExc_OverflowError,
1197 "rounded value too large to represent");
1198 else
1199 result = PyFloat_FromDouble(rounded);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001200
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001201 /* done computing value; now clean up */
1202 if (mybuf != shortbuf)
1203 PyMem_Free(mybuf);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001204 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001205 _Py_dg_freedtoa(buf);
1206 return result;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001207}
1208
1209#undef FIVE_POW_LIMIT
1210
1211#else /* PY_NO_SHORT_FLOAT_REPR */
1212
1213/* fallback version, to be used when correctly rounded binary<->decimal
1214 conversions aren't available */
1215
1216PyObject *
1217_Py_double_round(double x, int ndigits) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001218 double pow1, pow2, y, z;
1219 if (ndigits >= 0) {
1220 if (ndigits > 22) {
1221 /* pow1 and pow2 are each safe from overflow, but
1222 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1223 pow1 = pow(10.0, (double)(ndigits-22));
1224 pow2 = 1e22;
1225 }
1226 else {
1227 pow1 = pow(10.0, (double)ndigits);
1228 pow2 = 1.0;
1229 }
1230 y = (x*pow1)*pow2;
1231 /* if y overflows, then rounded value is exactly x */
1232 if (!Py_IS_FINITE(y))
1233 return PyFloat_FromDouble(x);
1234 }
1235 else {
1236 pow1 = pow(10.0, (double)-ndigits);
1237 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1238 y = x / pow1;
1239 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001241 z = round(y);
1242 if (fabs(y-z) == 0.5)
1243 /* halfway between two integers; use round-away-from-zero */
1244 z = y + copysign(0.5, y);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001245
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001246 if (ndigits >= 0)
1247 z = (z / pow2) / pow1;
1248 else
1249 z *= pow1;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001250
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001251 /* if computation resulted in overflow, raise OverflowError */
1252 if (!Py_IS_FINITE(z)) {
1253 PyErr_SetString(PyExc_OverflowError,
1254 "overflow occurred during round");
1255 return NULL;
1256 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001257
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001258 return PyFloat_FromDouble(z);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001259}
1260
1261#endif /* PY_NO_SHORT_FLOAT_REPR */
1262
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001263static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001264float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001266 if (PyFloat_CheckExact(v))
1267 Py_INCREF(v);
1268 else
1269 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1270 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001271}
1272
Mark Dickinson7103aa42008-07-15 19:08:33 +00001273/* turn ASCII hex characters into integer values and vice versa */
1274
1275static char
1276char_from_hex(int x)
1277{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001278 assert(0 <= x && x < 16);
1279 return "0123456789abcdef"[x];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001280}
1281
1282static int
1283hex_from_char(char c) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 int x;
1285 switch(c) {
1286 case '0':
1287 x = 0;
1288 break;
1289 case '1':
1290 x = 1;
1291 break;
1292 case '2':
1293 x = 2;
1294 break;
1295 case '3':
1296 x = 3;
1297 break;
1298 case '4':
1299 x = 4;
1300 break;
1301 case '5':
1302 x = 5;
1303 break;
1304 case '6':
1305 x = 6;
1306 break;
1307 case '7':
1308 x = 7;
1309 break;
1310 case '8':
1311 x = 8;
1312 break;
1313 case '9':
1314 x = 9;
1315 break;
1316 case 'a':
1317 case 'A':
1318 x = 10;
1319 break;
1320 case 'b':
1321 case 'B':
1322 x = 11;
1323 break;
1324 case 'c':
1325 case 'C':
1326 x = 12;
1327 break;
1328 case 'd':
1329 case 'D':
1330 x = 13;
1331 break;
1332 case 'e':
1333 case 'E':
1334 x = 14;
1335 break;
1336 case 'f':
1337 case 'F':
1338 x = 15;
1339 break;
1340 default:
1341 x = -1;
1342 break;
1343 }
1344 return x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001345}
1346
1347/* convert a float to a hexadecimal string */
1348
1349/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1350 of the form 4k+1. */
1351#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1352
1353static PyObject *
1354float_hex(PyObject *v)
1355{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001356 double x, m;
1357 int e, shift, i, si, esign;
1358 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1359 trailing NUL byte. */
1360 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001362 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001363
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001364 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1365 return float_str((PyFloatObject *)v);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001367 if (x == 0.0) {
Benjamin Petersoncf76d1f2010-07-02 19:41:39 +00001368 if (copysign(1.0, x) == -1.0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001369 return PyString_FromString("-0x0.0p+0");
1370 else
1371 return PyString_FromString("0x0.0p+0");
1372 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001373
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374 m = frexp(fabs(x), &e);
1375 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1376 m = ldexp(m, shift);
1377 e -= shift;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 si = 0;
1380 s[si] = char_from_hex((int)m);
1381 si++;
1382 m -= (int)m;
1383 s[si] = '.';
1384 si++;
1385 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1386 m *= 16.0;
1387 s[si] = char_from_hex((int)m);
1388 si++;
1389 m -= (int)m;
1390 }
1391 s[si] = '\0';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001393 if (e < 0) {
1394 esign = (int)'-';
1395 e = -e;
1396 }
1397 else
1398 esign = (int)'+';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001400 if (x < 0.0)
1401 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1402 else
1403 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001404}
1405
1406PyDoc_STRVAR(float_hex_doc,
1407"float.hex() -> string\n\
1408\n\
1409Return a hexadecimal representation of a floating-point number.\n\
1410>>> (-0.1).hex()\n\
1411'-0x1.999999999999ap-4'\n\
1412>>> 3.14159.hex()\n\
1413'0x1.921f9f01b866ep+1'");
1414
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001415/* Case-insensitive locale-independent string match used for nan and inf
1416 detection. t should be lower-case and null-terminated. Return a nonzero
1417 result if the first strlen(t) characters of s match t and 0 otherwise. */
1418
1419static int
1420case_insensitive_match(const char *s, const char *t)
1421{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001422 while(*t && Py_TOLOWER(*s) == *t) {
1423 s++;
1424 t++;
1425 }
1426 return *t ? 0 : 1;
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001427}
1428
Mark Dickinson7103aa42008-07-15 19:08:33 +00001429/* Convert a hexadecimal string to a float. */
1430
1431static PyObject *
1432float_fromhex(PyObject *cls, PyObject *arg)
1433{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001434 PyObject *result_as_float, *result;
1435 double x;
1436 long exp, top_exp, lsb, key_digit;
1437 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1438 int half_eps, digit, round_up, sign=1;
1439 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001440
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001441 /*
1442 * For the sake of simplicity and correctness, we impose an artificial
1443 * limit on ndigits, the total number of hex digits in the coefficient
1444 * The limit is chosen to ensure that, writing exp for the exponent,
1445 *
1446 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1447 * guaranteed to overflow (provided it's nonzero)
1448 *
1449 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1450 * guaranteed to underflow to 0.
1451 *
1452 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1453 * overflow in the calculation of exp and top_exp below.
1454 *
1455 * More specifically, ndigits is assumed to satisfy the following
1456 * inequalities:
1457 *
1458 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1459 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1460 *
1461 * If either of these inequalities is not satisfied, a ValueError is
1462 * raised. Otherwise, write x for the value of the hex string, and
1463 * assume x is nonzero. Then
1464 *
1465 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1466 *
1467 * Now if exp > LONG_MAX/2 then:
1468 *
1469 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1470 * = DBL_MAX_EXP
1471 *
1472 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1473 * double, so overflows. If exp < LONG_MIN/2, then
1474 *
1475 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1476 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1477 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1478 *
1479 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1480 * when converted to a C double.
1481 *
1482 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1483 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1484 */
Mark Dickinson7103aa42008-07-15 19:08:33 +00001485
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001486 if (PyString_AsStringAndSize(arg, &s, &length))
1487 return NULL;
1488 s_end = s + length;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001489
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001490 /********************
1491 * Parse the string *
1492 ********************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001494 /* leading whitespace and optional sign */
1495 while (Py_ISSPACE(*s))
1496 s++;
1497 if (*s == '-') {
1498 s++;
1499 sign = -1;
1500 }
1501 else if (*s == '+')
1502 s++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001504 /* infinities and nans */
1505 if (*s == 'i' || *s == 'I') {
1506 if (!case_insensitive_match(s+1, "nf"))
1507 goto parse_error;
1508 s += 3;
1509 x = Py_HUGE_VAL;
1510 if (case_insensitive_match(s, "inity"))
1511 s += 5;
1512 goto finished;
1513 }
1514 if (*s == 'n' || *s == 'N') {
1515 if (!case_insensitive_match(s+1, "an"))
1516 goto parse_error;
1517 s += 3;
1518 x = Py_NAN;
1519 goto finished;
1520 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001522 /* [0x] */
1523 s_store = s;
1524 if (*s == '0') {
1525 s++;
1526 if (*s == 'x' || *s == 'X')
1527 s++;
1528 else
1529 s = s_store;
1530 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 /* coefficient: <integer> [. <fraction>] */
1533 coeff_start = s;
1534 while (hex_from_char(*s) >= 0)
1535 s++;
1536 s_store = s;
1537 if (*s == '.') {
1538 s++;
1539 while (hex_from_char(*s) >= 0)
1540 s++;
1541 coeff_end = s-1;
1542 }
1543 else
1544 coeff_end = s;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001545
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 /* ndigits = total # of hex digits; fdigits = # after point */
1547 ndigits = coeff_end - coeff_start;
1548 fdigits = coeff_end - s_store;
1549 if (ndigits == 0)
1550 goto parse_error;
1551 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1552 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1553 goto insane_length_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001555 /* [p <exponent>] */
1556 if (*s == 'p' || *s == 'P') {
1557 s++;
1558 exp_start = s;
1559 if (*s == '-' || *s == '+')
1560 s++;
1561 if (!('0' <= *s && *s <= '9'))
1562 goto parse_error;
1563 s++;
1564 while ('0' <= *s && *s <= '9')
1565 s++;
1566 exp = strtol(exp_start, NULL, 10);
1567 }
1568 else
1569 exp = 0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001570
Mark Dickinson7103aa42008-07-15 19:08:33 +00001571/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001572#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1573 coeff_end-(j) : \
1574 coeff_end-1-(j)))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001575
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001576 /*******************************************
1577 * Compute rounded value of the hex string *
1578 *******************************************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001579
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001580 /* Discard leading zeros, and catch extreme overflow and underflow */
1581 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1582 ndigits--;
1583 if (ndigits == 0 || exp < LONG_MIN/2) {
1584 x = 0.0;
1585 goto finished;
1586 }
1587 if (exp > LONG_MAX/2)
1588 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001590 /* Adjust exponent for fractional part. */
1591 exp = exp - 4*((long)fdigits);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001592
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001593 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1594 top_exp = exp + 4*((long)ndigits - 1);
1595 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1596 top_exp++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001597
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001598 /* catch almost all nonextreme cases of overflow and underflow here */
1599 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1600 x = 0.0;
1601 goto finished;
1602 }
1603 if (top_exp > DBL_MAX_EXP)
1604 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001605
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001606 /* lsb = exponent of least significant bit of the *rounded* value.
1607 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1608 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001609
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001610 x = 0.0;
1611 if (exp >= lsb) {
1612 /* no rounding required */
1613 for (i = ndigits-1; i >= 0; i--)
1614 x = 16.0*x + HEX_DIGIT(i);
1615 x = ldexp(x, (int)(exp));
1616 goto finished;
1617 }
1618 /* rounding required. key_digit is the index of the hex digit
1619 containing the first bit to be rounded away. */
1620 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1621 key_digit = (lsb - exp - 1) / 4;
1622 for (i = ndigits-1; i > key_digit; i--)
1623 x = 16.0*x + HEX_DIGIT(i);
1624 digit = HEX_DIGIT(key_digit);
1625 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001627 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1628 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1629 if ((digit & half_eps) != 0) {
1630 round_up = 0;
1631 if ((digit & (3*half_eps-1)) != 0 ||
1632 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1633 round_up = 1;
1634 else
1635 for (i = key_digit-1; i >= 0; i--)
1636 if (HEX_DIGIT(i) != 0) {
1637 round_up = 1;
1638 break;
1639 }
1640 if (round_up == 1) {
1641 x += 2*half_eps;
1642 if (top_exp == DBL_MAX_EXP &&
1643 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1644 /* overflow corner case: pre-rounded value <
1645 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1646 goto overflow_error;
1647 }
1648 }
1649 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001650
1651 finished:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001652 /* optional trailing whitespace leading to the end of the string */
1653 while (Py_ISSPACE(*s))
1654 s++;
1655 if (s != s_end)
1656 goto parse_error;
1657 result_as_float = Py_BuildValue("(d)", sign * x);
1658 if (result_as_float == NULL)
1659 return NULL;
1660 result = PyObject_CallObject(cls, result_as_float);
1661 Py_DECREF(result_as_float);
1662 return result;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001663
1664 overflow_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001665 PyErr_SetString(PyExc_OverflowError,
1666 "hexadecimal value too large to represent as a float");
1667 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001668
1669 parse_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001670 PyErr_SetString(PyExc_ValueError,
1671 "invalid hexadecimal floating-point string");
1672 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001673
1674 insane_length_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 PyErr_SetString(PyExc_ValueError,
1676 "hexadecimal string too long to convert");
1677 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001678}
1679
1680PyDoc_STRVAR(float_fromhex_doc,
1681"float.fromhex(string) -> float\n\
1682\n\
1683Create a floating-point number from a hexadecimal string.\n\
1684>>> float.fromhex('0x1.ffffp10')\n\
16852047.984375\n\
1686>>> float.fromhex('-0x1p-1074')\n\
1687-4.9406564584124654e-324");
1688
1689
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001690static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001691float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001692{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001693 double self;
1694 double float_part;
1695 int exponent;
1696 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001697
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001698 PyObject *prev;
1699 PyObject *py_exponent = NULL;
1700 PyObject *numerator = NULL;
1701 PyObject *denominator = NULL;
1702 PyObject *result_pair = NULL;
1703 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001704
1705#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001706 prev = obj; \
1707 obj = call; \
1708 Py_DECREF(prev); \
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001709
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001710 CONVERT_TO_DOUBLE(v, self);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001711
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 if (Py_IS_INFINITY(self)) {
1713 PyErr_SetString(PyExc_OverflowError,
1714 "Cannot pass infinity to float.as_integer_ratio.");
1715 return NULL;
1716 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001717#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 if (Py_IS_NAN(self)) {
1719 PyErr_SetString(PyExc_ValueError,
1720 "Cannot pass NaN to float.as_integer_ratio.");
1721 return NULL;
1722 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001723#endif
1724
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001725 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1726 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1727 PyFPE_END_PROTECT(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001729 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1730 float_part *= 2.0;
1731 exponent--;
1732 }
1733 /* self == float_part * 2**exponent exactly and float_part is integral.
1734 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1735 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 numerator = PyLong_FromDouble(float_part);
1738 if (numerator == NULL) goto error;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 /* fold in 2**exponent */
1741 denominator = PyLong_FromLong(1);
1742 py_exponent = PyLong_FromLong(labs((long)exponent));
1743 if (py_exponent == NULL) goto error;
1744 INPLACE_UPDATE(py_exponent,
1745 long_methods->nb_lshift(denominator, py_exponent));
1746 if (py_exponent == NULL) goto error;
1747 if (exponent > 0) {
1748 INPLACE_UPDATE(numerator,
1749 long_methods->nb_multiply(numerator, py_exponent));
1750 if (numerator == NULL) goto error;
1751 }
1752 else {
1753 Py_DECREF(denominator);
1754 denominator = py_exponent;
1755 py_exponent = NULL;
1756 }
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001758 /* Returns ints instead of longs where possible */
1759 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1760 if (numerator == NULL) goto error;
1761 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1762 if (denominator == NULL) goto error;
1763
1764 result_pair = PyTuple_Pack(2, numerator, denominator);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001765
1766#undef INPLACE_UPDATE
1767error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001768 Py_XDECREF(py_exponent);
1769 Py_XDECREF(denominator);
1770 Py_XDECREF(numerator);
1771 return result_pair;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001772}
1773
1774PyDoc_STRVAR(float_as_integer_ratio_doc,
1775"float.as_integer_ratio() -> (int, int)\n"
1776"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001777"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1778"float and with a positive denominator.\n"
Andrew M. Kuchlingbd7c4ca2008-10-04 01:02:29 +00001779"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001780"\n"
1781">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001782"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001783">>> (0.0).as_integer_ratio()\n"
1784"(0, 1)\n"
1785">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001786"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001787
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001788
Jeremy Hylton938ace62002-07-17 16:30:39 +00001789static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001790float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1791
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792static PyObject *
1793float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1794{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001795 PyObject *x = Py_False; /* Integer zero */
1796 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 if (type != &PyFloat_Type)
1799 return float_subtype_new(type, args, kwds); /* Wimp out */
1800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1801 return NULL;
1802 /* If it's a string, but not a string subclass, use
1803 PyFloat_FromString. */
1804 if (PyString_CheckExact(x))
1805 return PyFloat_FromString(x, NULL);
1806 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807}
1808
Guido van Rossumbef14172001-08-29 15:47:46 +00001809/* Wimpy, slow approach to tp_new calls for subtypes of float:
1810 first create a regular float from whatever arguments we got,
1811 then allocate a subtype instance and initialize its ob_fval
1812 from the regular float. The regular float is then thrown away.
1813*/
1814static PyObject *
1815float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1816{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001817 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001819 assert(PyType_IsSubtype(type, &PyFloat_Type));
1820 tmp = float_new(&PyFloat_Type, args, kwds);
1821 if (tmp == NULL)
1822 return NULL;
1823 assert(PyFloat_CheckExact(tmp));
1824 newobj = type->tp_alloc(type, 0);
1825 if (newobj == NULL) {
1826 Py_DECREF(tmp);
1827 return NULL;
1828 }
1829 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1830 Py_DECREF(tmp);
1831 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001832}
1833
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001834static PyObject *
1835float_getnewargs(PyFloatObject *v)
1836{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001837 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001838}
1839
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001840/* this is for the benefit of the pack/unpack routines below */
1841
1842typedef enum {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001843 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001844} float_format_type;
1845
1846static float_format_type double_format, float_format;
1847static float_format_type detected_double_format, detected_float_format;
1848
1849static PyObject *
1850float_getformat(PyTypeObject *v, PyObject* arg)
1851{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001852 char* s;
1853 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001855 if (!PyString_Check(arg)) {
1856 PyErr_Format(PyExc_TypeError,
1857 "__getformat__() argument must be string, not %.500s",
1858 Py_TYPE(arg)->tp_name);
1859 return NULL;
1860 }
1861 s = PyString_AS_STRING(arg);
1862 if (strcmp(s, "double") == 0) {
1863 r = double_format;
1864 }
1865 else if (strcmp(s, "float") == 0) {
1866 r = float_format;
1867 }
1868 else {
1869 PyErr_SetString(PyExc_ValueError,
1870 "__getformat__() argument 1 must be "
1871 "'double' or 'float'");
1872 return NULL;
1873 }
1874
1875 switch (r) {
1876 case unknown_format:
1877 return PyString_FromString("unknown");
1878 case ieee_little_endian_format:
1879 return PyString_FromString("IEEE, little-endian");
1880 case ieee_big_endian_format:
1881 return PyString_FromString("IEEE, big-endian");
1882 default:
1883 Py_FatalError("insane float_format or double_format");
1884 return NULL;
1885 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001886}
1887
1888PyDoc_STRVAR(float_getformat_doc,
1889"float.__getformat__(typestr) -> string\n"
1890"\n"
1891"You probably don't want to use this function. It exists mainly to be\n"
1892"used in Python's test suite.\n"
1893"\n"
1894"typestr must be 'double' or 'float'. This function returns whichever of\n"
1895"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1896"format of floating point numbers used by the C type named by typestr.");
1897
1898static PyObject *
1899float_setformat(PyTypeObject *v, PyObject* args)
1900{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001901 char* typestr;
1902 char* format;
1903 float_format_type f;
1904 float_format_type detected;
1905 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001906
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001907 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1908 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001909
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001910 if (strcmp(typestr, "double") == 0) {
1911 p = &double_format;
1912 detected = detected_double_format;
1913 }
1914 else if (strcmp(typestr, "float") == 0) {
1915 p = &float_format;
1916 detected = detected_float_format;
1917 }
1918 else {
1919 PyErr_SetString(PyExc_ValueError,
1920 "__setformat__() argument 1 must "
1921 "be 'double' or 'float'");
1922 return NULL;
1923 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 if (strcmp(format, "unknown") == 0) {
1926 f = unknown_format;
1927 }
1928 else if (strcmp(format, "IEEE, little-endian") == 0) {
1929 f = ieee_little_endian_format;
1930 }
1931 else if (strcmp(format, "IEEE, big-endian") == 0) {
1932 f = ieee_big_endian_format;
1933 }
1934 else {
1935 PyErr_SetString(PyExc_ValueError,
1936 "__setformat__() argument 2 must be "
1937 "'unknown', 'IEEE, little-endian' or "
1938 "'IEEE, big-endian'");
1939 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001940
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001941 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001942
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 if (f != unknown_format && f != detected) {
1944 PyErr_Format(PyExc_ValueError,
1945 "can only set %s format to 'unknown' or the "
1946 "detected platform value", typestr);
1947 return NULL;
1948 }
1949
1950 *p = f;
1951 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001952}
1953
1954PyDoc_STRVAR(float_setformat_doc,
1955"float.__setformat__(typestr, fmt) -> None\n"
1956"\n"
1957"You probably don't want to use this function. It exists mainly to be\n"
1958"used in Python's test suite.\n"
1959"\n"
1960"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1961"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1962"one of the latter two if it appears to match the underlying C reality.\n"
1963"\n"
1964"Overrides the automatic determination of C-level floating point type.\n"
1965"This affects how floats are converted to and from binary strings.");
1966
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001967static PyObject *
1968float_getzero(PyObject *v, void *closure)
1969{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001970 return PyFloat_FromDouble(0.0);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001971}
1972
Eric Smitha9f7d622008-02-17 19:46:49 +00001973static PyObject *
1974float__format__(PyObject *self, PyObject *args)
1975{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001976 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001977
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001978 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1979 return NULL;
1980 if (PyBytes_Check(format_spec))
1981 return _PyFloat_FormatAdvanced(self,
1982 PyBytes_AS_STRING(format_spec),
1983 PyBytes_GET_SIZE(format_spec));
1984 if (PyUnicode_Check(format_spec)) {
1985 /* Convert format_spec to a str */
1986 PyObject *result;
1987 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001988
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001989 if (str_spec == NULL)
1990 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001991
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001992 result = _PyFloat_FormatAdvanced(self,
1993 PyBytes_AS_STRING(str_spec),
1994 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001995
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001996 Py_DECREF(str_spec);
1997 return result;
1998 }
1999 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
2000 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002001}
2002
2003PyDoc_STRVAR(float__format__doc,
2004"float.__format__(format_spec) -> string\n"
2005"\n"
2006"Formats the float according to format_spec.");
2007
2008
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002009static PyMethodDef float_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002010 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
2011 "Returns self, the complex conjugate of any float."},
2012 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
2013 "Returns the Integral closest to x between 0 and x."},
2014 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
2015 float_as_integer_ratio_doc},
2016 {"fromhex", (PyCFunction)float_fromhex,
2017 METH_O|METH_CLASS, float_fromhex_doc},
2018 {"hex", (PyCFunction)float_hex,
2019 METH_NOARGS, float_hex_doc},
2020 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
2021 "Returns True if the float is an integer."},
Christian Heimes6f341092008-04-18 23:13:07 +00002022#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002023 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
2024 "Returns True if the float is positive or negative infinite."},
2025 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
2026 "Returns True if the float is finite, neither infinite nor NaN."},
2027 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
2028 "Returns True if the float is not a number (NaN)."},
Christian Heimes6f341092008-04-18 23:13:07 +00002029#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002030 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
2031 {"__getformat__", (PyCFunction)float_getformat,
2032 METH_O|METH_CLASS, float_getformat_doc},
2033 {"__setformat__", (PyCFunction)float_setformat,
2034 METH_VARARGS|METH_CLASS, float_setformat_doc},
2035 {"__format__", (PyCFunction)float__format__,
2036 METH_VARARGS, float__format__doc},
2037 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002038};
2039
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002040static PyGetSetDef float_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002041 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002042 (getter)float_float, (setter)NULL,
2043 "the real part of a complex number",
2044 NULL},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002045 {"imag",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002046 (getter)float_getzero, (setter)NULL,
2047 "the imaginary part of a complex number",
2048 NULL},
2049 {NULL} /* Sentinel */
2050};
2051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002052PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053"float(x) -> floating point number\n\
2054\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002055Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056
2057
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002058static PyNumberMethods float_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002059 float_add, /*nb_add*/
2060 float_sub, /*nb_subtract*/
2061 float_mul, /*nb_multiply*/
2062 float_classic_div, /*nb_divide*/
2063 float_rem, /*nb_remainder*/
2064 float_divmod, /*nb_divmod*/
2065 float_pow, /*nb_power*/
2066 (unaryfunc)float_neg, /*nb_negative*/
2067 (unaryfunc)float_float, /*nb_positive*/
2068 (unaryfunc)float_abs, /*nb_absolute*/
2069 (inquiry)float_nonzero, /*nb_nonzero*/
2070 0, /*nb_invert*/
2071 0, /*nb_lshift*/
2072 0, /*nb_rshift*/
2073 0, /*nb_and*/
2074 0, /*nb_xor*/
2075 0, /*nb_or*/
2076 float_coerce, /*nb_coerce*/
2077 float_trunc, /*nb_int*/
2078 float_long, /*nb_long*/
2079 float_float, /*nb_float*/
2080 0, /* nb_oct */
2081 0, /* nb_hex */
2082 0, /* nb_inplace_add */
2083 0, /* nb_inplace_subtract */
2084 0, /* nb_inplace_multiply */
2085 0, /* nb_inplace_divide */
2086 0, /* nb_inplace_remainder */
2087 0, /* nb_inplace_power */
2088 0, /* nb_inplace_lshift */
2089 0, /* nb_inplace_rshift */
2090 0, /* nb_inplace_and */
2091 0, /* nb_inplace_xor */
2092 0, /* nb_inplace_or */
2093 float_floor_div, /* nb_floor_divide */
2094 float_div, /* nb_true_divide */
2095 0, /* nb_inplace_floor_divide */
2096 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002097};
2098
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099PyTypeObject PyFloat_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002100 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2101 "float",
2102 sizeof(PyFloatObject),
2103 0,
2104 (destructor)float_dealloc, /* tp_dealloc */
2105 (printfunc)float_print, /* tp_print */
2106 0, /* tp_getattr */
2107 0, /* tp_setattr */
2108 0, /* tp_compare */
2109 (reprfunc)float_repr, /* tp_repr */
2110 &float_as_number, /* tp_as_number */
2111 0, /* tp_as_sequence */
2112 0, /* tp_as_mapping */
2113 (hashfunc)float_hash, /* tp_hash */
2114 0, /* tp_call */
2115 (reprfunc)float_str, /* tp_str */
2116 PyObject_GenericGetAttr, /* tp_getattro */
2117 0, /* tp_setattro */
2118 0, /* tp_as_buffer */
2119 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2120 Py_TPFLAGS_BASETYPE, /* tp_flags */
2121 float_doc, /* tp_doc */
2122 0, /* tp_traverse */
2123 0, /* tp_clear */
2124 float_richcompare, /* tp_richcompare */
2125 0, /* tp_weaklistoffset */
2126 0, /* tp_iter */
2127 0, /* tp_iternext */
2128 float_methods, /* tp_methods */
2129 0, /* tp_members */
2130 float_getset, /* tp_getset */
2131 0, /* tp_base */
2132 0, /* tp_dict */
2133 0, /* tp_descr_get */
2134 0, /* tp_descr_set */
2135 0, /* tp_dictoffset */
2136 0, /* tp_init */
2137 0, /* tp_alloc */
2138 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002139};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002140
2141void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002142_PyFloat_Init(void)
2143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002144 /* We attempt to determine if this machine is using IEEE
2145 floating point formats by peering at the bits of some
2146 carefully chosen values. If it looks like we are on an
2147 IEEE platform, the float packing/unpacking routines can
2148 just copy bits, if not they resort to arithmetic & shifts
2149 and masks. The shifts & masks approach works on all finite
2150 values, but what happens to infinities, NaNs and signed
2151 zeroes on packing is an accident, and attempting to unpack
2152 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002153
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002154 Note that if we're on some whacked-out platform which uses
2155 IEEE formats but isn't strictly little-endian or big-
2156 endian, we will fall back to the portable shifts & masks
2157 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002158
2159#if SIZEOF_DOUBLE == 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002160 {
2161 double x = 9006104071832581.0;
2162 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2163 detected_double_format = ieee_big_endian_format;
2164 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2165 detected_double_format = ieee_little_endian_format;
2166 else
2167 detected_double_format = unknown_format;
2168 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002169#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171#endif
2172
2173#if SIZEOF_FLOAT == 4
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002174 {
2175 float y = 16711938.0;
2176 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2177 detected_float_format = ieee_big_endian_format;
2178 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2179 detected_float_format = ieee_little_endian_format;
2180 else
2181 detected_float_format = unknown_format;
2182 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002183#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002185#endif
2186
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002187 double_format = detected_double_format;
2188 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00002189
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002190 /* Init float info */
2191 if (FloatInfoType.tp_name == 0)
2192 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002193}
2194
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002195int
2196PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002197{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002198 PyFloatObject *p;
2199 PyFloatBlock *list, *next;
2200 int i;
2201 int u; /* remaining unfreed ints per block */
2202 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002203
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002204 list = block_list;
2205 block_list = NULL;
2206 free_list = NULL;
2207 while (list != NULL) {
2208 u = 0;
2209 for (i = 0, p = &list->objects[0];
2210 i < N_FLOATOBJECTS;
2211 i++, p++) {
2212 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
2213 u++;
2214 }
2215 next = list->next;
2216 if (u) {
2217 list->next = block_list;
2218 block_list = list;
2219 for (i = 0, p = &list->objects[0];
2220 i < N_FLOATOBJECTS;
2221 i++, p++) {
2222 if (!PyFloat_CheckExact(p) ||
2223 Py_REFCNT(p) == 0) {
2224 Py_TYPE(p) = (struct _typeobject *)
2225 free_list;
2226 free_list = p;
2227 }
2228 }
2229 }
2230 else {
2231 PyMem_FREE(list);
2232 }
2233 freelist_size += u;
2234 list = next;
2235 }
2236 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002237}
2238
2239void
2240PyFloat_Fini(void)
2241{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002242 PyFloatObject *p;
2243 PyFloatBlock *list;
2244 int i;
2245 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002247 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002249 if (!Py_VerboseFlag)
2250 return;
2251 fprintf(stderr, "# cleanup floats");
2252 if (!u) {
2253 fprintf(stderr, "\n");
2254 }
2255 else {
2256 fprintf(stderr,
2257 ": %d unfreed float%s\n",
2258 u, u == 1 ? "" : "s");
2259 }
2260 if (Py_VerboseFlag > 1) {
2261 list = block_list;
2262 while (list != NULL) {
2263 for (i = 0, p = &list->objects[0];
2264 i < N_FLOATOBJECTS;
2265 i++, p++) {
2266 if (PyFloat_CheckExact(p) &&
2267 Py_REFCNT(p) != 0) {
2268 char *buf = PyOS_double_to_string(
2269 PyFloat_AS_DOUBLE(p), 'r',
2270 0, 0, NULL);
2271 if (buf) {
2272 /* XXX(twouters) cast
2273 refcount to long
2274 until %zd is
2275 universally
2276 available
2277 */
2278 fprintf(stderr,
2279 "# <float at %p, refcnt=%ld, val=%s>\n",
2280 p, (long)Py_REFCNT(p), buf);
2281 PyMem_Free(buf);
2282 }
2283 }
2284 }
2285 list = list->next;
2286 }
2287 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002288}
Tim Peters9905b942003-03-20 20:53:32 +00002289
2290/*----------------------------------------------------------------------------
2291 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002292 */
2293int
2294_PyFloat_Pack4(double x, unsigned char *p, int le)
2295{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002296 if (float_format == unknown_format) {
2297 unsigned char sign;
2298 int e;
2299 double f;
2300 unsigned int fbits;
2301 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002302
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002303 if (le) {
2304 p += 3;
2305 incr = -1;
2306 }
Tim Peters9905b942003-03-20 20:53:32 +00002307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002308 if (x < 0) {
2309 sign = 1;
2310 x = -x;
2311 }
2312 else
2313 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002316
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002317 /* Normalize f to be in the range [1.0, 2.0) */
2318 if (0.5 <= f && f < 1.0) {
2319 f *= 2.0;
2320 e--;
2321 }
2322 else if (f == 0.0)
2323 e = 0;
2324 else {
2325 PyErr_SetString(PyExc_SystemError,
2326 "frexp() result out of range");
2327 return -1;
2328 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002329
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002330 if (e >= 128)
2331 goto Overflow;
2332 else if (e < -126) {
2333 /* Gradual underflow */
2334 f = ldexp(f, 126 + e);
2335 e = 0;
2336 }
2337 else if (!(e == 0 && f == 0.0)) {
2338 e += 127;
2339 f -= 1.0; /* Get rid of leading 1 */
2340 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002341
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002342 f *= 8388608.0; /* 2**23 */
2343 fbits = (unsigned int)(f + 0.5); /* Round */
2344 assert(fbits <= 8388608);
2345 if (fbits >> 23) {
2346 /* The carry propagated out of a string of 23 1 bits. */
2347 fbits = 0;
2348 ++e;
2349 if (e >= 255)
2350 goto Overflow;
2351 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002353 /* First byte */
2354 *p = (sign << 7) | (e >> 1);
2355 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002357 /* Second byte */
2358 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2359 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002361 /* Third byte */
2362 *p = (fbits >> 8) & 0xFF;
2363 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002365 /* Fourth byte */
2366 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002367
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002368 /* Done */
2369 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 }
2372 else {
2373 float y = (float)x;
2374 const char *s = (char*)&y;
2375 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002376
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002377 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2378 goto Overflow;
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002379
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002380 if ((float_format == ieee_little_endian_format && !le)
2381 || (float_format == ieee_big_endian_format && le)) {
2382 p += 3;
2383 incr = -1;
2384 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002385
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002386 for (i = 0; i < 4; i++) {
2387 *p = *s++;
2388 p += incr;
2389 }
2390 return 0;
2391 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002392 Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002393 PyErr_SetString(PyExc_OverflowError,
2394 "float too large to pack with f format");
2395 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002396}
2397
2398int
2399_PyFloat_Pack8(double x, unsigned char *p, int le)
2400{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002401 if (double_format == unknown_format) {
2402 unsigned char sign;
2403 int e;
2404 double f;
2405 unsigned int fhi, flo;
2406 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002407
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002408 if (le) {
2409 p += 7;
2410 incr = -1;
2411 }
Tim Peters9905b942003-03-20 20:53:32 +00002412
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002413 if (x < 0) {
2414 sign = 1;
2415 x = -x;
2416 }
2417 else
2418 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002419
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002420 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002421
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002422 /* Normalize f to be in the range [1.0, 2.0) */
2423 if (0.5 <= f && f < 1.0) {
2424 f *= 2.0;
2425 e--;
2426 }
2427 else if (f == 0.0)
2428 e = 0;
2429 else {
2430 PyErr_SetString(PyExc_SystemError,
2431 "frexp() result out of range");
2432 return -1;
2433 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002434
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002435 if (e >= 1024)
2436 goto Overflow;
2437 else if (e < -1022) {
2438 /* Gradual underflow */
2439 f = ldexp(f, 1022 + e);
2440 e = 0;
2441 }
2442 else if (!(e == 0 && f == 0.0)) {
2443 e += 1023;
2444 f -= 1.0; /* Get rid of leading 1 */
2445 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002446
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002447 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2448 f *= 268435456.0; /* 2**28 */
2449 fhi = (unsigned int)f; /* Truncate */
2450 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002451
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002452 f -= (double)fhi;
2453 f *= 16777216.0; /* 2**24 */
2454 flo = (unsigned int)(f + 0.5); /* Round */
2455 assert(flo <= 16777216);
2456 if (flo >> 24) {
2457 /* The carry propagated out of a string of 24 1 bits. */
2458 flo = 0;
2459 ++fhi;
2460 if (fhi >> 28) {
2461 /* And it also progagated out of the next 28 bits. */
2462 fhi = 0;
2463 ++e;
2464 if (e >= 2047)
2465 goto Overflow;
2466 }
2467 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002468
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002469 /* First byte */
2470 *p = (sign << 7) | (e >> 4);
2471 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002472
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002473 /* Second byte */
2474 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2475 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002477 /* Third byte */
2478 *p = (fhi >> 16) & 0xFF;
2479 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002481 /* Fourth byte */
2482 *p = (fhi >> 8) & 0xFF;
2483 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002485 /* Fifth byte */
2486 *p = fhi & 0xFF;
2487 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002488
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002489 /* Sixth byte */
2490 *p = (flo >> 16) & 0xFF;
2491 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002492
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002493 /* Seventh byte */
2494 *p = (flo >> 8) & 0xFF;
2495 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002496
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002497 /* Eighth byte */
2498 *p = flo & 0xFF;
2499 /* p += incr; Unneeded (for now) */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002500
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002501 /* Done */
2502 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002504 Overflow:
2505 PyErr_SetString(PyExc_OverflowError,
2506 "float too large to pack with d format");
2507 return -1;
2508 }
2509 else {
2510 const char *s = (char*)&x;
2511 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002512
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002513 if ((double_format == ieee_little_endian_format && !le)
2514 || (double_format == ieee_big_endian_format && le)) {
2515 p += 7;
2516 incr = -1;
2517 }
2518
2519 for (i = 0; i < 8; i++) {
2520 *p = *s++;
2521 p += incr;
2522 }
2523 return 0;
2524 }
Tim Peters9905b942003-03-20 20:53:32 +00002525}
2526
2527double
2528_PyFloat_Unpack4(const unsigned char *p, int le)
2529{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002530 if (float_format == unknown_format) {
2531 unsigned char sign;
2532 int e;
2533 unsigned int f;
2534 double x;
2535 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002536
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002537 if (le) {
2538 p += 3;
2539 incr = -1;
2540 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002541
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002542 /* First byte */
2543 sign = (*p >> 7) & 1;
2544 e = (*p & 0x7F) << 1;
2545 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002546
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002547 /* Second byte */
2548 e |= (*p >> 7) & 1;
2549 f = (*p & 0x7F) << 16;
2550 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002551
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002552 if (e == 255) {
2553 PyErr_SetString(
2554 PyExc_ValueError,
2555 "can't unpack IEEE 754 special value "
2556 "on non-IEEE platform");
2557 return -1;
2558 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002560 /* Third byte */
2561 f |= *p << 8;
2562 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002564 /* Fourth byte */
2565 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002566
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002567 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002568
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002569 /* XXX This sadly ignores Inf/NaN issues */
2570 if (e == 0)
2571 e = -126;
2572 else {
2573 x += 1.0;
2574 e -= 127;
2575 }
2576 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002577
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002578 if (sign)
2579 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002581 return x;
2582 }
2583 else {
2584 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002585
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002586 if ((float_format == ieee_little_endian_format && !le)
2587 || (float_format == ieee_big_endian_format && le)) {
2588 char buf[4];
2589 char *d = &buf[3];
2590 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002591
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002592 for (i = 0; i < 4; i++) {
2593 *d-- = *p++;
2594 }
2595 memcpy(&x, buf, 4);
2596 }
2597 else {
2598 memcpy(&x, p, 4);
2599 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002600
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002601 return x;
2602 }
Tim Peters9905b942003-03-20 20:53:32 +00002603}
2604
2605double
2606_PyFloat_Unpack8(const unsigned char *p, int le)
2607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002608 if (double_format == unknown_format) {
2609 unsigned char sign;
2610 int e;
2611 unsigned int fhi, flo;
2612 double x;
2613 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002614
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002615 if (le) {
2616 p += 7;
2617 incr = -1;
2618 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002619
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002620 /* First byte */
2621 sign = (*p >> 7) & 1;
2622 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002623
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002624 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 /* Second byte */
2627 e |= (*p >> 4) & 0xF;
2628 fhi = (*p & 0xF) << 24;
2629 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002631 if (e == 2047) {
2632 PyErr_SetString(
2633 PyExc_ValueError,
2634 "can't unpack IEEE 754 special value "
2635 "on non-IEEE platform");
2636 return -1.0;
2637 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002638
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002639 /* Third byte */
2640 fhi |= *p << 16;
2641 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002642
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002643 /* Fourth byte */
2644 fhi |= *p << 8;
2645 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002646
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002647 /* Fifth byte */
2648 fhi |= *p;
2649 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002650
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002651 /* Sixth byte */
2652 flo = *p << 16;
2653 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002655 /* Seventh byte */
2656 flo |= *p << 8;
2657 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002658
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002659 /* Eighth byte */
2660 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002662 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2663 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 if (e == 0)
2666 e = -1022;
2667 else {
2668 x += 1.0;
2669 e -= 1023;
2670 }
2671 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002672
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002673 if (sign)
2674 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002675
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002676 return x;
2677 }
2678 else {
2679 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002680
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002681 if ((double_format == ieee_little_endian_format && !le)
2682 || (double_format == ieee_big_endian_format && le)) {
2683 char buf[8];
2684 char *d = &buf[7];
2685 int i;
2686
2687 for (i = 0; i < 8; i++) {
2688 *d-- = *p++;
2689 }
2690 memcpy(&x, buf, 8);
2691 }
2692 else {
2693 memcpy(&x, p, 8);
2694 }
2695
2696 return x;
2697 }
Tim Peters9905b942003-03-20 20:53:32 +00002698}