blob: 0ce7f6ce5cf22b89c798995b5beab4ce7d9b97e1 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Mark Dickinson7103aa42008-07-15 19:08:33 +000013#undef MAX
14#undef MIN
15#define MAX(x, y) ((x) < (y) ? (y) : (x))
16#define MIN(x, y) ((x) < (y) ? (x) : (y))
17
Neal Norwitz5f95a792008-01-25 08:04:16 +000018#ifdef _OSF_SOURCE
19/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
20extern int finite(double);
21#endif
22
Guido van Rossum93ad0df1997-05-13 21:00:42 +000023/* Special free list -- see comments for same code in intobject.c. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000024#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
25#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
26#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000027
Guido van Rossum3fce8831999-03-12 19:43:17 +000028struct _floatblock {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000029 struct _floatblock *next;
30 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000031};
32
33typedef struct _floatblock PyFloatBlock;
34
35static PyFloatBlock *block_list = NULL;
36static PyFloatObject *free_list = NULL;
37
Guido van Rossum93ad0df1997-05-13 21:00:42 +000038static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000039fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000040{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000041 PyFloatObject *p, *q;
42 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
43 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
44 if (p == NULL)
45 return (PyFloatObject *) PyErr_NoMemory();
46 ((PyFloatBlock *)p)->next = block_list;
47 block_list = (PyFloatBlock *)p;
48 p = &((PyFloatBlock *)p)->objects[0];
49 q = p + N_FLOATOBJECTS;
50 while (--q > p)
51 Py_TYPE(q) = (struct _typeobject *)(q-1);
52 Py_TYPE(q) = NULL;
53 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054}
55
Christian Heimesdfdfaab2007-12-01 11:20:10 +000056double
57PyFloat_GetMax(void)
58{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000059 return DBL_MAX;
Christian Heimesdfdfaab2007-12-01 11:20:10 +000060}
61
62double
63PyFloat_GetMin(void)
64{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000065 return DBL_MIN;
Christian Heimesdfdfaab2007-12-01 11:20:10 +000066}
67
Christian Heimes796fc312008-01-30 18:58:29 +000068static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000069
70PyDoc_STRVAR(floatinfo__doc__,
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +000071"sys.float_info\n\
Christian Heimesc94e2b52008-01-14 04:13:37 +000072\n\
73A structseq holding information about the float type. It contains low level\n\
74information about the precision and internal representation. Please study\n\
75your system's :file:`float.h` for more information.");
76
77static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000078 {"max", "DBL_MAX -- maximum representable finite float"},
79 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
80 "is representable"},
81 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
82 "is representable"},
83 {"min", "DBL_MIN -- Minimum positive normalizer float"},
84 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
85 "is a normalized float"},
86 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
87 "a normalized"},
88 {"dig", "DBL_DIG -- digits"},
89 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
90 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
91 "representable float"},
92 {"radix", "FLT_RADIX -- radix of exponent"},
93 {"rounds", "FLT_ROUNDS -- addition rounds"},
94 {0}
Christian Heimesc94e2b52008-01-14 04:13:37 +000095};
96
97static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000098 "sys.float_info", /* name */
99 floatinfo__doc__, /* doc */
100 floatinfo_fields, /* fields */
101 11
Christian Heimesc94e2b52008-01-14 04:13:37 +0000102};
103
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000104PyObject *
105PyFloat_GetInfo(void)
106{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000107 PyObject* floatinfo;
108 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000109
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000110 floatinfo = PyStructSequence_New(&FloatInfoType);
111 if (floatinfo == NULL) {
112 return NULL;
113 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000114
Christian Heimesc94e2b52008-01-14 04:13:37 +0000115#define SetIntFlag(flag) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000116 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
Christian Heimesc94e2b52008-01-14 04:13:37 +0000117#define SetDblFlag(flag) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000119
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000120 SetDblFlag(DBL_MAX);
121 SetIntFlag(DBL_MAX_EXP);
122 SetIntFlag(DBL_MAX_10_EXP);
123 SetDblFlag(DBL_MIN);
124 SetIntFlag(DBL_MIN_EXP);
125 SetIntFlag(DBL_MIN_10_EXP);
126 SetIntFlag(DBL_DIG);
127 SetIntFlag(DBL_MANT_DIG);
128 SetDblFlag(DBL_EPSILON);
129 SetIntFlag(FLT_RADIX);
130 SetIntFlag(FLT_ROUNDS);
Christian Heimesc94e2b52008-01-14 04:13:37 +0000131#undef SetIntFlag
132#undef SetDblFlag
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133
134 if (PyErr_Occurred()) {
135 Py_CLEAR(floatinfo);
136 return NULL;
137 }
138 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000139}
140
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 register PyFloatObject *op;
145 if (free_list == NULL) {
146 if ((free_list = fill_free_list()) == NULL)
147 return NULL;
148 }
149 /* Inline PyObject_New */
150 op = free_list;
151 free_list = (PyFloatObject *)Py_TYPE(op);
152 PyObject_INIT(op, &PyFloat_Type);
153 op->ob_fval = fval;
154 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
156
Tim Petersef14d732000-09-23 03:39:17 +0000157/**************************************************************************
158RED_FLAG 22-Sep-2000 tim
159PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
160
1611. If v was a regular string, *pend was set to point to its terminating
162 null byte. That's useless (the caller can find that without any
163 help from this function!).
164
1652. If v was a Unicode string, or an object convertible to a character
166 buffer, *pend was set to point into stack trash (the auto temp
167 vector holding the character buffer). That was downright dangerous.
168
169Since we can't change the interface of a public API function, pend is
170still supported but now *officially* useless: if pend is not NULL,
171*pend is set to NULL.
172**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000174PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000175{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000176 const char *s, *last, *end;
177 double x;
178 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000179#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000180 char *s_buffer = NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000181#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000182 Py_ssize_t len;
183 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000184
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000185 if (pend)
186 *pend = NULL;
187 if (PyString_Check(v)) {
188 s = PyString_AS_STRING(v);
189 len = PyString_GET_SIZE(v);
190 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000191#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000192 else if (PyUnicode_Check(v)) {
193 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
194 if (s_buffer == NULL)
195 return PyErr_NoMemory();
196 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
197 PyUnicode_GET_SIZE(v),
198 s_buffer,
199 NULL))
200 goto error;
201 s = s_buffer;
202 len = strlen(s);
203 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000204#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000205 else if (PyObject_AsCharBuffer(v, &s, &len)) {
206 PyErr_SetString(PyExc_TypeError,
207 "float() argument must be a string or a number");
208 return NULL;
209 }
210 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000211
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000212 while (Py_ISSPACE(*s))
213 s++;
214 /* We don't care about overflow or underflow. If the platform
215 * supports them, infinities and signed zeroes (on underflow) are
216 * fine. */
217 x = PyOS_string_to_double(s, (char **)&end, NULL);
218 if (x == -1.0 && PyErr_Occurred())
219 goto error;
220 while (Py_ISSPACE(*end))
221 end++;
222 if (end == last)
223 result = PyFloat_FromDouble(x);
224 else {
225 PyOS_snprintf(buffer, sizeof(buffer),
226 "invalid literal for float(): %.200s", s);
227 PyErr_SetString(PyExc_ValueError, buffer);
228 result = NULL;
229 }
Mark Dickinson8568b192009-10-26 21:11:20 +0000230
231 error:
232#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 if (s_buffer)
234 PyMem_FREE(s_buffer);
Mark Dickinson8568b192009-10-26 21:11:20 +0000235#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237}
238
Guido van Rossum234f9421993-06-17 12:35:49 +0000239static void
Fred Drakefd99de62000-07-09 05:02:18 +0000240float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000241{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000242 if (PyFloat_CheckExact(op)) {
243 Py_TYPE(op) = (struct _typeobject *)free_list;
244 free_list = op;
245 }
246 else
247 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000248}
249
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250double
Fred Drakefd99de62000-07-09 05:02:18 +0000251PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 PyNumberMethods *nb;
254 PyFloatObject *fo;
255 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000256
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 if (op && PyFloat_Check(op))
258 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000259
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 if (op == NULL) {
261 PyErr_BadArgument();
262 return -1;
263 }
Tim Petersd2364e82001-11-01 20:09:42 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
266 PyErr_SetString(PyExc_TypeError, "a float is required");
267 return -1;
268 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000269
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000270 fo = (PyFloatObject*) (*nb->nb_float) (op);
271 if (fo == NULL)
272 return -1;
273 if (!PyFloat_Check(fo)) {
Benjamin Petersonf0506482015-03-06 09:08:44 -0500274 Py_DECREF(fo);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 PyErr_SetString(PyExc_TypeError,
276 "nb_float should return float object");
277 return -1;
278 }
Tim Petersd2364e82001-11-01 20:09:42 +0000279
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000280 val = PyFloat_AS_DOUBLE(fo);
281 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284}
285
286/* Methods */
287
Neil Schemenauer32117e52001-01-04 01:44:34 +0000288/* Macro and helper that convert PyObject obj to a C double and store
289 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000290 slot function. If conversion to double raises an exception, obj is
291 set to NULL, and the function invoking this macro returns NULL. If
292 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
293 stored in obj, and returned from the function invoking this macro.
294*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000295#define CONVERT_TO_DOUBLE(obj, dbl) \
296 if (PyFloat_Check(obj)) \
297 dbl = PyFloat_AS_DOUBLE(obj); \
298 else if (convert_to_double(&(obj), &(dbl)) < 0) \
299 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000300
301static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000302convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000303{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000304 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000305
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000306 if (PyInt_Check(obj)) {
307 *dbl = (double)PyInt_AS_LONG(obj);
308 }
309 else if (PyLong_Check(obj)) {
310 *dbl = PyLong_AsDouble(obj);
311 if (*dbl == -1.0 && PyErr_Occurred()) {
312 *v = NULL;
313 return -1;
314 }
315 }
316 else {
317 Py_INCREF(Py_NotImplemented);
318 *v = Py_NotImplemented;
319 return -1;
320 }
321 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000322}
323
Eric Smithcfaf79c2009-10-26 14:48:55 +0000324/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
Tim Peters97019e42001-11-28 22:43:45 +0000325 XXX they pass a char buffer without passing a length.
326*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000327void
Fred Drakefd99de62000-07-09 05:02:18 +0000328PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000329{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
331 PyFloat_STR_PRECISION,
332 Py_DTSF_ADD_DOT_0, NULL);
333 strcpy(buf, tmp);
334 PyMem_Free(tmp);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000335}
336
Tim Peters72f98e92001-05-08 15:19:57 +0000337void
338PyFloat_AsReprString(char *buf, PyFloatObject *v)
339{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000340 char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
341 Py_DTSF_ADD_DOT_0, NULL);
342 strcpy(buf, tmp);
343 PyMem_Free(tmp);
Tim Peters72f98e92001-05-08 15:19:57 +0000344}
345
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000346/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000347static int
Fred Drakefd99de62000-07-09 05:02:18 +0000348float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 char *buf;
351 if (flags & Py_PRINT_RAW)
352 buf = PyOS_double_to_string(v->ob_fval,
353 'g', PyFloat_STR_PRECISION,
354 Py_DTSF_ADD_DOT_0, NULL);
355 else
356 buf = PyOS_double_to_string(v->ob_fval,
357 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
358 Py_BEGIN_ALLOW_THREADS
359 fputs(buf, fp);
360 Py_END_ALLOW_THREADS
361 PyMem_Free(buf);
362 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363}
364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365static PyObject *
Eric Smithcfaf79c2009-10-26 14:48:55 +0000366float_str_or_repr(PyFloatObject *v, int precision, char format_code)
367{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000368 PyObject *result;
369 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
370 format_code, precision,
371 Py_DTSF_ADD_DOT_0,
372 NULL);
373 if (!buf)
374 return PyErr_NoMemory();
375 result = PyString_FromString(buf);
376 PyMem_Free(buf);
377 return result;
Eric Smithcfaf79c2009-10-26 14:48:55 +0000378}
379
380static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000381float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000383 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000384}
385
386static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000387float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000388{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000389 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390}
391
Tim Peters307fa782004-09-23 08:06:40 +0000392/* Comparison is pretty much a nightmare. When comparing float to float,
393 * we do it as straightforwardly (and long-windedly) as conceivable, so
394 * that, e.g., Python x == y delivers the same result as the platform
395 * C x == y when x and/or y is a NaN.
396 * When mixing float with an integer type, there's no good *uniform* approach.
397 * Converting the double to an integer obviously doesn't work, since we
398 * may lose info from fractional bits. Converting the integer to a double
399 * also has two failure modes: (1) a long int may trigger overflow (too
400 * large to fit in the dynamic range of a C double); (2) even a C long may have
401 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
402 * 63 bits of precision, but a C double probably has only 53), and then
403 * we can falsely claim equality when low-order integer bits are lost by
404 * coercion to double. So this part is painful too.
405 */
406
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000407static PyObject*
408float_richcompare(PyObject *v, PyObject *w, int op)
409{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000410 double i, j;
411 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000412
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 assert(PyFloat_Check(v));
414 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000415
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000416 /* Switch on the type of w. Set i and j to doubles to be compared,
417 * and op to the richcomp to use.
418 */
419 if (PyFloat_Check(w))
420 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000421
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 else if (!Py_IS_FINITE(i)) {
423 if (PyInt_Check(w) || PyLong_Check(w))
424 /* If i is an infinity, its magnitude exceeds any
425 * finite integer, so it doesn't matter which int we
426 * compare i with. If i is a NaN, similarly.
427 */
428 j = 0.0;
429 else
430 goto Unimplemented;
431 }
Tim Peters307fa782004-09-23 08:06:40 +0000432
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000433 else if (PyInt_Check(w)) {
434 long jj = PyInt_AS_LONG(w);
435 /* In the worst realistic case I can imagine, C double is a
436 * Cray single with 48 bits of precision, and long has 64
437 * bits.
438 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000439#if SIZEOF_LONG > 6
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
441 if (abs >> 48) {
442 /* Needs more than 48 bits. Make it take the
443 * PyLong path.
444 */
445 PyObject *result;
446 PyObject *ww = PyLong_FromLong(jj);
Tim Peters307fa782004-09-23 08:06:40 +0000447
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000448 if (ww == NULL)
449 return NULL;
450 result = float_richcompare(v, ww, op);
451 Py_DECREF(ww);
452 return result;
453 }
Tim Peters307fa782004-09-23 08:06:40 +0000454#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000455 j = (double)jj;
456 assert((long)j == jj);
457 }
Tim Peters307fa782004-09-23 08:06:40 +0000458
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000459 else if (PyLong_Check(w)) {
460 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
461 int wsign = _PyLong_Sign(w);
462 size_t nbits;
463 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000464
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 if (vsign != wsign) {
466 /* Magnitudes are irrelevant -- the signs alone
467 * determine the outcome.
468 */
469 i = (double)vsign;
470 j = (double)wsign;
471 goto Compare;
472 }
473 /* The signs are the same. */
474 /* Convert w to a double if it fits. In particular, 0 fits. */
475 nbits = _PyLong_NumBits(w);
476 if (nbits == (size_t)-1 && PyErr_Occurred()) {
477 /* This long is so large that size_t isn't big enough
478 * to hold the # of bits. Replace with little doubles
479 * that give the same outcome -- w is so large that
480 * its magnitude must exceed the magnitude of any
481 * finite float.
482 */
483 PyErr_Clear();
484 i = (double)vsign;
485 assert(wsign != 0);
486 j = wsign * 2.0;
487 goto Compare;
488 }
489 if (nbits <= 48) {
490 j = PyLong_AsDouble(w);
491 /* It's impossible that <= 48 bits overflowed. */
492 assert(j != -1.0 || ! PyErr_Occurred());
493 goto Compare;
494 }
495 assert(wsign != 0); /* else nbits was 0 */
496 assert(vsign != 0); /* if vsign were 0, then since wsign is
497 * not 0, we would have taken the
498 * vsign != wsign branch at the start */
499 /* We want to work with non-negative numbers. */
500 if (vsign < 0) {
501 /* "Multiply both sides" by -1; this also swaps the
502 * comparator.
503 */
504 i = -i;
505 op = _Py_SwappedOp[op];
506 }
507 assert(i > 0.0);
508 (void) frexp(i, &exponent);
509 /* exponent is the # of bits in v before the radix point;
510 * we know that nbits (the # of bits in w) > 48 at this point
511 */
512 if (exponent < 0 || (size_t)exponent < nbits) {
513 i = 1.0;
514 j = 2.0;
515 goto Compare;
516 }
517 if ((size_t)exponent > nbits) {
518 i = 2.0;
519 j = 1.0;
520 goto Compare;
521 }
522 /* v and w have the same number of bits before the radix
523 * point. Construct two longs that have the same comparison
524 * outcome.
525 */
526 {
527 double fracpart;
528 double intpart;
529 PyObject *result = NULL;
530 PyObject *one = NULL;
531 PyObject *vv = NULL;
532 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000533
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000534 if (wsign < 0) {
535 ww = PyNumber_Negative(w);
536 if (ww == NULL)
537 goto Error;
538 }
539 else
540 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000541
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 fracpart = modf(i, &intpart);
543 vv = PyLong_FromDouble(intpart);
544 if (vv == NULL)
545 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000546
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 if (fracpart != 0.0) {
548 /* Shift left, and or a 1 bit into vv
549 * to represent the lost fraction.
550 */
551 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000552
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 one = PyInt_FromLong(1);
554 if (one == NULL)
555 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000556
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000557 temp = PyNumber_Lshift(ww, one);
558 if (temp == NULL)
559 goto Error;
560 Py_DECREF(ww);
561 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000562
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 temp = PyNumber_Lshift(vv, one);
564 if (temp == NULL)
565 goto Error;
566 Py_DECREF(vv);
567 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000568
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000569 temp = PyNumber_Or(vv, one);
570 if (temp == NULL)
571 goto Error;
572 Py_DECREF(vv);
573 vv = temp;
574 }
Tim Peters307fa782004-09-23 08:06:40 +0000575
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000576 r = PyObject_RichCompareBool(vv, ww, op);
577 if (r < 0)
578 goto Error;
579 result = PyBool_FromLong(r);
580 Error:
581 Py_XDECREF(vv);
582 Py_XDECREF(ww);
583 Py_XDECREF(one);
584 return result;
585 }
586 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000587
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000588 else /* w isn't float, int, or long */
589 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000590
591 Compare:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000592 PyFPE_START_PROTECT("richcompare", return NULL)
593 switch (op) {
594 case Py_EQ:
595 r = i == j;
596 break;
597 case Py_NE:
598 r = i != j;
599 break;
600 case Py_LE:
601 r = i <= j;
602 break;
603 case Py_GE:
604 r = i >= j;
605 break;
606 case Py_LT:
607 r = i < j;
608 break;
609 case Py_GT:
610 r = i > j;
611 break;
612 }
613 PyFPE_END_PROTECT(r)
614 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000615
616 Unimplemented:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000617 Py_INCREF(Py_NotImplemented);
618 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000619}
620
Guido van Rossum9bfef441993-03-29 10:43:31 +0000621static long
Fred Drakefd99de62000-07-09 05:02:18 +0000622float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000623{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000624 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000625}
626
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000628float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000630 double a,b;
631 CONVERT_TO_DOUBLE(v, a);
632 CONVERT_TO_DOUBLE(w, b);
633 PyFPE_START_PROTECT("add", return 0)
634 a = a + b;
635 PyFPE_END_PROTECT(a)
636 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000640float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000642 double a,b;
643 CONVERT_TO_DOUBLE(v, a);
644 CONVERT_TO_DOUBLE(w, b);
645 PyFPE_START_PROTECT("subtract", return 0)
646 a = a - b;
647 PyFPE_END_PROTECT(a)
648 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649}
650
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000651static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000652float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000654 double a,b;
655 CONVERT_TO_DOUBLE(v, a);
656 CONVERT_TO_DOUBLE(w, b);
657 PyFPE_START_PROTECT("multiply", return 0)
658 a = a * b;
659 PyFPE_END_PROTECT(a)
660 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661}
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000664float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000665{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000666 double a,b;
667 CONVERT_TO_DOUBLE(v, a);
668 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000669#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000670 if (b == 0.0) {
671 PyErr_SetString(PyExc_ZeroDivisionError,
672 "float division by zero");
673 return NULL;
674 }
Christian Heimes6f341092008-04-18 23:13:07 +0000675#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 PyFPE_START_PROTECT("divide", return 0)
677 a = a / b;
678 PyFPE_END_PROTECT(a)
679 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680}
681
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000683float_classic_div(PyObject *v, PyObject *w)
684{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000685 double a,b;
686 CONVERT_TO_DOUBLE(v, a);
687 CONVERT_TO_DOUBLE(w, b);
688 if (Py_DivisionWarningFlag >= 2 &&
689 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
690 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000691#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 if (b == 0.0) {
693 PyErr_SetString(PyExc_ZeroDivisionError,
694 "float division by zero");
695 return NULL;
696 }
Christian Heimes6f341092008-04-18 23:13:07 +0000697#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 PyFPE_START_PROTECT("divide", return 0)
699 a = a / b;
700 PyFPE_END_PROTECT(a)
701 return PyFloat_FromDouble(a);
Guido van Rossum393661d2001-08-31 17:40:15 +0000702}
703
704static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000705float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000706{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 double vx, wx;
708 double mod;
709 CONVERT_TO_DOUBLE(v, vx);
710 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes6f341092008-04-18 23:13:07 +0000711#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000712 if (wx == 0.0) {
713 PyErr_SetString(PyExc_ZeroDivisionError,
714 "float modulo");
715 return NULL;
716 }
Christian Heimes6f341092008-04-18 23:13:07 +0000717#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000718 PyFPE_START_PROTECT("modulo", return 0)
719 mod = fmod(vx, wx);
Mark Dickinsonecf8ec62010-12-04 12:30:41 +0000720 if (mod) {
721 /* ensure the remainder has the same sign as the denominator */
722 if ((wx < 0) != (mod < 0)) {
723 mod += wx;
724 }
725 }
726 else {
727 /* the remainder is zero, and in the presence of signed zeroes
728 fmod returns different results across platforms; ensure
729 it has the same sign as the denominator; we'd like to do
730 "mod = wx * 0.0", but that may get optimized away */
731 mod *= mod; /* hide "mod = +0" from optimizer */
732 if (wx < 0.0)
733 mod = -mod;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 }
735 PyFPE_END_PROTECT(mod)
736 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737}
738
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000739static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000740float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000741{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 double vx, wx;
743 double div, mod, floordiv;
744 CONVERT_TO_DOUBLE(v, vx);
745 CONVERT_TO_DOUBLE(w, wx);
746 if (wx == 0.0) {
747 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
748 return NULL;
749 }
750 PyFPE_START_PROTECT("divmod", return 0)
751 mod = fmod(vx, wx);
752 /* fmod is typically exact, so vx-mod is *mathematically* an
753 exact multiple of wx. But this is fp arithmetic, and fp
754 vx - mod is an approximation; the result is that div may
755 not be an exact integral value after the division, although
756 it will always be very close to one.
757 */
758 div = (vx - mod) / wx;
759 if (mod) {
760 /* ensure the remainder has the same sign as the denominator */
761 if ((wx < 0) != (mod < 0)) {
762 mod += wx;
763 div -= 1.0;
764 }
765 }
766 else {
767 /* the remainder is zero, and in the presence of signed zeroes
768 fmod returns different results across platforms; ensure
769 it has the same sign as the denominator; we'd like to do
770 "mod = wx * 0.0", but that may get optimized away */
771 mod *= mod; /* hide "mod = +0" from optimizer */
772 if (wx < 0.0)
773 mod = -mod;
774 }
775 /* snap quotient to nearest integral value */
776 if (div) {
777 floordiv = floor(div);
778 if (div - floordiv > 0.5)
779 floordiv += 1.0;
780 }
781 else {
782 /* div is zero - get the same sign as the true quotient */
783 div *= div; /* hide "div = +0" from optimizers */
784 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
785 }
786 PyFPE_END_PROTECT(floordiv)
787 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000788}
789
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000790static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000791float_floor_div(PyObject *v, PyObject *w)
792{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000794
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000795 t = float_divmod(v, w);
796 if (t == NULL || t == Py_NotImplemented)
797 return t;
798 assert(PyTuple_CheckExact(t));
799 r = PyTuple_GET_ITEM(t, 0);
800 Py_INCREF(r);
801 Py_DECREF(t);
802 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000803}
804
Mark Dickinson99d652e2009-12-30 12:12:23 +0000805/* determine whether x is an odd integer or not; assumes that
806 x is not an infinity or nan. */
807#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
808
Tim Peters63a35712001-12-11 19:57:24 +0000809static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000810float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 double iv, iw, ix;
813 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000814
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000815 if ((PyObject *)z != Py_None) {
816 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
817 "allowed unless all arguments are integers");
818 return NULL;
819 }
Tim Peters32f453e2001-09-03 08:35:41 +0000820
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000821 CONVERT_TO_DOUBLE(v, iv);
822 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000823
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 /* Sort out special cases here instead of relying on pow() */
825 if (iw == 0) { /* v**0 is 1, even 0**0 */
826 return PyFloat_FromDouble(1.0);
827 }
828 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
829 return PyFloat_FromDouble(iv);
830 }
831 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
832 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
833 }
834 if (Py_IS_INFINITY(iw)) {
835 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
836 * abs(v) > 1 (including case where v infinite)
837 *
838 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
839 * abs(v) > 1 (including case where v infinite)
840 */
841 iv = fabs(iv);
842 if (iv == 1.0)
843 return PyFloat_FromDouble(1.0);
844 else if ((iw > 0.0) == (iv > 1.0))
845 return PyFloat_FromDouble(fabs(iw)); /* return inf */
846 else
847 return PyFloat_FromDouble(0.0);
848 }
849 if (Py_IS_INFINITY(iv)) {
850 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
851 * both cases, we need to add the appropriate sign if w is
852 * an odd integer.
853 */
854 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
855 if (iw > 0.0)
856 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
857 else
858 return PyFloat_FromDouble(iw_is_odd ?
859 copysign(0.0, iv) : 0.0);
860 }
861 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
862 (already dealt with above), and an error
863 if w is negative. */
864 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
865 if (iw < 0.0) {
866 PyErr_SetString(PyExc_ZeroDivisionError,
867 "0.0 cannot be raised to a "
868 "negative power");
869 return NULL;
870 }
871 /* use correct sign if iw is odd */
872 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
873 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000874
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 if (iv < 0.0) {
876 /* Whether this is an error is a mess, and bumps into libm
877 * bugs so we have to figure it out ourselves.
878 */
879 if (iw != floor(iw)) {
880 PyErr_SetString(PyExc_ValueError, "negative number "
881 "cannot be raised to a fractional power");
882 return NULL;
883 }
884 /* iw is an exact integer, albeit perhaps a very large
885 * one. Replace iv by its absolute value and remember
886 * to negate the pow result if iw is odd.
887 */
888 iv = -iv;
889 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
890 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000891
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000892 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
893 /* (-1) ** large_integer also ends up here. Here's an
894 * extract from the comments for the previous
895 * implementation explaining why this special case is
896 * necessary:
897 *
898 * -1 raised to an exact integer should never be exceptional.
899 * Alas, some libms (chiefly glibc as of early 2003) return
900 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
901 * happen to be representable in a *C* integer. That's a
902 * bug.
903 */
904 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
905 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000906
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000907 /* Now iv and iw are finite, iw is nonzero, and iv is
908 * positive and not equal to 1.0. We finally allow
909 * the platform pow to step in and do the rest.
910 */
911 errno = 0;
912 PyFPE_START_PROTECT("pow", return NULL)
913 ix = pow(iv, iw);
914 PyFPE_END_PROTECT(ix)
915 Py_ADJUST_ERANGE1(ix);
916 if (negate_result)
917 ix = -ix;
Mark Dickinson99d652e2009-12-30 12:12:23 +0000918
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000919 if (errno != 0) {
920 /* We don't expect any errno value other than ERANGE, but
921 * the range of libm bugs appears unbounded.
922 */
923 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
924 PyExc_ValueError);
925 return NULL;
926 }
927 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000928}
929
Mark Dickinson99d652e2009-12-30 12:12:23 +0000930#undef DOUBLE_IS_ODD_INTEGER
931
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000933float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000934{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000936}
937
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000938static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000939float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000940{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000941 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000942}
943
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000944static int
Fred Drakefd99de62000-07-09 05:02:18 +0000945float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000946{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000947 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000948}
949
Guido van Rossum234f9421993-06-17 12:35:49 +0000950static int
Fred Drakefd99de62000-07-09 05:02:18 +0000951float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000952{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 if (PyInt_Check(*pw)) {
954 long x = PyInt_AsLong(*pw);
955 *pw = PyFloat_FromDouble((double)x);
956 Py_INCREF(*pv);
957 return 0;
958 }
959 else if (PyLong_Check(*pw)) {
960 double x = PyLong_AsDouble(*pw);
961 if (x == -1.0 && PyErr_Occurred())
962 return -1;
963 *pw = PyFloat_FromDouble(x);
964 Py_INCREF(*pv);
965 return 0;
966 }
967 else if (PyFloat_Check(*pw)) {
968 Py_INCREF(*pv);
969 Py_INCREF(*pw);
970 return 0;
971 }
972 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +0000973}
974
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000976float_is_integer(PyObject *v)
977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000978 double x = PyFloat_AsDouble(v);
979 PyObject *o;
980
981 if (x == -1.0 && PyErr_Occurred())
982 return NULL;
983 if (!Py_IS_FINITE(x))
984 Py_RETURN_FALSE;
985 errno = 0;
986 PyFPE_START_PROTECT("is_integer", return NULL)
987 o = (floor(x) == x) ? Py_True : Py_False;
988 PyFPE_END_PROTECT(x)
989 if (errno != 0) {
990 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
991 PyExc_ValueError);
992 return NULL;
993 }
994 Py_INCREF(o);
995 return o;
Christian Heimes6f341092008-04-18 23:13:07 +0000996}
997
998#if 0
999static PyObject *
1000float_is_inf(PyObject *v)
1001{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001002 double x = PyFloat_AsDouble(v);
1003 if (x == -1.0 && PyErr_Occurred())
1004 return NULL;
1005 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001006}
1007
1008static PyObject *
1009float_is_nan(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_NAN(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001015}
1016
1017static PyObject *
1018float_is_finite(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_FINITE(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001024}
1025#endif
1026
1027static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001028float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001029{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001030 double x = PyFloat_AsDouble(v);
1031 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001032
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001033 (void)modf(x, &wholepart);
1034 /* Try to get out cheap if this fits in a Python int. The attempt
1035 * to cast to long must be protected, as C doesn't define what
1036 * happens if the double is too big to fit in a long. Some rare
1037 * systems raise an exception then (RISCOS was mentioned as one,
1038 * and someone using a non-default option on Sun also bumped into
Mark Dickinson874d59e2011-03-26 12:18:00 +00001039 * that). Note that checking for <= LONG_MAX is unsafe: if a long
1040 * has more bits of precision than a double, casting LONG_MAX to
1041 * double may yield an approximation, and if that's rounded up,
1042 * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
1043 * expression wholepart<=LONG_MAX, despite that wholepart is
1044 * actually greater than LONG_MAX. However, assuming a two's complement
1045 * machine with no trap representation, LONG_MIN will be a power of 2 (and
1046 * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
1047 * the comparisons with (double)LONG_MIN below should be safe.
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001048 */
Mark Dickinson874d59e2011-03-26 12:18:00 +00001049 if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 const long aslong = (long)wholepart;
1051 return PyInt_FromLong(aslong);
1052 }
1053 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001054}
1055
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001056static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001057float_long(PyObject *v)
1058{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 double x = PyFloat_AsDouble(v);
1060 return PyLong_FromDouble(x);
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001061}
1062
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001063/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
1064 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1065 ndigits <= 323). Returns a Python float, or sets a Python error and
1066 returns NULL on failure (OverflowError and memory errors are possible). */
1067
1068#ifndef PY_NO_SHORT_FLOAT_REPR
1069/* version of _Py_double_round that uses the correctly-rounded string<->double
1070 conversions from Python/dtoa.c */
1071
1072/* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1073 a double. Since we're using the code in Python/dtoa.c, it should be safe
1074 to assume that C doubles are IEEE 754 binary64 format. To be on the safe
1075 side, we check this. */
1076#if DBL_MANT_DIG == 53
1077#define FIVE_POW_LIMIT 22
1078#else
1079#error "C doubles do not appear to be IEEE 754 binary64 format"
1080#endif
1081
1082PyObject *
1083_Py_double_round(double x, int ndigits) {
1084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001085 double rounded, m;
1086 Py_ssize_t buflen, mybuflen=100;
1087 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
1088 int decpt, sign, val, halfway_case;
1089 PyObject *result = NULL;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001090 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001091
Mark Dickinson115bc792012-11-17 20:18:52 +00001092 /* Easy path for the common case ndigits == 0. */
1093 if (ndigits == 0) {
1094 rounded = round(x);
1095 if (fabs(rounded - x) == 0.5)
1096 /* halfway between two integers; use round-away-from-zero */
1097 rounded = x + (x > 0.0 ? 0.5 : -0.5);
1098 return PyFloat_FromDouble(rounded);
1099 }
1100
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001101 /* The basic idea is very simple: convert and round the double to a
1102 decimal string using _Py_dg_dtoa, then convert that decimal string
1103 back to a double with _Py_dg_strtod. There's one minor difficulty:
1104 Python 2.x expects round to do round-half-away-from-zero, while
1105 _Py_dg_dtoa does round-half-to-even. So we need some way to detect
1106 and correct the halfway cases.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001107
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001108 Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1109 some odd integer k. Or in other words, a rational number x is
1110 exactly halfway between two multiples of 10**-ndigits if its
1111 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1112 -ndigits. For ndigits >= 0 the latter condition is automatically
1113 satisfied for a binary float x, since any such float has
1114 nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
1115 integral multiple of 5**-ndigits; we can check this using fmod.
1116 For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1117 to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1118 23 takes at least 54 bits of precision to represent exactly.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 Correction: a simple strategy for dealing with halfway cases is to
1121 (for the halfway cases only) call _Py_dg_dtoa with an argument of
1122 ndigits+1 instead of ndigits (thus doing an exact conversion to
1123 decimal), round the resulting string manually, and then convert
1124 back using _Py_dg_strtod.
1125 */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001126
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 /* nans, infinities and zeros should have already been dealt
1128 with by the caller (in this case, builtin_round) */
1129 assert(Py_IS_FINITE(x) && x != 0.0);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001130
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001131 /* find 2-valuation val of x */
1132 m = frexp(x, &val);
1133 while (m != floor(m)) {
1134 m *= 2.0;
1135 val--;
1136 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 /* determine whether this is a halfway case */
1139 if (val == -ndigits-1) {
1140 if (ndigits >= 0)
1141 halfway_case = 1;
1142 else if (ndigits >= -FIVE_POW_LIMIT) {
1143 double five_pow = 1.0;
1144 int i;
1145 for (i=0; i < -ndigits; i++)
1146 five_pow *= 5.0;
1147 halfway_case = fmod(x, five_pow) == 0.0;
1148 }
1149 else
1150 halfway_case = 0;
1151 }
1152 else
1153 halfway_case = 0;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001155 /* round to a decimal string; use an extra place for halfway case */
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001156 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001157 buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001158 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001159 if (buf == NULL) {
1160 PyErr_NoMemory();
1161 return NULL;
1162 }
1163 buflen = buf_end - buf;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001164
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001165 /* in halfway case, do the round-half-away-from-zero manually */
1166 if (halfway_case) {
1167 int i, carry;
1168 /* sanity check: _Py_dg_dtoa should not have stripped
1169 any zeros from the result: there should be exactly
1170 ndigits+1 places following the decimal point, and
1171 the last digit in the buffer should be a '5'.*/
1172 assert(buflen - decpt == ndigits+1);
1173 assert(buf[buflen-1] == '5');
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001174
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001175 /* increment and shift right at the same time. */
1176 decpt += 1;
1177 carry = 1;
1178 for (i=buflen-1; i-- > 0;) {
1179 carry += buf[i] - '0';
1180 buf[i+1] = carry % 10 + '0';
1181 carry /= 10;
1182 }
1183 buf[0] = carry + '0';
1184 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001185
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001186 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
1187 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1188 if (buflen + 8 > mybuflen) {
1189 mybuflen = buflen+8;
1190 mybuf = (char *)PyMem_Malloc(mybuflen);
1191 if (mybuf == NULL) {
1192 PyErr_NoMemory();
1193 goto exit;
1194 }
1195 }
1196 /* copy buf to mybuf, adding exponent, sign and leading 0 */
1197 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
1198 buf, decpt - (int)buflen);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001199
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001200 /* and convert the resulting string back to a double */
1201 errno = 0;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001202 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001203 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001204 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001205 if (errno == ERANGE && fabs(rounded) >= 1.)
1206 PyErr_SetString(PyExc_OverflowError,
1207 "rounded value too large to represent");
1208 else
1209 result = PyFloat_FromDouble(rounded);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001210
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001211 /* done computing value; now clean up */
1212 if (mybuf != shortbuf)
1213 PyMem_Free(mybuf);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001214 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001215 _Py_dg_freedtoa(buf);
1216 return result;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001217}
1218
1219#undef FIVE_POW_LIMIT
1220
1221#else /* PY_NO_SHORT_FLOAT_REPR */
1222
1223/* fallback version, to be used when correctly rounded binary<->decimal
1224 conversions aren't available */
1225
1226PyObject *
1227_Py_double_round(double x, int ndigits) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001228 double pow1, pow2, y, z;
1229 if (ndigits >= 0) {
1230 if (ndigits > 22) {
1231 /* pow1 and pow2 are each safe from overflow, but
1232 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1233 pow1 = pow(10.0, (double)(ndigits-22));
1234 pow2 = 1e22;
1235 }
1236 else {
1237 pow1 = pow(10.0, (double)ndigits);
1238 pow2 = 1.0;
1239 }
1240 y = (x*pow1)*pow2;
1241 /* if y overflows, then rounded value is exactly x */
1242 if (!Py_IS_FINITE(y))
1243 return PyFloat_FromDouble(x);
1244 }
1245 else {
1246 pow1 = pow(10.0, (double)-ndigits);
1247 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1248 y = x / pow1;
1249 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001250
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001251 z = round(y);
1252 if (fabs(y-z) == 0.5)
1253 /* halfway between two integers; use round-away-from-zero */
1254 z = y + copysign(0.5, y);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 if (ndigits >= 0)
1257 z = (z / pow2) / pow1;
1258 else
1259 z *= pow1;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001260
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001261 /* if computation resulted in overflow, raise OverflowError */
1262 if (!Py_IS_FINITE(z)) {
1263 PyErr_SetString(PyExc_OverflowError,
1264 "overflow occurred during round");
1265 return NULL;
1266 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001268 return PyFloat_FromDouble(z);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001269}
1270
1271#endif /* PY_NO_SHORT_FLOAT_REPR */
1272
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001273static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001274float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001275{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001276 if (PyFloat_CheckExact(v))
1277 Py_INCREF(v);
1278 else
1279 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1280 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001281}
1282
Mark Dickinson7103aa42008-07-15 19:08:33 +00001283/* turn ASCII hex characters into integer values and vice versa */
1284
1285static char
1286char_from_hex(int x)
1287{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001288 assert(0 <= x && x < 16);
1289 return "0123456789abcdef"[x];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001290}
1291
1292static int
1293hex_from_char(char c) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001294 int x;
1295 switch(c) {
1296 case '0':
1297 x = 0;
1298 break;
1299 case '1':
1300 x = 1;
1301 break;
1302 case '2':
1303 x = 2;
1304 break;
1305 case '3':
1306 x = 3;
1307 break;
1308 case '4':
1309 x = 4;
1310 break;
1311 case '5':
1312 x = 5;
1313 break;
1314 case '6':
1315 x = 6;
1316 break;
1317 case '7':
1318 x = 7;
1319 break;
1320 case '8':
1321 x = 8;
1322 break;
1323 case '9':
1324 x = 9;
1325 break;
1326 case 'a':
1327 case 'A':
1328 x = 10;
1329 break;
1330 case 'b':
1331 case 'B':
1332 x = 11;
1333 break;
1334 case 'c':
1335 case 'C':
1336 x = 12;
1337 break;
1338 case 'd':
1339 case 'D':
1340 x = 13;
1341 break;
1342 case 'e':
1343 case 'E':
1344 x = 14;
1345 break;
1346 case 'f':
1347 case 'F':
1348 x = 15;
1349 break;
1350 default:
1351 x = -1;
1352 break;
1353 }
1354 return x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001355}
1356
1357/* convert a float to a hexadecimal string */
1358
1359/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1360 of the form 4k+1. */
1361#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1362
1363static PyObject *
1364float_hex(PyObject *v)
1365{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001366 double x, m;
1367 int e, shift, i, si, esign;
1368 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1369 trailing NUL byte. */
1370 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001371
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001372 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001373
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1375 return float_str((PyFloatObject *)v);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001376
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001377 if (x == 0.0) {
Benjamin Petersoncf76d1f2010-07-02 19:41:39 +00001378 if (copysign(1.0, x) == -1.0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 return PyString_FromString("-0x0.0p+0");
1380 else
1381 return PyString_FromString("0x0.0p+0");
1382 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001384 m = frexp(fabs(x), &e);
1385 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1386 m = ldexp(m, shift);
1387 e -= shift;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001388
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001389 si = 0;
1390 s[si] = char_from_hex((int)m);
1391 si++;
1392 m -= (int)m;
1393 s[si] = '.';
1394 si++;
1395 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1396 m *= 16.0;
1397 s[si] = char_from_hex((int)m);
1398 si++;
1399 m -= (int)m;
1400 }
1401 s[si] = '\0';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001402
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001403 if (e < 0) {
1404 esign = (int)'-';
1405 e = -e;
1406 }
1407 else
1408 esign = (int)'+';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001409
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001410 if (x < 0.0)
1411 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1412 else
1413 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001414}
1415
1416PyDoc_STRVAR(float_hex_doc,
1417"float.hex() -> string\n\
1418\n\
1419Return a hexadecimal representation of a floating-point number.\n\
1420>>> (-0.1).hex()\n\
1421'-0x1.999999999999ap-4'\n\
1422>>> 3.14159.hex()\n\
1423'0x1.921f9f01b866ep+1'");
1424
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001425/* Case-insensitive locale-independent string match used for nan and inf
1426 detection. t should be lower-case and null-terminated. Return a nonzero
1427 result if the first strlen(t) characters of s match t and 0 otherwise. */
1428
1429static int
1430case_insensitive_match(const char *s, const char *t)
1431{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001432 while(*t && Py_TOLOWER(*s) == *t) {
1433 s++;
1434 t++;
1435 }
1436 return *t ? 0 : 1;
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001437}
1438
Mark Dickinson7103aa42008-07-15 19:08:33 +00001439/* Convert a hexadecimal string to a float. */
1440
1441static PyObject *
1442float_fromhex(PyObject *cls, PyObject *arg)
1443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001444 PyObject *result_as_float, *result;
1445 double x;
1446 long exp, top_exp, lsb, key_digit;
1447 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1448 int half_eps, digit, round_up, sign=1;
1449 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001450
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001451 /*
1452 * For the sake of simplicity and correctness, we impose an artificial
1453 * limit on ndigits, the total number of hex digits in the coefficient
1454 * The limit is chosen to ensure that, writing exp for the exponent,
1455 *
1456 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1457 * guaranteed to overflow (provided it's nonzero)
1458 *
1459 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1460 * guaranteed to underflow to 0.
1461 *
1462 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1463 * overflow in the calculation of exp and top_exp below.
1464 *
1465 * More specifically, ndigits is assumed to satisfy the following
1466 * inequalities:
1467 *
1468 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1469 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1470 *
1471 * If either of these inequalities is not satisfied, a ValueError is
1472 * raised. Otherwise, write x for the value of the hex string, and
1473 * assume x is nonzero. Then
1474 *
1475 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1476 *
1477 * Now if exp > LONG_MAX/2 then:
1478 *
1479 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1480 * = DBL_MAX_EXP
1481 *
1482 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1483 * double, so overflows. If exp < LONG_MIN/2, then
1484 *
1485 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1486 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1487 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1488 *
1489 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1490 * when converted to a C double.
1491 *
1492 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1493 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1494 */
Mark Dickinson7103aa42008-07-15 19:08:33 +00001495
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 if (PyString_AsStringAndSize(arg, &s, &length))
1497 return NULL;
1498 s_end = s + length;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 /********************
1501 * Parse the string *
1502 ********************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001504 /* leading whitespace and optional sign */
1505 while (Py_ISSPACE(*s))
1506 s++;
1507 if (*s == '-') {
1508 s++;
1509 sign = -1;
1510 }
1511 else if (*s == '+')
1512 s++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001513
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001514 /* infinities and nans */
1515 if (*s == 'i' || *s == 'I') {
1516 if (!case_insensitive_match(s+1, "nf"))
1517 goto parse_error;
1518 s += 3;
1519 x = Py_HUGE_VAL;
1520 if (case_insensitive_match(s, "inity"))
1521 s += 5;
1522 goto finished;
1523 }
1524 if (*s == 'n' || *s == 'N') {
1525 if (!case_insensitive_match(s+1, "an"))
1526 goto parse_error;
1527 s += 3;
1528 x = Py_NAN;
1529 goto finished;
1530 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 /* [0x] */
1533 s_store = s;
1534 if (*s == '0') {
1535 s++;
1536 if (*s == 'x' || *s == 'X')
1537 s++;
1538 else
1539 s = s_store;
1540 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001541
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001542 /* coefficient: <integer> [. <fraction>] */
1543 coeff_start = s;
1544 while (hex_from_char(*s) >= 0)
1545 s++;
1546 s_store = s;
1547 if (*s == '.') {
1548 s++;
1549 while (hex_from_char(*s) >= 0)
1550 s++;
1551 coeff_end = s-1;
1552 }
1553 else
1554 coeff_end = s;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001555
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001556 /* ndigits = total # of hex digits; fdigits = # after point */
1557 ndigits = coeff_end - coeff_start;
1558 fdigits = coeff_end - s_store;
1559 if (ndigits == 0)
1560 goto parse_error;
1561 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1562 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1563 goto insane_length_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001564
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001565 /* [p <exponent>] */
1566 if (*s == 'p' || *s == 'P') {
1567 s++;
1568 exp_start = s;
1569 if (*s == '-' || *s == '+')
1570 s++;
1571 if (!('0' <= *s && *s <= '9'))
1572 goto parse_error;
1573 s++;
1574 while ('0' <= *s && *s <= '9')
1575 s++;
1576 exp = strtol(exp_start, NULL, 10);
1577 }
1578 else
1579 exp = 0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001580
Mark Dickinson7103aa42008-07-15 19:08:33 +00001581/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001582#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1583 coeff_end-(j) : \
1584 coeff_end-1-(j)))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001585
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001586 /*******************************************
1587 * Compute rounded value of the hex string *
1588 *******************************************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001590 /* Discard leading zeros, and catch extreme overflow and underflow */
1591 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1592 ndigits--;
1593 if (ndigits == 0 || exp < LONG_MIN/2) {
1594 x = 0.0;
1595 goto finished;
1596 }
1597 if (exp > LONG_MAX/2)
1598 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001599
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001600 /* Adjust exponent for fractional part. */
1601 exp = exp - 4*((long)fdigits);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001602
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001603 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1604 top_exp = exp + 4*((long)ndigits - 1);
1605 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1606 top_exp++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001607
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001608 /* catch almost all nonextreme cases of overflow and underflow here */
1609 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1610 x = 0.0;
1611 goto finished;
1612 }
1613 if (top_exp > DBL_MAX_EXP)
1614 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001616 /* lsb = exponent of least significant bit of the *rounded* value.
1617 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1618 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001619
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001620 x = 0.0;
1621 if (exp >= lsb) {
1622 /* no rounding required */
1623 for (i = ndigits-1; i >= 0; i--)
1624 x = 16.0*x + HEX_DIGIT(i);
1625 x = ldexp(x, (int)(exp));
1626 goto finished;
1627 }
1628 /* rounding required. key_digit is the index of the hex digit
1629 containing the first bit to be rounded away. */
1630 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1631 key_digit = (lsb - exp - 1) / 4;
1632 for (i = ndigits-1; i > key_digit; i--)
1633 x = 16.0*x + HEX_DIGIT(i);
1634 digit = HEX_DIGIT(key_digit);
1635 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001636
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001637 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1638 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1639 if ((digit & half_eps) != 0) {
1640 round_up = 0;
1641 if ((digit & (3*half_eps-1)) != 0 ||
1642 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1643 round_up = 1;
1644 else
1645 for (i = key_digit-1; i >= 0; i--)
1646 if (HEX_DIGIT(i) != 0) {
1647 round_up = 1;
1648 break;
1649 }
1650 if (round_up == 1) {
1651 x += 2*half_eps;
1652 if (top_exp == DBL_MAX_EXP &&
1653 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1654 /* overflow corner case: pre-rounded value <
1655 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1656 goto overflow_error;
1657 }
1658 }
1659 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001660
1661 finished:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001662 /* optional trailing whitespace leading to the end of the string */
1663 while (Py_ISSPACE(*s))
1664 s++;
1665 if (s != s_end)
1666 goto parse_error;
1667 result_as_float = Py_BuildValue("(d)", sign * x);
1668 if (result_as_float == NULL)
1669 return NULL;
1670 result = PyObject_CallObject(cls, result_as_float);
1671 Py_DECREF(result_as_float);
1672 return result;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001673
1674 overflow_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 PyErr_SetString(PyExc_OverflowError,
1676 "hexadecimal value too large to represent as a float");
1677 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001678
1679 parse_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001680 PyErr_SetString(PyExc_ValueError,
1681 "invalid hexadecimal floating-point string");
1682 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001683
1684 insane_length_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001685 PyErr_SetString(PyExc_ValueError,
1686 "hexadecimal string too long to convert");
1687 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001688}
1689
1690PyDoc_STRVAR(float_fromhex_doc,
1691"float.fromhex(string) -> float\n\
1692\n\
1693Create a floating-point number from a hexadecimal string.\n\
1694>>> float.fromhex('0x1.ffffp10')\n\
16952047.984375\n\
1696>>> float.fromhex('-0x1p-1074')\n\
1697-4.9406564584124654e-324");
1698
1699
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001700static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001701float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001702{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 double self;
1704 double float_part;
1705 int exponent;
1706 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001707
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001708 PyObject *prev;
1709 PyObject *py_exponent = NULL;
1710 PyObject *numerator = NULL;
1711 PyObject *denominator = NULL;
1712 PyObject *result_pair = NULL;
1713 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001714
1715#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001716 prev = obj; \
1717 obj = call; \
1718 Py_DECREF(prev); \
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001719
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001720 CONVERT_TO_DOUBLE(v, self);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001722 if (Py_IS_INFINITY(self)) {
1723 PyErr_SetString(PyExc_OverflowError,
1724 "Cannot pass infinity to float.as_integer_ratio.");
1725 return NULL;
1726 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001727#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001728 if (Py_IS_NAN(self)) {
1729 PyErr_SetString(PyExc_ValueError,
1730 "Cannot pass NaN to float.as_integer_ratio.");
1731 return NULL;
1732 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001733#endif
1734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001735 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1736 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1737 PyFPE_END_PROTECT(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1740 float_part *= 2.0;
1741 exponent--;
1742 }
1743 /* self == float_part * 2**exponent exactly and float_part is integral.
1744 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1745 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001747 numerator = PyLong_FromDouble(float_part);
1748 if (numerator == NULL) goto error;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001749
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001750 /* fold in 2**exponent */
1751 denominator = PyLong_FromLong(1);
1752 py_exponent = PyLong_FromLong(labs((long)exponent));
1753 if (py_exponent == NULL) goto error;
1754 INPLACE_UPDATE(py_exponent,
1755 long_methods->nb_lshift(denominator, py_exponent));
1756 if (py_exponent == NULL) goto error;
1757 if (exponent > 0) {
1758 INPLACE_UPDATE(numerator,
1759 long_methods->nb_multiply(numerator, py_exponent));
1760 if (numerator == NULL) goto error;
1761 }
1762 else {
1763 Py_DECREF(denominator);
1764 denominator = py_exponent;
1765 py_exponent = NULL;
1766 }
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001768 /* Returns ints instead of longs where possible */
1769 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1770 if (numerator == NULL) goto error;
1771 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1772 if (denominator == NULL) goto error;
1773
1774 result_pair = PyTuple_Pack(2, numerator, denominator);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001775
1776#undef INPLACE_UPDATE
1777error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 Py_XDECREF(py_exponent);
1779 Py_XDECREF(denominator);
1780 Py_XDECREF(numerator);
1781 return result_pair;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001782}
1783
1784PyDoc_STRVAR(float_as_integer_ratio_doc,
1785"float.as_integer_ratio() -> (int, int)\n"
1786"\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001787"Return a pair of integers, whose ratio is exactly equal to the original\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001788"float and with a positive denominator.\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001789"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001790"\n"
1791">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001792"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001793">>> (0.0).as_integer_ratio()\n"
1794"(0, 1)\n"
1795">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001796"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001797
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001798
Jeremy Hylton938ace62002-07-17 16:30:39 +00001799static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001800float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1801
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802static PyObject *
1803float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1804{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001805 PyObject *x = Py_False; /* Integer zero */
1806 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 if (type != &PyFloat_Type)
1809 return float_subtype_new(type, args, kwds); /* Wimp out */
1810 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1811 return NULL;
1812 /* If it's a string, but not a string subclass, use
1813 PyFloat_FromString. */
1814 if (PyString_CheckExact(x))
1815 return PyFloat_FromString(x, NULL);
1816 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817}
1818
Guido van Rossumbef14172001-08-29 15:47:46 +00001819/* Wimpy, slow approach to tp_new calls for subtypes of float:
1820 first create a regular float from whatever arguments we got,
1821 then allocate a subtype instance and initialize its ob_fval
1822 from the regular float. The regular float is then thrown away.
1823*/
1824static PyObject *
1825float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1826{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001827 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001829 assert(PyType_IsSubtype(type, &PyFloat_Type));
1830 tmp = float_new(&PyFloat_Type, args, kwds);
1831 if (tmp == NULL)
1832 return NULL;
1833 assert(PyFloat_CheckExact(tmp));
1834 newobj = type->tp_alloc(type, 0);
1835 if (newobj == NULL) {
1836 Py_DECREF(tmp);
1837 return NULL;
1838 }
1839 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1840 Py_DECREF(tmp);
1841 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001842}
1843
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001844static PyObject *
1845float_getnewargs(PyFloatObject *v)
1846{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001847 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001848}
1849
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001850/* this is for the benefit of the pack/unpack routines below */
1851
1852typedef enum {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001854} float_format_type;
1855
1856static float_format_type double_format, float_format;
1857static float_format_type detected_double_format, detected_float_format;
1858
1859static PyObject *
1860float_getformat(PyTypeObject *v, PyObject* arg)
1861{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001862 char* s;
1863 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001864
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001865 if (!PyString_Check(arg)) {
1866 PyErr_Format(PyExc_TypeError,
1867 "__getformat__() argument must be string, not %.500s",
1868 Py_TYPE(arg)->tp_name);
1869 return NULL;
1870 }
1871 s = PyString_AS_STRING(arg);
1872 if (strcmp(s, "double") == 0) {
1873 r = double_format;
1874 }
1875 else if (strcmp(s, "float") == 0) {
1876 r = float_format;
1877 }
1878 else {
1879 PyErr_SetString(PyExc_ValueError,
1880 "__getformat__() argument 1 must be "
1881 "'double' or 'float'");
1882 return NULL;
1883 }
1884
1885 switch (r) {
1886 case unknown_format:
1887 return PyString_FromString("unknown");
1888 case ieee_little_endian_format:
1889 return PyString_FromString("IEEE, little-endian");
1890 case ieee_big_endian_format:
1891 return PyString_FromString("IEEE, big-endian");
1892 default:
1893 Py_FatalError("insane float_format or double_format");
1894 return NULL;
1895 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001896}
1897
1898PyDoc_STRVAR(float_getformat_doc,
1899"float.__getformat__(typestr) -> string\n"
1900"\n"
1901"You probably don't want to use this function. It exists mainly to be\n"
1902"used in Python's test suite.\n"
1903"\n"
1904"typestr must be 'double' or 'float'. This function returns whichever of\n"
1905"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1906"format of floating point numbers used by the C type named by typestr.");
1907
1908static PyObject *
1909float_setformat(PyTypeObject *v, PyObject* args)
1910{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001911 char* typestr;
1912 char* format;
1913 float_format_type f;
1914 float_format_type detected;
1915 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001917 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1918 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001919
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 if (strcmp(typestr, "double") == 0) {
1921 p = &double_format;
1922 detected = detected_double_format;
1923 }
1924 else if (strcmp(typestr, "float") == 0) {
1925 p = &float_format;
1926 detected = detected_float_format;
1927 }
1928 else {
1929 PyErr_SetString(PyExc_ValueError,
1930 "__setformat__() argument 1 must "
1931 "be 'double' or 'float'");
1932 return NULL;
1933 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001935 if (strcmp(format, "unknown") == 0) {
1936 f = unknown_format;
1937 }
1938 else if (strcmp(format, "IEEE, little-endian") == 0) {
1939 f = ieee_little_endian_format;
1940 }
1941 else if (strcmp(format, "IEEE, big-endian") == 0) {
1942 f = ieee_big_endian_format;
1943 }
1944 else {
1945 PyErr_SetString(PyExc_ValueError,
1946 "__setformat__() argument 2 must be "
1947 "'unknown', 'IEEE, little-endian' or "
1948 "'IEEE, big-endian'");
1949 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001951 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 if (f != unknown_format && f != detected) {
1954 PyErr_Format(PyExc_ValueError,
1955 "can only set %s format to 'unknown' or the "
1956 "detected platform value", typestr);
1957 return NULL;
1958 }
1959
1960 *p = f;
1961 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001962}
1963
1964PyDoc_STRVAR(float_setformat_doc,
1965"float.__setformat__(typestr, fmt) -> None\n"
1966"\n"
1967"You probably don't want to use this function. It exists mainly to be\n"
1968"used in Python's test suite.\n"
1969"\n"
1970"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1971"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1972"one of the latter two if it appears to match the underlying C reality.\n"
1973"\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001974"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001975"This affects how floats are converted to and from binary strings.");
1976
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001977static PyObject *
1978float_getzero(PyObject *v, void *closure)
1979{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001980 return PyFloat_FromDouble(0.0);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001981}
1982
Eric Smitha9f7d622008-02-17 19:46:49 +00001983static PyObject *
1984float__format__(PyObject *self, PyObject *args)
1985{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001986 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001987
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001988 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1989 return NULL;
1990 if (PyBytes_Check(format_spec))
1991 return _PyFloat_FormatAdvanced(self,
1992 PyBytes_AS_STRING(format_spec),
1993 PyBytes_GET_SIZE(format_spec));
1994 if (PyUnicode_Check(format_spec)) {
1995 /* Convert format_spec to a str */
1996 PyObject *result;
1997 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001998
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001999 if (str_spec == NULL)
2000 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002002 result = _PyFloat_FormatAdvanced(self,
2003 PyBytes_AS_STRING(str_spec),
2004 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00002005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002006 Py_DECREF(str_spec);
2007 return result;
2008 }
2009 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
2010 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002011}
2012
2013PyDoc_STRVAR(float__format__doc,
2014"float.__format__(format_spec) -> string\n"
2015"\n"
2016"Formats the float according to format_spec.");
2017
2018
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002019static PyMethodDef float_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002020 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002021 "Return self, the complex conjugate of any float."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002022 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002023 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002024 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
2025 float_as_integer_ratio_doc},
2026 {"fromhex", (PyCFunction)float_fromhex,
2027 METH_O|METH_CLASS, float_fromhex_doc},
2028 {"hex", (PyCFunction)float_hex,
2029 METH_NOARGS, float_hex_doc},
2030 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002031 "Return True if the float is an integer."},
Christian Heimes6f341092008-04-18 23:13:07 +00002032#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002033 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002034 "Return True if the float is positive or negative infinite."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002036 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002037 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002038 "Return True if the float is not a number (NaN)."},
Christian Heimes6f341092008-04-18 23:13:07 +00002039#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002040 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
2041 {"__getformat__", (PyCFunction)float_getformat,
2042 METH_O|METH_CLASS, float_getformat_doc},
2043 {"__setformat__", (PyCFunction)float_setformat,
2044 METH_VARARGS|METH_CLASS, float_setformat_doc},
2045 {"__format__", (PyCFunction)float__format__,
2046 METH_VARARGS, float__format__doc},
2047 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002048};
2049
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002050static PyGetSetDef float_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002051 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002052 (getter)float_float, (setter)NULL,
2053 "the real part of a complex number",
2054 NULL},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002055 {"imag",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002056 (getter)float_getzero, (setter)NULL,
2057 "the imaginary part of a complex number",
2058 NULL},
2059 {NULL} /* Sentinel */
2060};
2061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002062PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063"float(x) -> floating point number\n\
2064\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002065Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066
2067
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068static PyNumberMethods float_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002069 float_add, /*nb_add*/
2070 float_sub, /*nb_subtract*/
2071 float_mul, /*nb_multiply*/
2072 float_classic_div, /*nb_divide*/
2073 float_rem, /*nb_remainder*/
2074 float_divmod, /*nb_divmod*/
2075 float_pow, /*nb_power*/
2076 (unaryfunc)float_neg, /*nb_negative*/
2077 (unaryfunc)float_float, /*nb_positive*/
2078 (unaryfunc)float_abs, /*nb_absolute*/
2079 (inquiry)float_nonzero, /*nb_nonzero*/
2080 0, /*nb_invert*/
2081 0, /*nb_lshift*/
2082 0, /*nb_rshift*/
2083 0, /*nb_and*/
2084 0, /*nb_xor*/
2085 0, /*nb_or*/
2086 float_coerce, /*nb_coerce*/
2087 float_trunc, /*nb_int*/
2088 float_long, /*nb_long*/
2089 float_float, /*nb_float*/
2090 0, /* nb_oct */
2091 0, /* nb_hex */
2092 0, /* nb_inplace_add */
2093 0, /* nb_inplace_subtract */
2094 0, /* nb_inplace_multiply */
2095 0, /* nb_inplace_divide */
2096 0, /* nb_inplace_remainder */
2097 0, /* nb_inplace_power */
2098 0, /* nb_inplace_lshift */
2099 0, /* nb_inplace_rshift */
2100 0, /* nb_inplace_and */
2101 0, /* nb_inplace_xor */
2102 0, /* nb_inplace_or */
2103 float_floor_div, /* nb_floor_divide */
2104 float_div, /* nb_true_divide */
2105 0, /* nb_inplace_floor_divide */
2106 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002107};
2108
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002109PyTypeObject PyFloat_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002110 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2111 "float",
2112 sizeof(PyFloatObject),
2113 0,
2114 (destructor)float_dealloc, /* tp_dealloc */
2115 (printfunc)float_print, /* tp_print */
2116 0, /* tp_getattr */
2117 0, /* tp_setattr */
2118 0, /* tp_compare */
2119 (reprfunc)float_repr, /* tp_repr */
2120 &float_as_number, /* tp_as_number */
2121 0, /* tp_as_sequence */
2122 0, /* tp_as_mapping */
2123 (hashfunc)float_hash, /* tp_hash */
2124 0, /* tp_call */
2125 (reprfunc)float_str, /* tp_str */
2126 PyObject_GenericGetAttr, /* tp_getattro */
2127 0, /* tp_setattro */
2128 0, /* tp_as_buffer */
2129 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2130 Py_TPFLAGS_BASETYPE, /* tp_flags */
2131 float_doc, /* tp_doc */
2132 0, /* tp_traverse */
2133 0, /* tp_clear */
2134 float_richcompare, /* tp_richcompare */
2135 0, /* tp_weaklistoffset */
2136 0, /* tp_iter */
2137 0, /* tp_iternext */
2138 float_methods, /* tp_methods */
2139 0, /* tp_members */
2140 float_getset, /* tp_getset */
2141 0, /* tp_base */
2142 0, /* tp_dict */
2143 0, /* tp_descr_get */
2144 0, /* tp_descr_set */
2145 0, /* tp_dictoffset */
2146 0, /* tp_init */
2147 0, /* tp_alloc */
2148 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002149};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002150
2151void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002152_PyFloat_Init(void)
2153{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002154 /* We attempt to determine if this machine is using IEEE
2155 floating point formats by peering at the bits of some
2156 carefully chosen values. If it looks like we are on an
2157 IEEE platform, the float packing/unpacking routines can
2158 just copy bits, if not they resort to arithmetic & shifts
2159 and masks. The shifts & masks approach works on all finite
2160 values, but what happens to infinities, NaNs and signed
2161 zeroes on packing is an accident, and attempting to unpack
2162 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002163
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002164 Note that if we're on some whacked-out platform which uses
2165 IEEE formats but isn't strictly little-endian or big-
2166 endian, we will fall back to the portable shifts & masks
2167 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002168
2169#if SIZEOF_DOUBLE == 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 {
2171 double x = 9006104071832581.0;
2172 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2173 detected_double_format = ieee_big_endian_format;
2174 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2175 detected_double_format = ieee_little_endian_format;
2176 else
2177 detected_double_format = unknown_format;
2178 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002179#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002180 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002181#endif
2182
2183#if SIZEOF_FLOAT == 4
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 {
2185 float y = 16711938.0;
2186 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2187 detected_float_format = ieee_big_endian_format;
2188 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2189 detected_float_format = ieee_little_endian_format;
2190 else
2191 detected_float_format = unknown_format;
2192 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002193#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002194 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002195#endif
2196
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002197 double_format = detected_double_format;
2198 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00002199
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002200 /* Init float info */
2201 if (FloatInfoType.tp_name == 0)
2202 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002203}
2204
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002205int
2206PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002207{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002208 PyFloatObject *p;
2209 PyFloatBlock *list, *next;
2210 int i;
2211 int u; /* remaining unfreed ints per block */
2212 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002213
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002214 list = block_list;
2215 block_list = NULL;
2216 free_list = NULL;
2217 while (list != NULL) {
2218 u = 0;
2219 for (i = 0, p = &list->objects[0];
2220 i < N_FLOATOBJECTS;
2221 i++, p++) {
2222 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
2223 u++;
2224 }
2225 next = list->next;
2226 if (u) {
2227 list->next = block_list;
2228 block_list = list;
2229 for (i = 0, p = &list->objects[0];
2230 i < N_FLOATOBJECTS;
2231 i++, p++) {
2232 if (!PyFloat_CheckExact(p) ||
2233 Py_REFCNT(p) == 0) {
2234 Py_TYPE(p) = (struct _typeobject *)
2235 free_list;
2236 free_list = p;
2237 }
2238 }
2239 }
2240 else {
2241 PyMem_FREE(list);
2242 }
2243 freelist_size += u;
2244 list = next;
2245 }
2246 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002247}
2248
2249void
2250PyFloat_Fini(void)
2251{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002252 PyFloatObject *p;
2253 PyFloatBlock *list;
2254 int i;
2255 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002256
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002257 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002258
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002259 if (!Py_VerboseFlag)
2260 return;
2261 fprintf(stderr, "# cleanup floats");
2262 if (!u) {
2263 fprintf(stderr, "\n");
2264 }
2265 else {
2266 fprintf(stderr,
2267 ": %d unfreed float%s\n",
2268 u, u == 1 ? "" : "s");
2269 }
2270 if (Py_VerboseFlag > 1) {
2271 list = block_list;
2272 while (list != NULL) {
2273 for (i = 0, p = &list->objects[0];
2274 i < N_FLOATOBJECTS;
2275 i++, p++) {
2276 if (PyFloat_CheckExact(p) &&
2277 Py_REFCNT(p) != 0) {
2278 char *buf = PyOS_double_to_string(
2279 PyFloat_AS_DOUBLE(p), 'r',
2280 0, 0, NULL);
2281 if (buf) {
2282 /* XXX(twouters) cast
2283 refcount to long
2284 until %zd is
2285 universally
2286 available
2287 */
2288 fprintf(stderr,
2289 "# <float at %p, refcnt=%ld, val=%s>\n",
2290 p, (long)Py_REFCNT(p), buf);
2291 PyMem_Free(buf);
2292 }
2293 }
2294 }
2295 list = list->next;
2296 }
2297 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002298}
Tim Peters9905b942003-03-20 20:53:32 +00002299
2300/*----------------------------------------------------------------------------
2301 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002302 */
2303int
2304_PyFloat_Pack4(double x, unsigned char *p, int le)
2305{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002306 if (float_format == unknown_format) {
2307 unsigned char sign;
2308 int e;
2309 double f;
2310 unsigned int fbits;
2311 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 if (le) {
2314 p += 3;
2315 incr = -1;
2316 }
Tim Peters9905b942003-03-20 20:53:32 +00002317
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002318 if (x < 0) {
2319 sign = 1;
2320 x = -x;
2321 }
2322 else
2323 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002324
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002325 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002326
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002327 /* Normalize f to be in the range [1.0, 2.0) */
2328 if (0.5 <= f && f < 1.0) {
2329 f *= 2.0;
2330 e--;
2331 }
2332 else if (f == 0.0)
2333 e = 0;
2334 else {
2335 PyErr_SetString(PyExc_SystemError,
2336 "frexp() result out of range");
2337 return -1;
2338 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002340 if (e >= 128)
2341 goto Overflow;
2342 else if (e < -126) {
2343 /* Gradual underflow */
2344 f = ldexp(f, 126 + e);
2345 e = 0;
2346 }
2347 else if (!(e == 0 && f == 0.0)) {
2348 e += 127;
2349 f -= 1.0; /* Get rid of leading 1 */
2350 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002351
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002352 f *= 8388608.0; /* 2**23 */
2353 fbits = (unsigned int)(f + 0.5); /* Round */
2354 assert(fbits <= 8388608);
2355 if (fbits >> 23) {
2356 /* The carry propagated out of a string of 23 1 bits. */
2357 fbits = 0;
2358 ++e;
2359 if (e >= 255)
2360 goto Overflow;
2361 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002363 /* First byte */
2364 *p = (sign << 7) | (e >> 1);
2365 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002367 /* Second byte */
2368 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2369 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 /* Third byte */
2372 *p = (fbits >> 8) & 0xFF;
2373 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002375 /* Fourth byte */
2376 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002377
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002378 /* Done */
2379 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002380
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002381 }
2382 else {
2383 float y = (float)x;
2384 const char *s = (char*)&y;
2385 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002386
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002387 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2388 goto Overflow;
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002389
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002390 if ((float_format == ieee_little_endian_format && !le)
2391 || (float_format == ieee_big_endian_format && le)) {
2392 p += 3;
2393 incr = -1;
2394 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002395
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002396 for (i = 0; i < 4; i++) {
2397 *p = *s++;
2398 p += incr;
2399 }
2400 return 0;
2401 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002402 Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002403 PyErr_SetString(PyExc_OverflowError,
2404 "float too large to pack with f format");
2405 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002406}
2407
2408int
2409_PyFloat_Pack8(double x, unsigned char *p, int le)
2410{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002411 if (double_format == unknown_format) {
2412 unsigned char sign;
2413 int e;
2414 double f;
2415 unsigned int fhi, flo;
2416 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002417
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002418 if (le) {
2419 p += 7;
2420 incr = -1;
2421 }
Tim Peters9905b942003-03-20 20:53:32 +00002422
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002423 if (x < 0) {
2424 sign = 1;
2425 x = -x;
2426 }
2427 else
2428 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002430 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002431
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002432 /* Normalize f to be in the range [1.0, 2.0) */
2433 if (0.5 <= f && f < 1.0) {
2434 f *= 2.0;
2435 e--;
2436 }
2437 else if (f == 0.0)
2438 e = 0;
2439 else {
2440 PyErr_SetString(PyExc_SystemError,
2441 "frexp() result out of range");
2442 return -1;
2443 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002444
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002445 if (e >= 1024)
2446 goto Overflow;
2447 else if (e < -1022) {
2448 /* Gradual underflow */
2449 f = ldexp(f, 1022 + e);
2450 e = 0;
2451 }
2452 else if (!(e == 0 && f == 0.0)) {
2453 e += 1023;
2454 f -= 1.0; /* Get rid of leading 1 */
2455 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002457 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2458 f *= 268435456.0; /* 2**28 */
2459 fhi = (unsigned int)f; /* Truncate */
2460 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002461
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002462 f -= (double)fhi;
2463 f *= 16777216.0; /* 2**24 */
2464 flo = (unsigned int)(f + 0.5); /* Round */
2465 assert(flo <= 16777216);
2466 if (flo >> 24) {
2467 /* The carry propagated out of a string of 24 1 bits. */
2468 flo = 0;
2469 ++fhi;
2470 if (fhi >> 28) {
2471 /* And it also progagated out of the next 28 bits. */
2472 fhi = 0;
2473 ++e;
2474 if (e >= 2047)
2475 goto Overflow;
2476 }
2477 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002479 /* First byte */
2480 *p = (sign << 7) | (e >> 4);
2481 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 /* Second byte */
2484 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2485 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002487 /* Third byte */
2488 *p = (fhi >> 16) & 0xFF;
2489 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002490
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002491 /* Fourth byte */
2492 *p = (fhi >> 8) & 0xFF;
2493 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002494
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002495 /* Fifth byte */
2496 *p = fhi & 0xFF;
2497 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002499 /* Sixth byte */
2500 *p = (flo >> 16) & 0xFF;
2501 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002503 /* Seventh byte */
2504 *p = (flo >> 8) & 0xFF;
2505 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 /* Eighth byte */
2508 *p = flo & 0xFF;
2509 /* p += incr; Unneeded (for now) */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002511 /* Done */
2512 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002513
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002514 Overflow:
2515 PyErr_SetString(PyExc_OverflowError,
2516 "float too large to pack with d format");
2517 return -1;
2518 }
2519 else {
2520 const char *s = (char*)&x;
2521 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002522
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002523 if ((double_format == ieee_little_endian_format && !le)
2524 || (double_format == ieee_big_endian_format && le)) {
2525 p += 7;
2526 incr = -1;
2527 }
2528
2529 for (i = 0; i < 8; i++) {
2530 *p = *s++;
2531 p += incr;
2532 }
2533 return 0;
2534 }
Tim Peters9905b942003-03-20 20:53:32 +00002535}
2536
2537double
2538_PyFloat_Unpack4(const unsigned char *p, int le)
2539{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002540 if (float_format == unknown_format) {
2541 unsigned char sign;
2542 int e;
2543 unsigned int f;
2544 double x;
2545 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002546
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002547 if (le) {
2548 p += 3;
2549 incr = -1;
2550 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002551
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002552 /* First byte */
2553 sign = (*p >> 7) & 1;
2554 e = (*p & 0x7F) << 1;
2555 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002556
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002557 /* Second byte */
2558 e |= (*p >> 7) & 1;
2559 f = (*p & 0x7F) << 16;
2560 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002561
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002562 if (e == 255) {
2563 PyErr_SetString(
2564 PyExc_ValueError,
2565 "can't unpack IEEE 754 special value "
2566 "on non-IEEE platform");
2567 return -1;
2568 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002569
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002570 /* Third byte */
2571 f |= *p << 8;
2572 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002574 /* Fourth byte */
2575 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002576
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002577 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002578
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 /* XXX This sadly ignores Inf/NaN issues */
2580 if (e == 0)
2581 e = -126;
2582 else {
2583 x += 1.0;
2584 e -= 127;
2585 }
2586 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002587
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002588 if (sign)
2589 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002590
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002591 return x;
2592 }
2593 else {
2594 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002595
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002596 if ((float_format == ieee_little_endian_format && !le)
2597 || (float_format == ieee_big_endian_format && le)) {
2598 char buf[4];
2599 char *d = &buf[3];
2600 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002601
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002602 for (i = 0; i < 4; i++) {
2603 *d-- = *p++;
2604 }
2605 memcpy(&x, buf, 4);
2606 }
2607 else {
2608 memcpy(&x, p, 4);
2609 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002611 return x;
2612 }
Tim Peters9905b942003-03-20 20:53:32 +00002613}
2614
2615double
2616_PyFloat_Unpack8(const unsigned char *p, int le)
2617{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002618 if (double_format == unknown_format) {
2619 unsigned char sign;
2620 int e;
2621 unsigned int fhi, flo;
2622 double x;
2623 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002624
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002625 if (le) {
2626 p += 7;
2627 incr = -1;
2628 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002629
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002630 /* First byte */
2631 sign = (*p >> 7) & 1;
2632 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002634 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002635
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002636 /* Second byte */
2637 e |= (*p >> 4) & 0xF;
2638 fhi = (*p & 0xF) << 24;
2639 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002641 if (e == 2047) {
2642 PyErr_SetString(
2643 PyExc_ValueError,
2644 "can't unpack IEEE 754 special value "
2645 "on non-IEEE platform");
2646 return -1.0;
2647 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002648
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002649 /* Third byte */
2650 fhi |= *p << 16;
2651 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002652
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002653 /* Fourth byte */
2654 fhi |= *p << 8;
2655 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 /* Fifth byte */
2658 fhi |= *p;
2659 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002661 /* Sixth byte */
2662 flo = *p << 16;
2663 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 /* Seventh byte */
2666 flo |= *p << 8;
2667 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002668
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002669 /* Eighth byte */
2670 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002671
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002672 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2673 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002675 if (e == 0)
2676 e = -1022;
2677 else {
2678 x += 1.0;
2679 e -= 1023;
2680 }
2681 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002682
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002683 if (sign)
2684 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002685
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002686 return x;
2687 }
2688 else {
2689 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 if ((double_format == ieee_little_endian_format && !le)
2692 || (double_format == ieee_big_endian_format && le)) {
2693 char buf[8];
2694 char *d = &buf[7];
2695 int i;
2696
2697 for (i = 0; i < 8; i++) {
2698 *d-- = *p++;
2699 }
2700 memcpy(&x, buf, 8);
2701 }
2702 else {
2703 memcpy(&x, p, 8);
2704 }
2705
2706 return x;
2707 }
Tim Peters9905b942003-03-20 20:53:32 +00002708}