blob: 82f996067b5eccca8b7006af1fd055a65e86b171 [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;
Serhiy Storchaka61565602015-11-20 21:56:21 +0200183 PyObject *str = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000184 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000185
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000186 if (pend)
187 *pend = NULL;
188 if (PyString_Check(v)) {
189 s = PyString_AS_STRING(v);
190 len = PyString_GET_SIZE(v);
191 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000192#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000193 else if (PyUnicode_Check(v)) {
194 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
195 if (s_buffer == NULL)
196 return PyErr_NoMemory();
197 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
198 PyUnicode_GET_SIZE(v),
199 s_buffer,
200 NULL))
201 goto error;
202 s = s_buffer;
203 len = strlen(s);
204 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000205#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +0200206 else if (!PyObject_AsCharBuffer(v, &s, &len)) {
207 /* Copy to NUL-terminated buffer. */
208 str = PyString_FromStringAndSize(s, len);
209 if (str == NULL)
210 return NULL;
211 s = PyString_AS_STRING(str);
212 }
213 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000214 PyErr_SetString(PyExc_TypeError,
215 "float() argument must be a string or a number");
216 return NULL;
217 }
218 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000219
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 while (Py_ISSPACE(*s))
221 s++;
222 /* We don't care about overflow or underflow. If the platform
223 * supports them, infinities and signed zeroes (on underflow) are
224 * fine. */
225 x = PyOS_string_to_double(s, (char **)&end, NULL);
226 if (x == -1.0 && PyErr_Occurred())
227 goto error;
228 while (Py_ISSPACE(*end))
229 end++;
230 if (end == last)
231 result = PyFloat_FromDouble(x);
232 else {
233 PyOS_snprintf(buffer, sizeof(buffer),
234 "invalid literal for float(): %.200s", s);
235 PyErr_SetString(PyExc_ValueError, buffer);
236 result = NULL;
237 }
Mark Dickinson8568b192009-10-26 21:11:20 +0000238
239 error:
240#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000241 if (s_buffer)
242 PyMem_FREE(s_buffer);
Mark Dickinson8568b192009-10-26 21:11:20 +0000243#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +0200244 Py_XDECREF(str);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000245 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000246}
247
Guido van Rossum234f9421993-06-17 12:35:49 +0000248static void
Fred Drakefd99de62000-07-09 05:02:18 +0000249float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000250{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 if (PyFloat_CheckExact(op)) {
252 Py_TYPE(op) = (struct _typeobject *)free_list;
253 free_list = op;
254 }
255 else
256 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000257}
258
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000259double
Fred Drakefd99de62000-07-09 05:02:18 +0000260PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 PyNumberMethods *nb;
263 PyFloatObject *fo;
264 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000265
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 if (op && PyFloat_Check(op))
267 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000268
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000269 if (op == NULL) {
270 PyErr_BadArgument();
271 return -1;
272 }
Tim Petersd2364e82001-11-01 20:09:42 +0000273
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000274 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
275 PyErr_SetString(PyExc_TypeError, "a float is required");
276 return -1;
277 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000278
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279 fo = (PyFloatObject*) (*nb->nb_float) (op);
280 if (fo == NULL)
281 return -1;
282 if (!PyFloat_Check(fo)) {
Benjamin Petersonf0506482015-03-06 09:08:44 -0500283 Py_DECREF(fo);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000284 PyErr_SetString(PyExc_TypeError,
285 "nb_float should return float object");
286 return -1;
287 }
Tim Petersd2364e82001-11-01 20:09:42 +0000288
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 val = PyFloat_AS_DOUBLE(fo);
290 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000291
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293}
294
295/* Methods */
296
Neil Schemenauer32117e52001-01-04 01:44:34 +0000297/* Macro and helper that convert PyObject obj to a C double and store
298 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000299 slot function. If conversion to double raises an exception, obj is
300 set to NULL, and the function invoking this macro returns NULL. If
301 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
302 stored in obj, and returned from the function invoking this macro.
303*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000304#define CONVERT_TO_DOUBLE(obj, dbl) \
305 if (PyFloat_Check(obj)) \
306 dbl = PyFloat_AS_DOUBLE(obj); \
307 else if (convert_to_double(&(obj), &(dbl)) < 0) \
308 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000309
310static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000311convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000312{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000313 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000314
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 if (PyInt_Check(obj)) {
316 *dbl = (double)PyInt_AS_LONG(obj);
317 }
318 else if (PyLong_Check(obj)) {
319 *dbl = PyLong_AsDouble(obj);
320 if (*dbl == -1.0 && PyErr_Occurred()) {
321 *v = NULL;
322 return -1;
323 }
324 }
325 else {
326 Py_INCREF(Py_NotImplemented);
327 *v = Py_NotImplemented;
328 return -1;
329 }
330 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000331}
332
Eric Smithcfaf79c2009-10-26 14:48:55 +0000333/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
Tim Peters97019e42001-11-28 22:43:45 +0000334 XXX they pass a char buffer without passing a length.
335*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000336void
Fred Drakefd99de62000-07-09 05:02:18 +0000337PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
340 PyFloat_STR_PRECISION,
341 Py_DTSF_ADD_DOT_0, NULL);
342 strcpy(buf, tmp);
343 PyMem_Free(tmp);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000344}
345
Tim Peters72f98e92001-05-08 15:19:57 +0000346void
347PyFloat_AsReprString(char *buf, PyFloatObject *v)
348{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
350 Py_DTSF_ADD_DOT_0, NULL);
351 strcpy(buf, tmp);
352 PyMem_Free(tmp);
Tim Peters72f98e92001-05-08 15:19:57 +0000353}
354
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000355/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000356static int
Fred Drakefd99de62000-07-09 05:02:18 +0000357float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000359 char *buf;
360 if (flags & Py_PRINT_RAW)
361 buf = PyOS_double_to_string(v->ob_fval,
362 'g', PyFloat_STR_PRECISION,
363 Py_DTSF_ADD_DOT_0, NULL);
364 else
365 buf = PyOS_double_to_string(v->ob_fval,
366 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
367 Py_BEGIN_ALLOW_THREADS
368 fputs(buf, fp);
369 Py_END_ALLOW_THREADS
370 PyMem_Free(buf);
371 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Eric Smithcfaf79c2009-10-26 14:48:55 +0000375float_str_or_repr(PyFloatObject *v, int precision, char format_code)
376{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 PyObject *result;
378 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
379 format_code, precision,
380 Py_DTSF_ADD_DOT_0,
381 NULL);
382 if (!buf)
383 return PyErr_NoMemory();
384 result = PyString_FromString(buf);
385 PyMem_Free(buf);
386 return result;
Eric Smithcfaf79c2009-10-26 14:48:55 +0000387}
388
389static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000390float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000392 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000393}
394
395static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000396float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000397{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Tim Peters307fa782004-09-23 08:06:40 +0000401/* Comparison is pretty much a nightmare. When comparing float to float,
402 * we do it as straightforwardly (and long-windedly) as conceivable, so
403 * that, e.g., Python x == y delivers the same result as the platform
404 * C x == y when x and/or y is a NaN.
405 * When mixing float with an integer type, there's no good *uniform* approach.
406 * Converting the double to an integer obviously doesn't work, since we
407 * may lose info from fractional bits. Converting the integer to a double
408 * also has two failure modes: (1) a long int may trigger overflow (too
409 * large to fit in the dynamic range of a C double); (2) even a C long may have
410 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
411 * 63 bits of precision, but a C double probably has only 53), and then
412 * we can falsely claim equality when low-order integer bits are lost by
413 * coercion to double. So this part is painful too.
414 */
415
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000416static PyObject*
417float_richcompare(PyObject *v, PyObject *w, int op)
418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000419 double i, j;
420 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000421
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 assert(PyFloat_Check(v));
423 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000424
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 /* Switch on the type of w. Set i and j to doubles to be compared,
426 * and op to the richcomp to use.
427 */
428 if (PyFloat_Check(w))
429 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000430
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000431 else if (!Py_IS_FINITE(i)) {
432 if (PyInt_Check(w) || PyLong_Check(w))
433 /* If i is an infinity, its magnitude exceeds any
434 * finite integer, so it doesn't matter which int we
435 * compare i with. If i is a NaN, similarly.
436 */
437 j = 0.0;
438 else
439 goto Unimplemented;
440 }
Tim Peters307fa782004-09-23 08:06:40 +0000441
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000442 else if (PyInt_Check(w)) {
443 long jj = PyInt_AS_LONG(w);
444 /* In the worst realistic case I can imagine, C double is a
445 * Cray single with 48 bits of precision, and long has 64
446 * bits.
447 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000448#if SIZEOF_LONG > 6
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000449 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
450 if (abs >> 48) {
451 /* Needs more than 48 bits. Make it take the
452 * PyLong path.
453 */
454 PyObject *result;
455 PyObject *ww = PyLong_FromLong(jj);
Tim Peters307fa782004-09-23 08:06:40 +0000456
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000457 if (ww == NULL)
458 return NULL;
459 result = float_richcompare(v, ww, op);
460 Py_DECREF(ww);
461 return result;
462 }
Tim Peters307fa782004-09-23 08:06:40 +0000463#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 j = (double)jj;
465 assert((long)j == jj);
466 }
Tim Peters307fa782004-09-23 08:06:40 +0000467
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 else if (PyLong_Check(w)) {
469 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
470 int wsign = _PyLong_Sign(w);
471 size_t nbits;
472 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000473
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 if (vsign != wsign) {
475 /* Magnitudes are irrelevant -- the signs alone
476 * determine the outcome.
477 */
478 i = (double)vsign;
479 j = (double)wsign;
480 goto Compare;
481 }
482 /* The signs are the same. */
483 /* Convert w to a double if it fits. In particular, 0 fits. */
484 nbits = _PyLong_NumBits(w);
485 if (nbits == (size_t)-1 && PyErr_Occurred()) {
486 /* This long is so large that size_t isn't big enough
487 * to hold the # of bits. Replace with little doubles
488 * that give the same outcome -- w is so large that
489 * its magnitude must exceed the magnitude of any
490 * finite float.
491 */
492 PyErr_Clear();
493 i = (double)vsign;
494 assert(wsign != 0);
495 j = wsign * 2.0;
496 goto Compare;
497 }
498 if (nbits <= 48) {
499 j = PyLong_AsDouble(w);
500 /* It's impossible that <= 48 bits overflowed. */
501 assert(j != -1.0 || ! PyErr_Occurred());
502 goto Compare;
503 }
504 assert(wsign != 0); /* else nbits was 0 */
505 assert(vsign != 0); /* if vsign were 0, then since wsign is
506 * not 0, we would have taken the
507 * vsign != wsign branch at the start */
508 /* We want to work with non-negative numbers. */
509 if (vsign < 0) {
510 /* "Multiply both sides" by -1; this also swaps the
511 * comparator.
512 */
513 i = -i;
514 op = _Py_SwappedOp[op];
515 }
516 assert(i > 0.0);
517 (void) frexp(i, &exponent);
518 /* exponent is the # of bits in v before the radix point;
519 * we know that nbits (the # of bits in w) > 48 at this point
520 */
521 if (exponent < 0 || (size_t)exponent < nbits) {
522 i = 1.0;
523 j = 2.0;
524 goto Compare;
525 }
526 if ((size_t)exponent > nbits) {
527 i = 2.0;
528 j = 1.0;
529 goto Compare;
530 }
531 /* v and w have the same number of bits before the radix
532 * point. Construct two longs that have the same comparison
533 * outcome.
534 */
535 {
536 double fracpart;
537 double intpart;
538 PyObject *result = NULL;
539 PyObject *one = NULL;
540 PyObject *vv = NULL;
541 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000542
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 if (wsign < 0) {
544 ww = PyNumber_Negative(w);
545 if (ww == NULL)
546 goto Error;
547 }
548 else
549 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000550
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000551 fracpart = modf(i, &intpart);
552 vv = PyLong_FromDouble(intpart);
553 if (vv == NULL)
554 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000555
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000556 if (fracpart != 0.0) {
557 /* Shift left, and or a 1 bit into vv
558 * to represent the lost fraction.
559 */
560 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000561
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000562 one = PyInt_FromLong(1);
563 if (one == NULL)
564 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000565
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000566 temp = PyNumber_Lshift(ww, one);
567 if (temp == NULL)
568 goto Error;
569 Py_DECREF(ww);
570 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000571
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000572 temp = PyNumber_Lshift(vv, one);
573 if (temp == NULL)
574 goto Error;
575 Py_DECREF(vv);
576 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000577
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000578 temp = PyNumber_Or(vv, one);
579 if (temp == NULL)
580 goto Error;
581 Py_DECREF(vv);
582 vv = temp;
583 }
Tim Peters307fa782004-09-23 08:06:40 +0000584
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000585 r = PyObject_RichCompareBool(vv, ww, op);
586 if (r < 0)
587 goto Error;
588 result = PyBool_FromLong(r);
589 Error:
590 Py_XDECREF(vv);
591 Py_XDECREF(ww);
592 Py_XDECREF(one);
593 return result;
594 }
595 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000596
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 else /* w isn't float, int, or long */
598 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000599
600 Compare:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000601 PyFPE_START_PROTECT("richcompare", return NULL)
602 switch (op) {
603 case Py_EQ:
604 r = i == j;
605 break;
606 case Py_NE:
607 r = i != j;
608 break;
609 case Py_LE:
610 r = i <= j;
611 break;
612 case Py_GE:
613 r = i >= j;
614 break;
615 case Py_LT:
616 r = i < j;
617 break;
618 case Py_GT:
619 r = i > j;
620 break;
621 }
622 PyFPE_END_PROTECT(r)
623 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000624
625 Unimplemented:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000626 Py_INCREF(Py_NotImplemented);
627 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000628}
629
Guido van Rossum9bfef441993-03-29 10:43:31 +0000630static long
Fred Drakefd99de62000-07-09 05:02:18 +0000631float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000632{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000633 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000634}
635
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000636static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000637float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 double a,b;
640 CONVERT_TO_DOUBLE(v, a);
641 CONVERT_TO_DOUBLE(w, b);
642 PyFPE_START_PROTECT("add", return 0)
643 a = a + b;
644 PyFPE_END_PROTECT(a)
645 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646}
647
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000648static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000649float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000650{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 double a,b;
652 CONVERT_TO_DOUBLE(v, a);
653 CONVERT_TO_DOUBLE(w, b);
654 PyFPE_START_PROTECT("subtract", return 0)
655 a = a - b;
656 PyFPE_END_PROTECT(a)
657 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000658}
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000661float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 double a,b;
664 CONVERT_TO_DOUBLE(v, a);
665 CONVERT_TO_DOUBLE(w, b);
666 PyFPE_START_PROTECT("multiply", return 0)
667 a = a * b;
668 PyFPE_END_PROTECT(a)
669 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000670}
671
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000672static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000673float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 double a,b;
676 CONVERT_TO_DOUBLE(v, a);
677 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000678#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000679 if (b == 0.0) {
680 PyErr_SetString(PyExc_ZeroDivisionError,
681 "float division by zero");
682 return NULL;
683 }
Christian Heimes6f341092008-04-18 23:13:07 +0000684#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000685 PyFPE_START_PROTECT("divide", return 0)
686 a = a / b;
687 PyFPE_END_PROTECT(a)
688 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000689}
690
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000692float_classic_div(PyObject *v, PyObject *w)
693{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000694 double a,b;
695 CONVERT_TO_DOUBLE(v, a);
696 CONVERT_TO_DOUBLE(w, b);
697 if (Py_DivisionWarningFlag >= 2 &&
698 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
699 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000700#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000701 if (b == 0.0) {
702 PyErr_SetString(PyExc_ZeroDivisionError,
703 "float division by zero");
704 return NULL;
705 }
Christian Heimes6f341092008-04-18 23:13:07 +0000706#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 PyFPE_START_PROTECT("divide", return 0)
708 a = a / b;
709 PyFPE_END_PROTECT(a)
710 return PyFloat_FromDouble(a);
Guido van Rossum393661d2001-08-31 17:40:15 +0000711}
712
713static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000714float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 double vx, wx;
717 double mod;
718 CONVERT_TO_DOUBLE(v, vx);
719 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes6f341092008-04-18 23:13:07 +0000720#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721 if (wx == 0.0) {
722 PyErr_SetString(PyExc_ZeroDivisionError,
723 "float modulo");
724 return NULL;
725 }
Christian Heimes6f341092008-04-18 23:13:07 +0000726#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000727 PyFPE_START_PROTECT("modulo", return 0)
728 mod = fmod(vx, wx);
Mark Dickinsonecf8ec62010-12-04 12:30:41 +0000729 if (mod) {
730 /* ensure the remainder has the same sign as the denominator */
731 if ((wx < 0) != (mod < 0)) {
732 mod += wx;
733 }
734 }
735 else {
736 /* the remainder is zero, and in the presence of signed zeroes
737 fmod returns different results across platforms; ensure
738 it has the same sign as the denominator; we'd like to do
739 "mod = wx * 0.0", but that may get optimized away */
740 mod *= mod; /* hide "mod = +0" from optimizer */
741 if (wx < 0.0)
742 mod = -mod;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 }
744 PyFPE_END_PROTECT(mod)
745 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000746}
747
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000749float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000750{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 double vx, wx;
752 double div, mod, floordiv;
753 CONVERT_TO_DOUBLE(v, vx);
754 CONVERT_TO_DOUBLE(w, wx);
755 if (wx == 0.0) {
756 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
757 return NULL;
758 }
759 PyFPE_START_PROTECT("divmod", return 0)
760 mod = fmod(vx, wx);
761 /* fmod is typically exact, so vx-mod is *mathematically* an
762 exact multiple of wx. But this is fp arithmetic, and fp
763 vx - mod is an approximation; the result is that div may
764 not be an exact integral value after the division, although
765 it will always be very close to one.
766 */
767 div = (vx - mod) / wx;
768 if (mod) {
769 /* ensure the remainder has the same sign as the denominator */
770 if ((wx < 0) != (mod < 0)) {
771 mod += wx;
772 div -= 1.0;
773 }
774 }
775 else {
776 /* the remainder is zero, and in the presence of signed zeroes
777 fmod returns different results across platforms; ensure
778 it has the same sign as the denominator; we'd like to do
779 "mod = wx * 0.0", but that may get optimized away */
780 mod *= mod; /* hide "mod = +0" from optimizer */
781 if (wx < 0.0)
782 mod = -mod;
783 }
784 /* snap quotient to nearest integral value */
785 if (div) {
786 floordiv = floor(div);
787 if (div - floordiv > 0.5)
788 floordiv += 1.0;
789 }
790 else {
791 /* div is zero - get the same sign as the true quotient */
792 div *= div; /* hide "div = +0" from optimizers */
793 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
794 }
795 PyFPE_END_PROTECT(floordiv)
796 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000797}
798
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000799static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000800float_floor_div(PyObject *v, PyObject *w)
801{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000802 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000803
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 t = float_divmod(v, w);
805 if (t == NULL || t == Py_NotImplemented)
806 return t;
807 assert(PyTuple_CheckExact(t));
808 r = PyTuple_GET_ITEM(t, 0);
809 Py_INCREF(r);
810 Py_DECREF(t);
811 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000812}
813
Mark Dickinson99d652e2009-12-30 12:12:23 +0000814/* determine whether x is an odd integer or not; assumes that
815 x is not an infinity or nan. */
816#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
817
Tim Peters63a35712001-12-11 19:57:24 +0000818static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000819float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000821 double iv, iw, ix;
822 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000823
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 if ((PyObject *)z != Py_None) {
825 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
826 "allowed unless all arguments are integers");
827 return NULL;
828 }
Tim Peters32f453e2001-09-03 08:35:41 +0000829
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000830 CONVERT_TO_DOUBLE(v, iv);
831 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000832
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000833 /* Sort out special cases here instead of relying on pow() */
834 if (iw == 0) { /* v**0 is 1, even 0**0 */
835 return PyFloat_FromDouble(1.0);
836 }
837 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
838 return PyFloat_FromDouble(iv);
839 }
840 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
841 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
842 }
843 if (Py_IS_INFINITY(iw)) {
844 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
845 * abs(v) > 1 (including case where v infinite)
846 *
847 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
848 * abs(v) > 1 (including case where v infinite)
849 */
850 iv = fabs(iv);
851 if (iv == 1.0)
852 return PyFloat_FromDouble(1.0);
853 else if ((iw > 0.0) == (iv > 1.0))
854 return PyFloat_FromDouble(fabs(iw)); /* return inf */
855 else
856 return PyFloat_FromDouble(0.0);
857 }
858 if (Py_IS_INFINITY(iv)) {
859 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
860 * both cases, we need to add the appropriate sign if w is
861 * an odd integer.
862 */
863 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
864 if (iw > 0.0)
865 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
866 else
867 return PyFloat_FromDouble(iw_is_odd ?
868 copysign(0.0, iv) : 0.0);
869 }
870 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
871 (already dealt with above), and an error
872 if w is negative. */
873 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
874 if (iw < 0.0) {
875 PyErr_SetString(PyExc_ZeroDivisionError,
876 "0.0 cannot be raised to a "
877 "negative power");
878 return NULL;
879 }
880 /* use correct sign if iw is odd */
881 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
882 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000883
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000884 if (iv < 0.0) {
885 /* Whether this is an error is a mess, and bumps into libm
886 * bugs so we have to figure it out ourselves.
887 */
888 if (iw != floor(iw)) {
889 PyErr_SetString(PyExc_ValueError, "negative number "
890 "cannot be raised to a fractional power");
891 return NULL;
892 }
893 /* iw is an exact integer, albeit perhaps a very large
894 * one. Replace iv by its absolute value and remember
895 * to negate the pow result if iw is odd.
896 */
897 iv = -iv;
898 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
899 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000900
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000901 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
902 /* (-1) ** large_integer also ends up here. Here's an
903 * extract from the comments for the previous
904 * implementation explaining why this special case is
905 * necessary:
906 *
907 * -1 raised to an exact integer should never be exceptional.
908 * Alas, some libms (chiefly glibc as of early 2003) return
909 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
910 * happen to be representable in a *C* integer. That's a
911 * bug.
912 */
913 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
914 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000915
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000916 /* Now iv and iw are finite, iw is nonzero, and iv is
917 * positive and not equal to 1.0. We finally allow
918 * the platform pow to step in and do the rest.
919 */
920 errno = 0;
921 PyFPE_START_PROTECT("pow", return NULL)
922 ix = pow(iv, iw);
923 PyFPE_END_PROTECT(ix)
924 Py_ADJUST_ERANGE1(ix);
925 if (negate_result)
926 ix = -ix;
Mark Dickinson99d652e2009-12-30 12:12:23 +0000927
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 if (errno != 0) {
929 /* We don't expect any errno value other than ERANGE, but
930 * the range of libm bugs appears unbounded.
931 */
932 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
933 PyExc_ValueError);
934 return NULL;
935 }
936 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000937}
938
Mark Dickinson99d652e2009-12-30 12:12:23 +0000939#undef DOUBLE_IS_ODD_INTEGER
940
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000942float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000945}
946
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000947static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000948float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000949{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000951}
952
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000953static int
Fred Drakefd99de62000-07-09 05:02:18 +0000954float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000955{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000956 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000957}
958
Guido van Rossum234f9421993-06-17 12:35:49 +0000959static int
Fred Drakefd99de62000-07-09 05:02:18 +0000960float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000961{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 if (PyInt_Check(*pw)) {
963 long x = PyInt_AsLong(*pw);
964 *pw = PyFloat_FromDouble((double)x);
965 Py_INCREF(*pv);
966 return 0;
967 }
968 else if (PyLong_Check(*pw)) {
969 double x = PyLong_AsDouble(*pw);
970 if (x == -1.0 && PyErr_Occurred())
971 return -1;
972 *pw = PyFloat_FromDouble(x);
973 Py_INCREF(*pv);
974 return 0;
975 }
976 else if (PyFloat_Check(*pw)) {
977 Py_INCREF(*pv);
978 Py_INCREF(*pw);
979 return 0;
980 }
981 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +0000982}
983
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000985float_is_integer(PyObject *v)
986{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000987 double x = PyFloat_AsDouble(v);
988 PyObject *o;
989
990 if (x == -1.0 && PyErr_Occurred())
991 return NULL;
992 if (!Py_IS_FINITE(x))
993 Py_RETURN_FALSE;
994 errno = 0;
995 PyFPE_START_PROTECT("is_integer", return NULL)
996 o = (floor(x) == x) ? Py_True : Py_False;
997 PyFPE_END_PROTECT(x)
998 if (errno != 0) {
999 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1000 PyExc_ValueError);
1001 return NULL;
1002 }
1003 Py_INCREF(o);
1004 return o;
Christian Heimes6f341092008-04-18 23:13:07 +00001005}
1006
1007#if 0
1008static PyObject *
1009float_is_inf(PyObject *v)
1010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 double x = PyFloat_AsDouble(v);
1012 if (x == -1.0 && PyErr_Occurred())
1013 return NULL;
1014 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001015}
1016
1017static PyObject *
1018float_is_nan(PyObject *v)
1019{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 double x = PyFloat_AsDouble(v);
1021 if (x == -1.0 && PyErr_Occurred())
1022 return NULL;
1023 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001024}
1025
1026static PyObject *
1027float_is_finite(PyObject *v)
1028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 double x = PyFloat_AsDouble(v);
1030 if (x == -1.0 && PyErr_Occurred())
1031 return NULL;
1032 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001033}
1034#endif
1035
1036static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001037float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001038{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001039 double x = PyFloat_AsDouble(v);
1040 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001042 (void)modf(x, &wholepart);
1043 /* Try to get out cheap if this fits in a Python int. The attempt
1044 * to cast to long must be protected, as C doesn't define what
1045 * happens if the double is too big to fit in a long. Some rare
1046 * systems raise an exception then (RISCOS was mentioned as one,
1047 * and someone using a non-default option on Sun also bumped into
Mark Dickinson874d59e2011-03-26 12:18:00 +00001048 * that). Note that checking for <= LONG_MAX is unsafe: if a long
1049 * has more bits of precision than a double, casting LONG_MAX to
1050 * double may yield an approximation, and if that's rounded up,
1051 * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
1052 * expression wholepart<=LONG_MAX, despite that wholepart is
1053 * actually greater than LONG_MAX. However, assuming a two's complement
1054 * machine with no trap representation, LONG_MIN will be a power of 2 (and
1055 * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
1056 * the comparisons with (double)LONG_MIN below should be safe.
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001057 */
Mark Dickinson874d59e2011-03-26 12:18:00 +00001058 if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 const long aslong = (long)wholepart;
1060 return PyInt_FromLong(aslong);
1061 }
1062 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001063}
1064
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001065static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001066float_long(PyObject *v)
1067{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 double x = PyFloat_AsDouble(v);
1069 return PyLong_FromDouble(x);
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001070}
1071
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001072/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
1073 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1074 ndigits <= 323). Returns a Python float, or sets a Python error and
1075 returns NULL on failure (OverflowError and memory errors are possible). */
1076
1077#ifndef PY_NO_SHORT_FLOAT_REPR
1078/* version of _Py_double_round that uses the correctly-rounded string<->double
1079 conversions from Python/dtoa.c */
1080
1081/* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1082 a double. Since we're using the code in Python/dtoa.c, it should be safe
1083 to assume that C doubles are IEEE 754 binary64 format. To be on the safe
1084 side, we check this. */
1085#if DBL_MANT_DIG == 53
1086#define FIVE_POW_LIMIT 22
1087#else
1088#error "C doubles do not appear to be IEEE 754 binary64 format"
1089#endif
1090
1091PyObject *
1092_Py_double_round(double x, int ndigits) {
1093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 double rounded, m;
1095 Py_ssize_t buflen, mybuflen=100;
1096 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
1097 int decpt, sign, val, halfway_case;
1098 PyObject *result = NULL;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001099 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001100
Mark Dickinson115bc792012-11-17 20:18:52 +00001101 /* Easy path for the common case ndigits == 0. */
1102 if (ndigits == 0) {
1103 rounded = round(x);
1104 if (fabs(rounded - x) == 0.5)
1105 /* halfway between two integers; use round-away-from-zero */
1106 rounded = x + (x > 0.0 ? 0.5 : -0.5);
1107 return PyFloat_FromDouble(rounded);
1108 }
1109
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001110 /* The basic idea is very simple: convert and round the double to a
1111 decimal string using _Py_dg_dtoa, then convert that decimal string
1112 back to a double with _Py_dg_strtod. There's one minor difficulty:
1113 Python 2.x expects round to do round-half-away-from-zero, while
1114 _Py_dg_dtoa does round-half-to-even. So we need some way to detect
1115 and correct the halfway cases.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001116
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1118 some odd integer k. Or in other words, a rational number x is
1119 exactly halfway between two multiples of 10**-ndigits if its
1120 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1121 -ndigits. For ndigits >= 0 the latter condition is automatically
1122 satisfied for a binary float x, since any such float has
1123 nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
1124 integral multiple of 5**-ndigits; we can check this using fmod.
1125 For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1126 to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1127 23 takes at least 54 bits of precision to represent exactly.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001129 Correction: a simple strategy for dealing with halfway cases is to
1130 (for the halfway cases only) call _Py_dg_dtoa with an argument of
1131 ndigits+1 instead of ndigits (thus doing an exact conversion to
1132 decimal), round the resulting string manually, and then convert
1133 back using _Py_dg_strtod.
1134 */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001136 /* nans, infinities and zeros should have already been dealt
1137 with by the caller (in this case, builtin_round) */
1138 assert(Py_IS_FINITE(x) && x != 0.0);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001139
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001140 /* find 2-valuation val of x */
1141 m = frexp(x, &val);
1142 while (m != floor(m)) {
1143 m *= 2.0;
1144 val--;
1145 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001146
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 /* determine whether this is a halfway case */
1148 if (val == -ndigits-1) {
1149 if (ndigits >= 0)
1150 halfway_case = 1;
1151 else if (ndigits >= -FIVE_POW_LIMIT) {
1152 double five_pow = 1.0;
1153 int i;
1154 for (i=0; i < -ndigits; i++)
1155 five_pow *= 5.0;
1156 halfway_case = fmod(x, five_pow) == 0.0;
1157 }
1158 else
1159 halfway_case = 0;
1160 }
1161 else
1162 halfway_case = 0;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001163
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001164 /* round to a decimal string; use an extra place for halfway case */
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001165 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001166 buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001167 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001168 if (buf == NULL) {
1169 PyErr_NoMemory();
1170 return NULL;
1171 }
1172 buflen = buf_end - buf;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 /* in halfway case, do the round-half-away-from-zero manually */
1175 if (halfway_case) {
1176 int i, carry;
1177 /* sanity check: _Py_dg_dtoa should not have stripped
1178 any zeros from the result: there should be exactly
1179 ndigits+1 places following the decimal point, and
1180 the last digit in the buffer should be a '5'.*/
1181 assert(buflen - decpt == ndigits+1);
1182 assert(buf[buflen-1] == '5');
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001183
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001184 /* increment and shift right at the same time. */
1185 decpt += 1;
1186 carry = 1;
1187 for (i=buflen-1; i-- > 0;) {
1188 carry += buf[i] - '0';
1189 buf[i+1] = carry % 10 + '0';
1190 carry /= 10;
1191 }
1192 buf[0] = carry + '0';
1193 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001194
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001195 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
1196 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1197 if (buflen + 8 > mybuflen) {
1198 mybuflen = buflen+8;
1199 mybuf = (char *)PyMem_Malloc(mybuflen);
1200 if (mybuf == NULL) {
1201 PyErr_NoMemory();
1202 goto exit;
1203 }
1204 }
1205 /* copy buf to mybuf, adding exponent, sign and leading 0 */
1206 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
1207 buf, decpt - (int)buflen);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001208
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001209 /* and convert the resulting string back to a double */
1210 errno = 0;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001211 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001212 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001213 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001214 if (errno == ERANGE && fabs(rounded) >= 1.)
1215 PyErr_SetString(PyExc_OverflowError,
1216 "rounded value too large to represent");
1217 else
1218 result = PyFloat_FromDouble(rounded);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001220 /* done computing value; now clean up */
1221 if (mybuf != shortbuf)
1222 PyMem_Free(mybuf);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001223 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001224 _Py_dg_freedtoa(buf);
1225 return result;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001226}
1227
1228#undef FIVE_POW_LIMIT
1229
1230#else /* PY_NO_SHORT_FLOAT_REPR */
1231
1232/* fallback version, to be used when correctly rounded binary<->decimal
1233 conversions aren't available */
1234
1235PyObject *
1236_Py_double_round(double x, int ndigits) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001237 double pow1, pow2, y, z;
1238 if (ndigits >= 0) {
1239 if (ndigits > 22) {
1240 /* pow1 and pow2 are each safe from overflow, but
1241 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1242 pow1 = pow(10.0, (double)(ndigits-22));
1243 pow2 = 1e22;
1244 }
1245 else {
1246 pow1 = pow(10.0, (double)ndigits);
1247 pow2 = 1.0;
1248 }
1249 y = (x*pow1)*pow2;
1250 /* if y overflows, then rounded value is exactly x */
1251 if (!Py_IS_FINITE(y))
1252 return PyFloat_FromDouble(x);
1253 }
1254 else {
1255 pow1 = pow(10.0, (double)-ndigits);
1256 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1257 y = x / pow1;
1258 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001259
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001260 z = round(y);
1261 if (fabs(y-z) == 0.5)
1262 /* halfway between two integers; use round-away-from-zero */
1263 z = y + copysign(0.5, y);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001264
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001265 if (ndigits >= 0)
1266 z = (z / pow2) / pow1;
1267 else
1268 z *= pow1;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001269
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001270 /* if computation resulted in overflow, raise OverflowError */
1271 if (!Py_IS_FINITE(z)) {
1272 PyErr_SetString(PyExc_OverflowError,
1273 "overflow occurred during round");
1274 return NULL;
1275 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001276
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001277 return PyFloat_FromDouble(z);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001278}
1279
1280#endif /* PY_NO_SHORT_FLOAT_REPR */
1281
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001282static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001283float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001285 if (PyFloat_CheckExact(v))
1286 Py_INCREF(v);
1287 else
1288 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1289 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001290}
1291
Mark Dickinson7103aa42008-07-15 19:08:33 +00001292/* turn ASCII hex characters into integer values and vice versa */
1293
1294static char
1295char_from_hex(int x)
1296{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001297 assert(0 <= x && x < 16);
1298 return "0123456789abcdef"[x];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001299}
1300
1301static int
1302hex_from_char(char c) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001303 int x;
1304 switch(c) {
1305 case '0':
1306 x = 0;
1307 break;
1308 case '1':
1309 x = 1;
1310 break;
1311 case '2':
1312 x = 2;
1313 break;
1314 case '3':
1315 x = 3;
1316 break;
1317 case '4':
1318 x = 4;
1319 break;
1320 case '5':
1321 x = 5;
1322 break;
1323 case '6':
1324 x = 6;
1325 break;
1326 case '7':
1327 x = 7;
1328 break;
1329 case '8':
1330 x = 8;
1331 break;
1332 case '9':
1333 x = 9;
1334 break;
1335 case 'a':
1336 case 'A':
1337 x = 10;
1338 break;
1339 case 'b':
1340 case 'B':
1341 x = 11;
1342 break;
1343 case 'c':
1344 case 'C':
1345 x = 12;
1346 break;
1347 case 'd':
1348 case 'D':
1349 x = 13;
1350 break;
1351 case 'e':
1352 case 'E':
1353 x = 14;
1354 break;
1355 case 'f':
1356 case 'F':
1357 x = 15;
1358 break;
1359 default:
1360 x = -1;
1361 break;
1362 }
1363 return x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001364}
1365
1366/* convert a float to a hexadecimal string */
1367
1368/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1369 of the form 4k+1. */
1370#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1371
1372static PyObject *
1373float_hex(PyObject *v)
1374{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001375 double x, m;
1376 int e, shift, i, si, esign;
1377 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1378 trailing NUL byte. */
1379 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001380
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001381 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1384 return float_str((PyFloatObject *)v);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001385
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001386 if (x == 0.0) {
Benjamin Petersoncf76d1f2010-07-02 19:41:39 +00001387 if (copysign(1.0, x) == -1.0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001388 return PyString_FromString("-0x0.0p+0");
1389 else
1390 return PyString_FromString("0x0.0p+0");
1391 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001393 m = frexp(fabs(x), &e);
1394 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1395 m = ldexp(m, shift);
1396 e -= shift;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001398 si = 0;
1399 s[si] = char_from_hex((int)m);
1400 si++;
1401 m -= (int)m;
1402 s[si] = '.';
1403 si++;
1404 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1405 m *= 16.0;
1406 s[si] = char_from_hex((int)m);
1407 si++;
1408 m -= (int)m;
1409 }
1410 s[si] = '\0';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 if (e < 0) {
1413 esign = (int)'-';
1414 e = -e;
1415 }
1416 else
1417 esign = (int)'+';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001418
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001419 if (x < 0.0)
1420 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1421 else
1422 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001423}
1424
1425PyDoc_STRVAR(float_hex_doc,
1426"float.hex() -> string\n\
1427\n\
1428Return a hexadecimal representation of a floating-point number.\n\
1429>>> (-0.1).hex()\n\
1430'-0x1.999999999999ap-4'\n\
1431>>> 3.14159.hex()\n\
1432'0x1.921f9f01b866ep+1'");
1433
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001434/* Case-insensitive locale-independent string match used for nan and inf
1435 detection. t should be lower-case and null-terminated. Return a nonzero
1436 result if the first strlen(t) characters of s match t and 0 otherwise. */
1437
1438static int
1439case_insensitive_match(const char *s, const char *t)
1440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001441 while(*t && Py_TOLOWER(*s) == *t) {
1442 s++;
1443 t++;
1444 }
1445 return *t ? 0 : 1;
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001446}
1447
Mark Dickinson7103aa42008-07-15 19:08:33 +00001448/* Convert a hexadecimal string to a float. */
1449
1450static PyObject *
1451float_fromhex(PyObject *cls, PyObject *arg)
1452{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001453 PyObject *result_as_float, *result;
1454 double x;
1455 long exp, top_exp, lsb, key_digit;
1456 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1457 int half_eps, digit, round_up, sign=1;
1458 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001459
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001460 /*
1461 * For the sake of simplicity and correctness, we impose an artificial
1462 * limit on ndigits, the total number of hex digits in the coefficient
1463 * The limit is chosen to ensure that, writing exp for the exponent,
1464 *
1465 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1466 * guaranteed to overflow (provided it's nonzero)
1467 *
1468 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1469 * guaranteed to underflow to 0.
1470 *
1471 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1472 * overflow in the calculation of exp and top_exp below.
1473 *
1474 * More specifically, ndigits is assumed to satisfy the following
1475 * inequalities:
1476 *
1477 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1478 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1479 *
1480 * If either of these inequalities is not satisfied, a ValueError is
1481 * raised. Otherwise, write x for the value of the hex string, and
1482 * assume x is nonzero. Then
1483 *
1484 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1485 *
1486 * Now if exp > LONG_MAX/2 then:
1487 *
1488 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1489 * = DBL_MAX_EXP
1490 *
1491 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1492 * double, so overflows. If exp < LONG_MIN/2, then
1493 *
1494 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1495 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1496 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1497 *
1498 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1499 * when converted to a C double.
1500 *
1501 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1502 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1503 */
Mark Dickinson7103aa42008-07-15 19:08:33 +00001504
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 if (PyString_AsStringAndSize(arg, &s, &length))
1506 return NULL;
1507 s_end = s + length;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001508
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001509 /********************
1510 * Parse the string *
1511 ********************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001512
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001513 /* leading whitespace and optional sign */
1514 while (Py_ISSPACE(*s))
1515 s++;
1516 if (*s == '-') {
1517 s++;
1518 sign = -1;
1519 }
1520 else if (*s == '+')
1521 s++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001522
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001523 /* infinities and nans */
1524 if (*s == 'i' || *s == 'I') {
1525 if (!case_insensitive_match(s+1, "nf"))
1526 goto parse_error;
1527 s += 3;
1528 x = Py_HUGE_VAL;
1529 if (case_insensitive_match(s, "inity"))
1530 s += 5;
1531 goto finished;
1532 }
1533 if (*s == 'n' || *s == 'N') {
1534 if (!case_insensitive_match(s+1, "an"))
1535 goto parse_error;
1536 s += 3;
1537 x = Py_NAN;
1538 goto finished;
1539 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001541 /* [0x] */
1542 s_store = s;
1543 if (*s == '0') {
1544 s++;
1545 if (*s == 'x' || *s == 'X')
1546 s++;
1547 else
1548 s = s_store;
1549 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 /* coefficient: <integer> [. <fraction>] */
1552 coeff_start = s;
1553 while (hex_from_char(*s) >= 0)
1554 s++;
1555 s_store = s;
1556 if (*s == '.') {
1557 s++;
1558 while (hex_from_char(*s) >= 0)
1559 s++;
1560 coeff_end = s-1;
1561 }
1562 else
1563 coeff_end = s;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001564
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001565 /* ndigits = total # of hex digits; fdigits = # after point */
1566 ndigits = coeff_end - coeff_start;
1567 fdigits = coeff_end - s_store;
1568 if (ndigits == 0)
1569 goto parse_error;
1570 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1571 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1572 goto insane_length_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001574 /* [p <exponent>] */
1575 if (*s == 'p' || *s == 'P') {
1576 s++;
1577 exp_start = s;
1578 if (*s == '-' || *s == '+')
1579 s++;
1580 if (!('0' <= *s && *s <= '9'))
1581 goto parse_error;
1582 s++;
1583 while ('0' <= *s && *s <= '9')
1584 s++;
1585 exp = strtol(exp_start, NULL, 10);
1586 }
1587 else
1588 exp = 0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001589
Mark Dickinson7103aa42008-07-15 19:08:33 +00001590/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001591#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1592 coeff_end-(j) : \
1593 coeff_end-1-(j)))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001595 /*******************************************
1596 * Compute rounded value of the hex string *
1597 *******************************************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001598
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001599 /* Discard leading zeros, and catch extreme overflow and underflow */
1600 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1601 ndigits--;
1602 if (ndigits == 0 || exp < LONG_MIN/2) {
1603 x = 0.0;
1604 goto finished;
1605 }
1606 if (exp > LONG_MAX/2)
1607 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001608
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001609 /* Adjust exponent for fractional part. */
1610 exp = exp - 4*((long)fdigits);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001611
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001612 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1613 top_exp = exp + 4*((long)ndigits - 1);
1614 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1615 top_exp++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001616
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001617 /* catch almost all nonextreme cases of overflow and underflow here */
1618 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1619 x = 0.0;
1620 goto finished;
1621 }
1622 if (top_exp > DBL_MAX_EXP)
1623 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001624
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001625 /* lsb = exponent of least significant bit of the *rounded* value.
1626 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1627 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001628
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001629 x = 0.0;
1630 if (exp >= lsb) {
1631 /* no rounding required */
1632 for (i = ndigits-1; i >= 0; i--)
1633 x = 16.0*x + HEX_DIGIT(i);
1634 x = ldexp(x, (int)(exp));
1635 goto finished;
1636 }
1637 /* rounding required. key_digit is the index of the hex digit
1638 containing the first bit to be rounded away. */
1639 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1640 key_digit = (lsb - exp - 1) / 4;
1641 for (i = ndigits-1; i > key_digit; i--)
1642 x = 16.0*x + HEX_DIGIT(i);
1643 digit = HEX_DIGIT(key_digit);
1644 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001645
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001646 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1647 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1648 if ((digit & half_eps) != 0) {
1649 round_up = 0;
1650 if ((digit & (3*half_eps-1)) != 0 ||
1651 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1652 round_up = 1;
1653 else
1654 for (i = key_digit-1; i >= 0; i--)
1655 if (HEX_DIGIT(i) != 0) {
1656 round_up = 1;
1657 break;
1658 }
1659 if (round_up == 1) {
1660 x += 2*half_eps;
1661 if (top_exp == DBL_MAX_EXP &&
1662 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1663 /* overflow corner case: pre-rounded value <
1664 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1665 goto overflow_error;
1666 }
1667 }
1668 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001669
1670 finished:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001671 /* optional trailing whitespace leading to the end of the string */
1672 while (Py_ISSPACE(*s))
1673 s++;
1674 if (s != s_end)
1675 goto parse_error;
1676 result_as_float = Py_BuildValue("(d)", sign * x);
1677 if (result_as_float == NULL)
1678 return NULL;
1679 result = PyObject_CallObject(cls, result_as_float);
1680 Py_DECREF(result_as_float);
1681 return result;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001682
1683 overflow_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001684 PyErr_SetString(PyExc_OverflowError,
1685 "hexadecimal value too large to represent as a float");
1686 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001687
1688 parse_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001689 PyErr_SetString(PyExc_ValueError,
1690 "invalid hexadecimal floating-point string");
1691 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001692
1693 insane_length_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001694 PyErr_SetString(PyExc_ValueError,
1695 "hexadecimal string too long to convert");
1696 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001697}
1698
1699PyDoc_STRVAR(float_fromhex_doc,
1700"float.fromhex(string) -> float\n\
1701\n\
1702Create a floating-point number from a hexadecimal string.\n\
1703>>> float.fromhex('0x1.ffffp10')\n\
17042047.984375\n\
1705>>> float.fromhex('-0x1p-1074')\n\
1706-4.9406564584124654e-324");
1707
1708
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001709static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001710float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 double self;
1713 double float_part;
1714 int exponent;
1715 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001716
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001717 PyObject *prev;
1718 PyObject *py_exponent = NULL;
1719 PyObject *numerator = NULL;
1720 PyObject *denominator = NULL;
1721 PyObject *result_pair = NULL;
1722 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001723
1724#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001725 prev = obj; \
1726 obj = call; \
1727 Py_DECREF(prev); \
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001729 CONVERT_TO_DOUBLE(v, self);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001730
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001731 if (Py_IS_INFINITY(self)) {
1732 PyErr_SetString(PyExc_OverflowError,
1733 "Cannot pass infinity to float.as_integer_ratio.");
1734 return NULL;
1735 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001736#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 if (Py_IS_NAN(self)) {
1738 PyErr_SetString(PyExc_ValueError,
1739 "Cannot pass NaN to float.as_integer_ratio.");
1740 return NULL;
1741 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001742#endif
1743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001744 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1745 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1746 PyFPE_END_PROTECT(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001748 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1749 float_part *= 2.0;
1750 exponent--;
1751 }
1752 /* self == float_part * 2**exponent exactly and float_part is integral.
1753 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1754 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001756 numerator = PyLong_FromDouble(float_part);
1757 if (numerator == NULL) goto error;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001759 /* fold in 2**exponent */
1760 denominator = PyLong_FromLong(1);
1761 py_exponent = PyLong_FromLong(labs((long)exponent));
1762 if (py_exponent == NULL) goto error;
1763 INPLACE_UPDATE(py_exponent,
1764 long_methods->nb_lshift(denominator, py_exponent));
1765 if (py_exponent == NULL) goto error;
1766 if (exponent > 0) {
1767 INPLACE_UPDATE(numerator,
1768 long_methods->nb_multiply(numerator, py_exponent));
1769 if (numerator == NULL) goto error;
1770 }
1771 else {
1772 Py_DECREF(denominator);
1773 denominator = py_exponent;
1774 py_exponent = NULL;
1775 }
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001776
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001777 /* Returns ints instead of longs where possible */
1778 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1779 if (numerator == NULL) goto error;
1780 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1781 if (denominator == NULL) goto error;
1782
1783 result_pair = PyTuple_Pack(2, numerator, denominator);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001784
1785#undef INPLACE_UPDATE
1786error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 Py_XDECREF(py_exponent);
1788 Py_XDECREF(denominator);
1789 Py_XDECREF(numerator);
1790 return result_pair;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001791}
1792
1793PyDoc_STRVAR(float_as_integer_ratio_doc,
1794"float.as_integer_ratio() -> (int, int)\n"
1795"\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001796"Return a pair of integers, whose ratio is exactly equal to the original\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001797"float and with a positive denominator.\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001798"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001799"\n"
1800">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001801"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001802">>> (0.0).as_integer_ratio()\n"
1803"(0, 1)\n"
1804">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001805"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001806
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001807
Jeremy Hylton938ace62002-07-17 16:30:39 +00001808static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001809float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1810
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811static PyObject *
1812float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1813{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 PyObject *x = Py_False; /* Integer zero */
1815 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001817 if (type != &PyFloat_Type)
1818 return float_subtype_new(type, args, kwds); /* Wimp out */
1819 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1820 return NULL;
1821 /* If it's a string, but not a string subclass, use
1822 PyFloat_FromString. */
1823 if (PyString_CheckExact(x))
1824 return PyFloat_FromString(x, NULL);
1825 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826}
1827
Guido van Rossumbef14172001-08-29 15:47:46 +00001828/* Wimpy, slow approach to tp_new calls for subtypes of float:
1829 first create a regular float from whatever arguments we got,
1830 then allocate a subtype instance and initialize its ob_fval
1831 from the regular float. The regular float is then thrown away.
1832*/
1833static PyObject *
1834float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1835{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001836 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 assert(PyType_IsSubtype(type, &PyFloat_Type));
1839 tmp = float_new(&PyFloat_Type, args, kwds);
1840 if (tmp == NULL)
1841 return NULL;
Serhiy Storchaka8d30ad72015-11-25 15:55:54 +02001842 assert(PyFloat_Check(tmp));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001843 newobj = type->tp_alloc(type, 0);
1844 if (newobj == NULL) {
1845 Py_DECREF(tmp);
1846 return NULL;
1847 }
1848 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1849 Py_DECREF(tmp);
1850 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001851}
1852
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001853static PyObject *
1854float_getnewargs(PyFloatObject *v)
1855{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001856 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001857}
1858
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001859/* this is for the benefit of the pack/unpack routines below */
1860
1861typedef enum {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001862 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001863} float_format_type;
1864
1865static float_format_type double_format, float_format;
1866static float_format_type detected_double_format, detected_float_format;
1867
1868static PyObject *
1869float_getformat(PyTypeObject *v, PyObject* arg)
1870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001871 char* s;
1872 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001873
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 if (!PyString_Check(arg)) {
1875 PyErr_Format(PyExc_TypeError,
1876 "__getformat__() argument must be string, not %.500s",
1877 Py_TYPE(arg)->tp_name);
1878 return NULL;
1879 }
1880 s = PyString_AS_STRING(arg);
1881 if (strcmp(s, "double") == 0) {
1882 r = double_format;
1883 }
1884 else if (strcmp(s, "float") == 0) {
1885 r = float_format;
1886 }
1887 else {
1888 PyErr_SetString(PyExc_ValueError,
1889 "__getformat__() argument 1 must be "
1890 "'double' or 'float'");
1891 return NULL;
1892 }
1893
1894 switch (r) {
1895 case unknown_format:
1896 return PyString_FromString("unknown");
1897 case ieee_little_endian_format:
1898 return PyString_FromString("IEEE, little-endian");
1899 case ieee_big_endian_format:
1900 return PyString_FromString("IEEE, big-endian");
1901 default:
1902 Py_FatalError("insane float_format or double_format");
1903 return NULL;
1904 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001905}
1906
1907PyDoc_STRVAR(float_getformat_doc,
1908"float.__getformat__(typestr) -> string\n"
1909"\n"
1910"You probably don't want to use this function. It exists mainly to be\n"
1911"used in Python's test suite.\n"
1912"\n"
1913"typestr must be 'double' or 'float'. This function returns whichever of\n"
1914"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1915"format of floating point numbers used by the C type named by typestr.");
1916
1917static PyObject *
1918float_setformat(PyTypeObject *v, PyObject* args)
1919{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 char* typestr;
1921 char* format;
1922 float_format_type f;
1923 float_format_type detected;
1924 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001925
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001926 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1927 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001928
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001929 if (strcmp(typestr, "double") == 0) {
1930 p = &double_format;
1931 detected = detected_double_format;
1932 }
1933 else if (strcmp(typestr, "float") == 0) {
1934 p = &float_format;
1935 detected = detected_float_format;
1936 }
1937 else {
1938 PyErr_SetString(PyExc_ValueError,
1939 "__setformat__() argument 1 must "
1940 "be 'double' or 'float'");
1941 return NULL;
1942 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001943
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001944 if (strcmp(format, "unknown") == 0) {
1945 f = unknown_format;
1946 }
1947 else if (strcmp(format, "IEEE, little-endian") == 0) {
1948 f = ieee_little_endian_format;
1949 }
1950 else if (strcmp(format, "IEEE, big-endian") == 0) {
1951 f = ieee_big_endian_format;
1952 }
1953 else {
1954 PyErr_SetString(PyExc_ValueError,
1955 "__setformat__() argument 2 must be "
1956 "'unknown', 'IEEE, little-endian' or "
1957 "'IEEE, big-endian'");
1958 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001959
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001960 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001961
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001962 if (f != unknown_format && f != detected) {
1963 PyErr_Format(PyExc_ValueError,
1964 "can only set %s format to 'unknown' or the "
1965 "detected platform value", typestr);
1966 return NULL;
1967 }
1968
1969 *p = f;
1970 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001971}
1972
1973PyDoc_STRVAR(float_setformat_doc,
1974"float.__setformat__(typestr, fmt) -> None\n"
1975"\n"
1976"You probably don't want to use this function. It exists mainly to be\n"
1977"used in Python's test suite.\n"
1978"\n"
1979"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1980"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1981"one of the latter two if it appears to match the underlying C reality.\n"
1982"\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001983"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001984"This affects how floats are converted to and from binary strings.");
1985
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001986static PyObject *
1987float_getzero(PyObject *v, void *closure)
1988{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001989 return PyFloat_FromDouble(0.0);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001990}
1991
Eric Smitha9f7d622008-02-17 19:46:49 +00001992static PyObject *
1993float__format__(PyObject *self, PyObject *args)
1994{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001995 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001997 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1998 return NULL;
1999 if (PyBytes_Check(format_spec))
2000 return _PyFloat_FormatAdvanced(self,
2001 PyBytes_AS_STRING(format_spec),
2002 PyBytes_GET_SIZE(format_spec));
2003 if (PyUnicode_Check(format_spec)) {
2004 /* Convert format_spec to a str */
2005 PyObject *result;
2006 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00002007
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002008 if (str_spec == NULL)
2009 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002010
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002011 result = _PyFloat_FormatAdvanced(self,
2012 PyBytes_AS_STRING(str_spec),
2013 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00002014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002015 Py_DECREF(str_spec);
2016 return result;
2017 }
2018 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
2019 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002020}
2021
2022PyDoc_STRVAR(float__format__doc,
2023"float.__format__(format_spec) -> string\n"
2024"\n"
2025"Formats the float according to format_spec.");
2026
2027
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002028static PyMethodDef float_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002029 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002030 "Return self, the complex conjugate of any float."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002031 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002032 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002033 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
2034 float_as_integer_ratio_doc},
2035 {"fromhex", (PyCFunction)float_fromhex,
2036 METH_O|METH_CLASS, float_fromhex_doc},
2037 {"hex", (PyCFunction)float_hex,
2038 METH_NOARGS, float_hex_doc},
2039 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002040 "Return True if the float is an integer."},
Christian Heimes6f341092008-04-18 23:13:07 +00002041#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002042 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002043 "Return True if the float is positive or negative infinite."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002044 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002045 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002046 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002047 "Return True if the float is not a number (NaN)."},
Christian Heimes6f341092008-04-18 23:13:07 +00002048#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002049 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
2050 {"__getformat__", (PyCFunction)float_getformat,
2051 METH_O|METH_CLASS, float_getformat_doc},
2052 {"__setformat__", (PyCFunction)float_setformat,
2053 METH_VARARGS|METH_CLASS, float_setformat_doc},
2054 {"__format__", (PyCFunction)float__format__,
2055 METH_VARARGS, float__format__doc},
2056 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002057};
2058
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002059static PyGetSetDef float_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002060 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002061 (getter)float_float, (setter)NULL,
2062 "the real part of a complex number",
2063 NULL},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002064 {"imag",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002065 (getter)float_getzero, (setter)NULL,
2066 "the imaginary part of a complex number",
2067 NULL},
2068 {NULL} /* Sentinel */
2069};
2070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002071PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072"float(x) -> floating point number\n\
2073\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002074Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075
2076
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002077static PyNumberMethods float_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002078 float_add, /*nb_add*/
2079 float_sub, /*nb_subtract*/
2080 float_mul, /*nb_multiply*/
2081 float_classic_div, /*nb_divide*/
2082 float_rem, /*nb_remainder*/
2083 float_divmod, /*nb_divmod*/
2084 float_pow, /*nb_power*/
2085 (unaryfunc)float_neg, /*nb_negative*/
2086 (unaryfunc)float_float, /*nb_positive*/
2087 (unaryfunc)float_abs, /*nb_absolute*/
2088 (inquiry)float_nonzero, /*nb_nonzero*/
2089 0, /*nb_invert*/
2090 0, /*nb_lshift*/
2091 0, /*nb_rshift*/
2092 0, /*nb_and*/
2093 0, /*nb_xor*/
2094 0, /*nb_or*/
2095 float_coerce, /*nb_coerce*/
2096 float_trunc, /*nb_int*/
2097 float_long, /*nb_long*/
2098 float_float, /*nb_float*/
2099 0, /* nb_oct */
2100 0, /* nb_hex */
2101 0, /* nb_inplace_add */
2102 0, /* nb_inplace_subtract */
2103 0, /* nb_inplace_multiply */
2104 0, /* nb_inplace_divide */
2105 0, /* nb_inplace_remainder */
2106 0, /* nb_inplace_power */
2107 0, /* nb_inplace_lshift */
2108 0, /* nb_inplace_rshift */
2109 0, /* nb_inplace_and */
2110 0, /* nb_inplace_xor */
2111 0, /* nb_inplace_or */
2112 float_floor_div, /* nb_floor_divide */
2113 float_div, /* nb_true_divide */
2114 0, /* nb_inplace_floor_divide */
2115 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002116};
2117
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118PyTypeObject PyFloat_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002119 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2120 "float",
2121 sizeof(PyFloatObject),
2122 0,
2123 (destructor)float_dealloc, /* tp_dealloc */
2124 (printfunc)float_print, /* tp_print */
2125 0, /* tp_getattr */
2126 0, /* tp_setattr */
2127 0, /* tp_compare */
2128 (reprfunc)float_repr, /* tp_repr */
2129 &float_as_number, /* tp_as_number */
2130 0, /* tp_as_sequence */
2131 0, /* tp_as_mapping */
2132 (hashfunc)float_hash, /* tp_hash */
2133 0, /* tp_call */
2134 (reprfunc)float_str, /* tp_str */
2135 PyObject_GenericGetAttr, /* tp_getattro */
2136 0, /* tp_setattro */
2137 0, /* tp_as_buffer */
2138 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2139 Py_TPFLAGS_BASETYPE, /* tp_flags */
2140 float_doc, /* tp_doc */
2141 0, /* tp_traverse */
2142 0, /* tp_clear */
2143 float_richcompare, /* tp_richcompare */
2144 0, /* tp_weaklistoffset */
2145 0, /* tp_iter */
2146 0, /* tp_iternext */
2147 float_methods, /* tp_methods */
2148 0, /* tp_members */
2149 float_getset, /* tp_getset */
2150 0, /* tp_base */
2151 0, /* tp_dict */
2152 0, /* tp_descr_get */
2153 0, /* tp_descr_set */
2154 0, /* tp_dictoffset */
2155 0, /* tp_init */
2156 0, /* tp_alloc */
2157 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002158};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002159
2160void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002161_PyFloat_Init(void)
2162{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002163 /* We attempt to determine if this machine is using IEEE
2164 floating point formats by peering at the bits of some
2165 carefully chosen values. If it looks like we are on an
2166 IEEE platform, the float packing/unpacking routines can
2167 just copy bits, if not they resort to arithmetic & shifts
2168 and masks. The shifts & masks approach works on all finite
2169 values, but what happens to infinities, NaNs and signed
2170 zeroes on packing is an accident, and attempting to unpack
2171 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002172
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002173 Note that if we're on some whacked-out platform which uses
2174 IEEE formats but isn't strictly little-endian or big-
2175 endian, we will fall back to the portable shifts & masks
2176 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002177
2178#if SIZEOF_DOUBLE == 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002179 {
2180 double x = 9006104071832581.0;
2181 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2182 detected_double_format = ieee_big_endian_format;
2183 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2184 detected_double_format = ieee_little_endian_format;
2185 else
2186 detected_double_format = unknown_format;
2187 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002188#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002189 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002190#endif
2191
2192#if SIZEOF_FLOAT == 4
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002193 {
2194 float y = 16711938.0;
2195 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2196 detected_float_format = ieee_big_endian_format;
2197 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2198 detected_float_format = ieee_little_endian_format;
2199 else
2200 detected_float_format = unknown_format;
2201 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002202#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002203 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002204#endif
2205
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002206 double_format = detected_double_format;
2207 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00002208
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002209 /* Init float info */
2210 if (FloatInfoType.tp_name == 0)
2211 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002212}
2213
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002214int
2215PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002216{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 PyFloatObject *p;
2218 PyFloatBlock *list, *next;
2219 int i;
2220 int u; /* remaining unfreed ints per block */
2221 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002223 list = block_list;
2224 block_list = NULL;
2225 free_list = NULL;
2226 while (list != NULL) {
2227 u = 0;
2228 for (i = 0, p = &list->objects[0];
2229 i < N_FLOATOBJECTS;
2230 i++, p++) {
2231 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
2232 u++;
2233 }
2234 next = list->next;
2235 if (u) {
2236 list->next = block_list;
2237 block_list = list;
2238 for (i = 0, p = &list->objects[0];
2239 i < N_FLOATOBJECTS;
2240 i++, p++) {
2241 if (!PyFloat_CheckExact(p) ||
2242 Py_REFCNT(p) == 0) {
2243 Py_TYPE(p) = (struct _typeobject *)
2244 free_list;
2245 free_list = p;
2246 }
2247 }
2248 }
2249 else {
2250 PyMem_FREE(list);
2251 }
2252 freelist_size += u;
2253 list = next;
2254 }
2255 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002256}
2257
2258void
2259PyFloat_Fini(void)
2260{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002261 PyFloatObject *p;
2262 PyFloatBlock *list;
2263 int i;
2264 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002265
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002266 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002268 if (!Py_VerboseFlag)
2269 return;
2270 fprintf(stderr, "# cleanup floats");
2271 if (!u) {
2272 fprintf(stderr, "\n");
2273 }
2274 else {
2275 fprintf(stderr,
2276 ": %d unfreed float%s\n",
2277 u, u == 1 ? "" : "s");
2278 }
2279 if (Py_VerboseFlag > 1) {
2280 list = block_list;
2281 while (list != NULL) {
2282 for (i = 0, p = &list->objects[0];
2283 i < N_FLOATOBJECTS;
2284 i++, p++) {
2285 if (PyFloat_CheckExact(p) &&
2286 Py_REFCNT(p) != 0) {
2287 char *buf = PyOS_double_to_string(
2288 PyFloat_AS_DOUBLE(p), 'r',
2289 0, 0, NULL);
2290 if (buf) {
2291 /* XXX(twouters) cast
2292 refcount to long
2293 until %zd is
2294 universally
2295 available
2296 */
2297 fprintf(stderr,
2298 "# <float at %p, refcnt=%ld, val=%s>\n",
2299 p, (long)Py_REFCNT(p), buf);
2300 PyMem_Free(buf);
2301 }
2302 }
2303 }
2304 list = list->next;
2305 }
2306 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002307}
Tim Peters9905b942003-03-20 20:53:32 +00002308
2309/*----------------------------------------------------------------------------
2310 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002311 */
2312int
2313_PyFloat_Pack4(double x, unsigned char *p, int le)
2314{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 if (float_format == unknown_format) {
2316 unsigned char sign;
2317 int e;
2318 double f;
2319 unsigned int fbits;
2320 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002321
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002322 if (le) {
2323 p += 3;
2324 incr = -1;
2325 }
Tim Peters9905b942003-03-20 20:53:32 +00002326
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002327 if (x < 0) {
2328 sign = 1;
2329 x = -x;
2330 }
2331 else
2332 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002333
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002334 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002336 /* Normalize f to be in the range [1.0, 2.0) */
2337 if (0.5 <= f && f < 1.0) {
2338 f *= 2.0;
2339 e--;
2340 }
2341 else if (f == 0.0)
2342 e = 0;
2343 else {
2344 PyErr_SetString(PyExc_SystemError,
2345 "frexp() result out of range");
2346 return -1;
2347 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002348
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002349 if (e >= 128)
2350 goto Overflow;
2351 else if (e < -126) {
2352 /* Gradual underflow */
2353 f = ldexp(f, 126 + e);
2354 e = 0;
2355 }
2356 else if (!(e == 0 && f == 0.0)) {
2357 e += 127;
2358 f -= 1.0; /* Get rid of leading 1 */
2359 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002361 f *= 8388608.0; /* 2**23 */
2362 fbits = (unsigned int)(f + 0.5); /* Round */
2363 assert(fbits <= 8388608);
2364 if (fbits >> 23) {
2365 /* The carry propagated out of a string of 23 1 bits. */
2366 fbits = 0;
2367 ++e;
2368 if (e >= 255)
2369 goto Overflow;
2370 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002371
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002372 /* First byte */
2373 *p = (sign << 7) | (e >> 1);
2374 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 /* Second byte */
2377 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2378 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002379
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002380 /* Third byte */
2381 *p = (fbits >> 8) & 0xFF;
2382 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002384 /* Fourth byte */
2385 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002386
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002387 /* Done */
2388 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002389
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002390 }
2391 else {
2392 float y = (float)x;
2393 const char *s = (char*)&y;
2394 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002395
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002396 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2397 goto Overflow;
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002399 if ((float_format == ieee_little_endian_format && !le)
2400 || (float_format == ieee_big_endian_format && le)) {
2401 p += 3;
2402 incr = -1;
2403 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002404
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002405 for (i = 0; i < 4; i++) {
2406 *p = *s++;
2407 p += incr;
2408 }
2409 return 0;
2410 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002411 Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002412 PyErr_SetString(PyExc_OverflowError,
2413 "float too large to pack with f format");
2414 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002415}
2416
2417int
2418_PyFloat_Pack8(double x, unsigned char *p, int le)
2419{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002420 if (double_format == unknown_format) {
2421 unsigned char sign;
2422 int e;
2423 double f;
2424 unsigned int fhi, flo;
2425 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002427 if (le) {
2428 p += 7;
2429 incr = -1;
2430 }
Tim Peters9905b942003-03-20 20:53:32 +00002431
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002432 if (x < 0) {
2433 sign = 1;
2434 x = -x;
2435 }
2436 else
2437 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002438
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002439 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002440
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002441 /* Normalize f to be in the range [1.0, 2.0) */
2442 if (0.5 <= f && f < 1.0) {
2443 f *= 2.0;
2444 e--;
2445 }
2446 else if (f == 0.0)
2447 e = 0;
2448 else {
2449 PyErr_SetString(PyExc_SystemError,
2450 "frexp() result out of range");
2451 return -1;
2452 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002453
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002454 if (e >= 1024)
2455 goto Overflow;
2456 else if (e < -1022) {
2457 /* Gradual underflow */
2458 f = ldexp(f, 1022 + e);
2459 e = 0;
2460 }
2461 else if (!(e == 0 && f == 0.0)) {
2462 e += 1023;
2463 f -= 1.0; /* Get rid of leading 1 */
2464 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2467 f *= 268435456.0; /* 2**28 */
2468 fhi = (unsigned int)f; /* Truncate */
2469 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002471 f -= (double)fhi;
2472 f *= 16777216.0; /* 2**24 */
2473 flo = (unsigned int)(f + 0.5); /* Round */
2474 assert(flo <= 16777216);
2475 if (flo >> 24) {
2476 /* The carry propagated out of a string of 24 1 bits. */
2477 flo = 0;
2478 ++fhi;
2479 if (fhi >> 28) {
2480 /* And it also progagated out of the next 28 bits. */
2481 fhi = 0;
2482 ++e;
2483 if (e >= 2047)
2484 goto Overflow;
2485 }
2486 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002487
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002488 /* First byte */
2489 *p = (sign << 7) | (e >> 4);
2490 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002491
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002492 /* Second byte */
2493 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2494 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002495
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 /* Third byte */
2497 *p = (fhi >> 16) & 0xFF;
2498 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002500 /* Fourth byte */
2501 *p = (fhi >> 8) & 0xFF;
2502 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002504 /* Fifth byte */
2505 *p = fhi & 0xFF;
2506 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002508 /* Sixth byte */
2509 *p = (flo >> 16) & 0xFF;
2510 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002511
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002512 /* Seventh byte */
2513 *p = (flo >> 8) & 0xFF;
2514 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002515
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002516 /* Eighth byte */
2517 *p = flo & 0xFF;
2518 /* p += incr; Unneeded (for now) */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002519
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002520 /* Done */
2521 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002522
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002523 Overflow:
2524 PyErr_SetString(PyExc_OverflowError,
2525 "float too large to pack with d format");
2526 return -1;
2527 }
2528 else {
2529 const char *s = (char*)&x;
2530 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002532 if ((double_format == ieee_little_endian_format && !le)
2533 || (double_format == ieee_big_endian_format && le)) {
2534 p += 7;
2535 incr = -1;
2536 }
2537
2538 for (i = 0; i < 8; i++) {
2539 *p = *s++;
2540 p += incr;
2541 }
2542 return 0;
2543 }
Tim Peters9905b942003-03-20 20:53:32 +00002544}
2545
2546double
2547_PyFloat_Unpack4(const unsigned char *p, int le)
2548{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002549 if (float_format == unknown_format) {
2550 unsigned char sign;
2551 int e;
2552 unsigned int f;
2553 double x;
2554 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002555
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002556 if (le) {
2557 p += 3;
2558 incr = -1;
2559 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002560
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002561 /* First byte */
2562 sign = (*p >> 7) & 1;
2563 e = (*p & 0x7F) << 1;
2564 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002565
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002566 /* Second byte */
2567 e |= (*p >> 7) & 1;
2568 f = (*p & 0x7F) << 16;
2569 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002570
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002571 if (e == 255) {
2572 PyErr_SetString(
2573 PyExc_ValueError,
2574 "can't unpack IEEE 754 special value "
2575 "on non-IEEE platform");
2576 return -1;
2577 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002578
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 /* Third byte */
2580 f |= *p << 8;
2581 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 /* Fourth byte */
2584 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002585
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002586 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002587
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002588 /* XXX This sadly ignores Inf/NaN issues */
2589 if (e == 0)
2590 e = -126;
2591 else {
2592 x += 1.0;
2593 e -= 127;
2594 }
2595 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002596
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002597 if (sign)
2598 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002599
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002600 return x;
2601 }
2602 else {
2603 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002605 if ((float_format == ieee_little_endian_format && !le)
2606 || (float_format == ieee_big_endian_format && le)) {
2607 char buf[4];
2608 char *d = &buf[3];
2609 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002611 for (i = 0; i < 4; i++) {
2612 *d-- = *p++;
2613 }
2614 memcpy(&x, buf, 4);
2615 }
2616 else {
2617 memcpy(&x, p, 4);
2618 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002619
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002620 return x;
2621 }
Tim Peters9905b942003-03-20 20:53:32 +00002622}
2623
2624double
2625_PyFloat_Unpack8(const unsigned char *p, int le)
2626{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002627 if (double_format == unknown_format) {
2628 unsigned char sign;
2629 int e;
2630 unsigned int fhi, flo;
2631 double x;
2632 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002634 if (le) {
2635 p += 7;
2636 incr = -1;
2637 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002638
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002639 /* First byte */
2640 sign = (*p >> 7) & 1;
2641 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002642
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002643 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002644
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002645 /* Second byte */
2646 e |= (*p >> 4) & 0xF;
2647 fhi = (*p & 0xF) << 24;
2648 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002649
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002650 if (e == 2047) {
2651 PyErr_SetString(
2652 PyExc_ValueError,
2653 "can't unpack IEEE 754 special value "
2654 "on non-IEEE platform");
2655 return -1.0;
2656 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002657
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002658 /* Third byte */
2659 fhi |= *p << 16;
2660 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002662 /* Fourth byte */
2663 fhi |= *p << 8;
2664 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002666 /* Fifth byte */
2667 fhi |= *p;
2668 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002669
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002670 /* Sixth byte */
2671 flo = *p << 16;
2672 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002673
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002674 /* Seventh byte */
2675 flo |= *p << 8;
2676 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002677
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002678 /* Eighth byte */
2679 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002680
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002681 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2682 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002684 if (e == 0)
2685 e = -1022;
2686 else {
2687 x += 1.0;
2688 e -= 1023;
2689 }
2690 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 if (sign)
2693 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002694
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002695 return x;
2696 }
2697 else {
2698 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002699
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002700 if ((double_format == ieee_little_endian_format && !le)
2701 || (double_format == ieee_big_endian_format && le)) {
2702 char buf[8];
2703 char *d = &buf[7];
2704 int i;
2705
2706 for (i = 0; i < 8; i++) {
2707 *d-- = *p++;
2708 }
2709 memcpy(&x, buf, 8);
2710 }
2711 else {
2712 memcpy(&x, p, 8);
2713 }
2714
2715 return x;
2716 }
Tim Peters9905b942003-03-20 20:53:32 +00002717}