blob: 5954d39cdb33fa5ead61de725996402083ac73fa [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Float object implementation */
2
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003/* XXX There should be overflow checks here, but it's hard to check
4 for any kind of float exception without losing portability. */
5
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00007#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Mark Dickinson7103aa42008-07-15 19:08:33 +000012#undef MAX
13#undef MIN
14#define MAX(x, y) ((x) < (y) ? (y) : (x))
15#define MIN(x, y) ((x) < (y) ? (x) : (y))
16
Neal Norwitz5f95a792008-01-25 08:04:16 +000017#ifdef _OSF_SOURCE
18/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
19extern int finite(double);
20#endif
21
Guido van Rossum93ad0df1997-05-13 21:00:42 +000022/* Special free list -- see comments for same code in intobject.c. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000023#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
24#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
25#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000026
Guido van Rossum3fce8831999-03-12 19:43:17 +000027struct _floatblock {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000028 struct _floatblock *next;
29 PyFloatObject objects[N_FLOATOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000030};
31
32typedef struct _floatblock PyFloatBlock;
33
34static PyFloatBlock *block_list = NULL;
35static PyFloatObject *free_list = NULL;
36
Guido van Rossum93ad0df1997-05-13 21:00:42 +000037static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000038fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000040 PyFloatObject *p, *q;
41 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
42 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
43 if (p == NULL)
44 return (PyFloatObject *) PyErr_NoMemory();
45 ((PyFloatBlock *)p)->next = block_list;
46 block_list = (PyFloatBlock *)p;
47 p = &((PyFloatBlock *)p)->objects[0];
48 q = p + N_FLOATOBJECTS;
49 while (--q > p)
50 Py_TYPE(q) = (struct _typeobject *)(q-1);
51 Py_TYPE(q) = NULL;
52 return p + N_FLOATOBJECTS - 1;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000053}
54
Christian Heimesdfdfaab2007-12-01 11:20:10 +000055double
56PyFloat_GetMax(void)
57{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000058 return DBL_MAX;
Christian Heimesdfdfaab2007-12-01 11:20:10 +000059}
60
61double
62PyFloat_GetMin(void)
63{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000064 return DBL_MIN;
Christian Heimesdfdfaab2007-12-01 11:20:10 +000065}
66
Benjamin Petersona72d15c2017-09-13 21:20:29 -070067static PyTypeObject FloatInfoType;
Christian Heimesc94e2b52008-01-14 04:13:37 +000068
69PyDoc_STRVAR(floatinfo__doc__,
Benjamin Petersonbf9ec9b2009-06-16 23:13:09 +000070"sys.float_info\n\
Christian Heimesc94e2b52008-01-14 04:13:37 +000071\n\
72A structseq holding information about the float type. It contains low level\n\
73information about the precision and internal representation. Please study\n\
74your system's :file:`float.h` for more information.");
75
76static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000077 {"max", "DBL_MAX -- maximum representable finite float"},
78 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
79 "is representable"},
80 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
81 "is representable"},
Miss Islington (bot)e3e8bdc2018-03-26 03:58:47 -070082 {"min", "DBL_MIN -- Minimum positive normalized float"},
Antoine Pitrouc83ea132010-05-09 14:46:46 +000083 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
84 "is a normalized float"},
85 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
86 "a normalized"},
87 {"dig", "DBL_DIG -- digits"},
88 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
89 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
90 "representable float"},
91 {"radix", "FLT_RADIX -- radix of exponent"},
Miss Islington (bot)e3e8bdc2018-03-26 03:58:47 -070092 {"rounds", "FLT_ROUNDS -- rounding mode"},
Antoine Pitrouc83ea132010-05-09 14:46:46 +000093 {0}
Christian Heimesc94e2b52008-01-14 04:13:37 +000094};
95
96static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000097 "sys.float_info", /* name */
98 floatinfo__doc__, /* doc */
99 floatinfo_fields, /* fields */
100 11
Christian Heimesc94e2b52008-01-14 04:13:37 +0000101};
102
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000103PyObject *
104PyFloat_GetInfo(void)
105{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000106 PyObject* floatinfo;
107 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000108
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000109 floatinfo = PyStructSequence_New(&FloatInfoType);
110 if (floatinfo == NULL) {
111 return NULL;
112 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000113
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114#define SetIntFlag(flag) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000115 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
Christian Heimesc94e2b52008-01-14 04:13:37 +0000116#define SetDblFlag(flag) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000117 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000118
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000119 SetDblFlag(DBL_MAX);
120 SetIntFlag(DBL_MAX_EXP);
121 SetIntFlag(DBL_MAX_10_EXP);
122 SetDblFlag(DBL_MIN);
123 SetIntFlag(DBL_MIN_EXP);
124 SetIntFlag(DBL_MIN_10_EXP);
125 SetIntFlag(DBL_DIG);
126 SetIntFlag(DBL_MANT_DIG);
127 SetDblFlag(DBL_EPSILON);
128 SetIntFlag(FLT_RADIX);
129 SetIntFlag(FLT_ROUNDS);
Christian Heimesc94e2b52008-01-14 04:13:37 +0000130#undef SetIntFlag
131#undef SetDblFlag
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000132
133 if (PyErr_Occurred()) {
134 Py_CLEAR(floatinfo);
135 return NULL;
136 }
137 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000143 register PyFloatObject *op;
144 if (free_list == NULL) {
145 if ((free_list = fill_free_list()) == NULL)
146 return NULL;
147 }
148 /* Inline PyObject_New */
149 op = free_list;
150 free_list = (PyFloatObject *)Py_TYPE(op);
Martin Panter646b5282016-06-21 23:58:05 +0000151 (void)PyObject_INIT(op, &PyFloat_Type);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000152 op->ob_fval = fval;
153 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154}
155
Tim Petersef14d732000-09-23 03:39:17 +0000156/**************************************************************************
157RED_FLAG 22-Sep-2000 tim
158PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
159
1601. If v was a regular string, *pend was set to point to its terminating
161 null byte. That's useless (the caller can find that without any
162 help from this function!).
163
1642. If v was a Unicode string, or an object convertible to a character
165 buffer, *pend was set to point into stack trash (the auto temp
166 vector holding the character buffer). That was downright dangerous.
167
168Since we can't change the interface of a public API function, pend is
169still supported but now *officially* useless: if pend is not NULL,
170*pend is set to NULL.
171**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000173PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000175 const char *s, *last, *end;
176 double x;
177 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000178#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 char *s_buffer = NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000180#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000181 Py_ssize_t len;
Serhiy Storchaka61565602015-11-20 21:56:21 +0200182 PyObject *str = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000183 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
Serhiy Storchaka61565602015-11-20 21:56:21 +0200205 else if (!PyObject_AsCharBuffer(v, &s, &len)) {
206 /* Copy to NUL-terminated buffer. */
207 str = PyString_FromStringAndSize(s, len);
208 if (str == NULL)
209 return NULL;
210 s = PyString_AS_STRING(str);
211 }
212 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000213 PyErr_SetString(PyExc_TypeError,
214 "float() argument must be a string or a number");
215 return NULL;
216 }
217 last = s + len;
Mark Dickinson6d6b2202009-04-26 16:04:05 +0000218
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000219 while (Py_ISSPACE(*s))
220 s++;
221 /* We don't care about overflow or underflow. If the platform
222 * supports them, infinities and signed zeroes (on underflow) are
223 * fine. */
224 x = PyOS_string_to_double(s, (char **)&end, NULL);
225 if (x == -1.0 && PyErr_Occurred())
226 goto error;
227 while (Py_ISSPACE(*end))
228 end++;
229 if (end == last)
230 result = PyFloat_FromDouble(x);
231 else {
232 PyOS_snprintf(buffer, sizeof(buffer),
233 "invalid literal for float(): %.200s", s);
234 PyErr_SetString(PyExc_ValueError, buffer);
235 result = NULL;
236 }
Mark Dickinson8568b192009-10-26 21:11:20 +0000237
238 error:
239#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 if (s_buffer)
241 PyMem_FREE(s_buffer);
Mark Dickinson8568b192009-10-26 21:11:20 +0000242#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +0200243 Py_XDECREF(str);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000245}
246
Guido van Rossum234f9421993-06-17 12:35:49 +0000247static void
Fred Drakefd99de62000-07-09 05:02:18 +0000248float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000249{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 if (PyFloat_CheckExact(op)) {
251 Py_TYPE(op) = (struct _typeobject *)free_list;
252 free_list = op;
253 }
254 else
255 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000256}
257
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258double
Fred Drakefd99de62000-07-09 05:02:18 +0000259PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 PyNumberMethods *nb;
262 PyFloatObject *fo;
263 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 if (op && PyFloat_Check(op))
266 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000267
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 if (op == NULL) {
269 PyErr_BadArgument();
270 return -1;
271 }
Tim Petersd2364e82001-11-01 20:09:42 +0000272
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
274 PyErr_SetString(PyExc_TypeError, "a float is required");
275 return -1;
276 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 fo = (PyFloatObject*) (*nb->nb_float) (op);
279 if (fo == NULL)
280 return -1;
281 if (!PyFloat_Check(fo)) {
Benjamin Petersonf0506482015-03-06 09:08:44 -0500282 Py_DECREF(fo);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 PyErr_SetString(PyExc_TypeError,
284 "nb_float should return float object");
285 return -1;
286 }
Tim Petersd2364e82001-11-01 20:09:42 +0000287
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 val = PyFloat_AS_DOUBLE(fo);
289 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000290
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000291 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
294/* Methods */
295
Neil Schemenauer32117e52001-01-04 01:44:34 +0000296/* Macro and helper that convert PyObject obj to a C double and store
297 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000298 slot function. If conversion to double raises an exception, obj is
299 set to NULL, and the function invoking this macro returns NULL. If
300 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
301 stored in obj, and returned from the function invoking this macro.
302*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303#define CONVERT_TO_DOUBLE(obj, dbl) \
304 if (PyFloat_Check(obj)) \
305 dbl = PyFloat_AS_DOUBLE(obj); \
306 else if (convert_to_double(&(obj), &(dbl)) < 0) \
307 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000308
309static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000310convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000311{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000312 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000313
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000314 if (PyInt_Check(obj)) {
315 *dbl = (double)PyInt_AS_LONG(obj);
316 }
317 else if (PyLong_Check(obj)) {
318 *dbl = PyLong_AsDouble(obj);
319 if (*dbl == -1.0 && PyErr_Occurred()) {
320 *v = NULL;
321 return -1;
322 }
323 }
324 else {
325 Py_INCREF(Py_NotImplemented);
326 *v = Py_NotImplemented;
327 return -1;
328 }
329 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000330}
331
Eric Smithcfaf79c2009-10-26 14:48:55 +0000332/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
Tim Peters97019e42001-11-28 22:43:45 +0000333 XXX they pass a char buffer without passing a length.
334*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000335void
Fred Drakefd99de62000-07-09 05:02:18 +0000336PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000337{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000338 char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
339 PyFloat_STR_PRECISION,
340 Py_DTSF_ADD_DOT_0, NULL);
341 strcpy(buf, tmp);
342 PyMem_Free(tmp);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000343}
344
Tim Peters72f98e92001-05-08 15:19:57 +0000345void
346PyFloat_AsReprString(char *buf, PyFloatObject *v)
347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000348 char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
349 Py_DTSF_ADD_DOT_0, NULL);
350 strcpy(buf, tmp);
351 PyMem_Free(tmp);
Tim Peters72f98e92001-05-08 15:19:57 +0000352}
353
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000354/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000355static int
Fred Drakefd99de62000-07-09 05:02:18 +0000356float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 char *buf;
359 if (flags & Py_PRINT_RAW)
360 buf = PyOS_double_to_string(v->ob_fval,
361 'g', PyFloat_STR_PRECISION,
362 Py_DTSF_ADD_DOT_0, NULL);
363 else
364 buf = PyOS_double_to_string(v->ob_fval,
365 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
366 Py_BEGIN_ALLOW_THREADS
367 fputs(buf, fp);
368 Py_END_ALLOW_THREADS
369 PyMem_Free(buf);
370 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371}
372
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373static PyObject *
Eric Smithcfaf79c2009-10-26 14:48:55 +0000374float_str_or_repr(PyFloatObject *v, int precision, char format_code)
375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000376 PyObject *result;
377 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
378 format_code, precision,
379 Py_DTSF_ADD_DOT_0,
380 NULL);
381 if (!buf)
382 return PyErr_NoMemory();
383 result = PyString_FromString(buf);
384 PyMem_Free(buf);
385 return result;
Eric Smithcfaf79c2009-10-26 14:48:55 +0000386}
387
388static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000389float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000391 return float_str_or_repr(v, 0, 'r');
Guido van Rossum57072eb1999-12-23 19:00:28 +0000392}
393
394static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000395float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000396{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000397 return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Tim Peters307fa782004-09-23 08:06:40 +0000400/* Comparison is pretty much a nightmare. When comparing float to float,
401 * we do it as straightforwardly (and long-windedly) as conceivable, so
402 * that, e.g., Python x == y delivers the same result as the platform
403 * C x == y when x and/or y is a NaN.
404 * When mixing float with an integer type, there's no good *uniform* approach.
405 * Converting the double to an integer obviously doesn't work, since we
406 * may lose info from fractional bits. Converting the integer to a double
407 * also has two failure modes: (1) a long int may trigger overflow (too
408 * large to fit in the dynamic range of a C double); (2) even a C long may have
Martin Panter4f23cab2016-05-08 13:45:55 +0000409 * more bits than fit in a C double (e.g., on a 64-bit box long may have
Tim Peters307fa782004-09-23 08:06:40 +0000410 * 63 bits of precision, but a C double probably has only 53), and then
411 * we can falsely claim equality when low-order integer bits are lost by
412 * coercion to double. So this part is painful too.
413 */
414
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000415static PyObject*
416float_richcompare(PyObject *v, PyObject *w, int op)
417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 double i, j;
419 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000420
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 assert(PyFloat_Check(v));
422 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000423
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000424 /* Switch on the type of w. Set i and j to doubles to be compared,
425 * and op to the richcomp to use.
426 */
427 if (PyFloat_Check(w))
428 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000429
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000430 else if (!Py_IS_FINITE(i)) {
Serhiy Storchaka48c8bf22018-07-31 09:09:36 +0300431 if (_PyAnyInt_Check(w))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432 /* If i is an infinity, its magnitude exceeds any
433 * finite integer, so it doesn't matter which int we
434 * compare i with. If i is a NaN, similarly.
435 */
436 j = 0.0;
437 else
438 goto Unimplemented;
439 }
Tim Peters307fa782004-09-23 08:06:40 +0000440
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 else if (PyInt_Check(w)) {
442 long jj = PyInt_AS_LONG(w);
443 /* In the worst realistic case I can imagine, C double is a
444 * Cray single with 48 bits of precision, and long has 64
445 * bits.
446 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000447#if SIZEOF_LONG > 6
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000448 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
449 if (abs >> 48) {
450 /* Needs more than 48 bits. Make it take the
451 * PyLong path.
452 */
453 PyObject *result;
454 PyObject *ww = PyLong_FromLong(jj);
Tim Peters307fa782004-09-23 08:06:40 +0000455
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000456 if (ww == NULL)
457 return NULL;
458 result = float_richcompare(v, ww, op);
459 Py_DECREF(ww);
460 return result;
461 }
Tim Peters307fa782004-09-23 08:06:40 +0000462#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000463 j = (double)jj;
464 assert((long)j == jj);
465 }
Tim Peters307fa782004-09-23 08:06:40 +0000466
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 else if (PyLong_Check(w)) {
468 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
469 int wsign = _PyLong_Sign(w);
470 size_t nbits;
471 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000472
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000473 if (vsign != wsign) {
474 /* Magnitudes are irrelevant -- the signs alone
475 * determine the outcome.
476 */
477 i = (double)vsign;
478 j = (double)wsign;
479 goto Compare;
480 }
481 /* The signs are the same. */
482 /* Convert w to a double if it fits. In particular, 0 fits. */
483 nbits = _PyLong_NumBits(w);
484 if (nbits == (size_t)-1 && PyErr_Occurred()) {
485 /* This long is so large that size_t isn't big enough
486 * to hold the # of bits. Replace with little doubles
487 * that give the same outcome -- w is so large that
488 * its magnitude must exceed the magnitude of any
489 * finite float.
490 */
491 PyErr_Clear();
492 i = (double)vsign;
493 assert(wsign != 0);
494 j = wsign * 2.0;
495 goto Compare;
496 }
497 if (nbits <= 48) {
498 j = PyLong_AsDouble(w);
499 /* It's impossible that <= 48 bits overflowed. */
500 assert(j != -1.0 || ! PyErr_Occurred());
501 goto Compare;
502 }
503 assert(wsign != 0); /* else nbits was 0 */
504 assert(vsign != 0); /* if vsign were 0, then since wsign is
505 * not 0, we would have taken the
506 * vsign != wsign branch at the start */
507 /* We want to work with non-negative numbers. */
508 if (vsign < 0) {
509 /* "Multiply both sides" by -1; this also swaps the
510 * comparator.
511 */
512 i = -i;
513 op = _Py_SwappedOp[op];
514 }
515 assert(i > 0.0);
516 (void) frexp(i, &exponent);
517 /* exponent is the # of bits in v before the radix point;
518 * we know that nbits (the # of bits in w) > 48 at this point
519 */
520 if (exponent < 0 || (size_t)exponent < nbits) {
521 i = 1.0;
522 j = 2.0;
523 goto Compare;
524 }
525 if ((size_t)exponent > nbits) {
526 i = 2.0;
527 j = 1.0;
528 goto Compare;
529 }
530 /* v and w have the same number of bits before the radix
531 * point. Construct two longs that have the same comparison
532 * outcome.
533 */
534 {
535 double fracpart;
536 double intpart;
537 PyObject *result = NULL;
538 PyObject *one = NULL;
539 PyObject *vv = NULL;
540 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000541
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 if (wsign < 0) {
543 ww = PyNumber_Negative(w);
544 if (ww == NULL)
545 goto Error;
546 }
547 else
548 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000549
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 fracpart = modf(i, &intpart);
551 vv = PyLong_FromDouble(intpart);
552 if (vv == NULL)
553 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000554
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 if (fracpart != 0.0) {
556 /* Shift left, and or a 1 bit into vv
557 * to represent the lost fraction.
558 */
559 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000560
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000561 one = PyInt_FromLong(1);
562 if (one == NULL)
563 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000564
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 temp = PyNumber_Lshift(ww, one);
566 if (temp == NULL)
567 goto Error;
568 Py_DECREF(ww);
569 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000570
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000571 temp = PyNumber_Lshift(vv, one);
572 if (temp == NULL)
573 goto Error;
574 Py_DECREF(vv);
575 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000576
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 temp = PyNumber_Or(vv, one);
578 if (temp == NULL)
579 goto Error;
580 Py_DECREF(vv);
581 vv = temp;
582 }
Tim Peters307fa782004-09-23 08:06:40 +0000583
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000584 r = PyObject_RichCompareBool(vv, ww, op);
585 if (r < 0)
586 goto Error;
587 result = PyBool_FromLong(r);
588 Error:
589 Py_XDECREF(vv);
590 Py_XDECREF(ww);
591 Py_XDECREF(one);
592 return result;
593 }
594 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000595
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000596 else /* w isn't float, int, or long */
597 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000598
599 Compare:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000600 PyFPE_START_PROTECT("richcompare", return NULL)
601 switch (op) {
602 case Py_EQ:
603 r = i == j;
604 break;
605 case Py_NE:
606 r = i != j;
607 break;
608 case Py_LE:
609 r = i <= j;
610 break;
611 case Py_GE:
612 r = i >= j;
613 break;
614 case Py_LT:
615 r = i < j;
616 break;
617 case Py_GT:
618 r = i > j;
619 break;
620 }
621 PyFPE_END_PROTECT(r)
622 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000623
624 Unimplemented:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000625 Py_INCREF(Py_NotImplemented);
626 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000627}
628
Guido van Rossum9bfef441993-03-29 10:43:31 +0000629static long
Fred Drakefd99de62000-07-09 05:02:18 +0000630float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000631{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000632 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000633}
634
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000636float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000638 double a,b;
639 CONVERT_TO_DOUBLE(v, a);
640 CONVERT_TO_DOUBLE(w, b);
641 PyFPE_START_PROTECT("add", return 0)
642 a = a + b;
643 PyFPE_END_PROTECT(a)
644 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645}
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000648float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000650 double a,b;
651 CONVERT_TO_DOUBLE(v, a);
652 CONVERT_TO_DOUBLE(w, b);
653 PyFPE_START_PROTECT("subtract", return 0)
654 a = a - b;
655 PyFPE_END_PROTECT(a)
656 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000660float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000662 double a,b;
663 CONVERT_TO_DOUBLE(v, a);
664 CONVERT_TO_DOUBLE(w, b);
665 PyFPE_START_PROTECT("multiply", return 0)
666 a = a * b;
667 PyFPE_END_PROTECT(a)
668 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000669}
670
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000672float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 double a,b;
675 CONVERT_TO_DOUBLE(v, a);
676 CONVERT_TO_DOUBLE(w, b);
Christian Heimes6f341092008-04-18 23:13:07 +0000677#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000678 if (b == 0.0) {
679 PyErr_SetString(PyExc_ZeroDivisionError,
680 "float division by zero");
681 return NULL;
682 }
Christian Heimes6f341092008-04-18 23:13:07 +0000683#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 PyFPE_START_PROTECT("divide", return 0)
685 a = a / b;
686 PyFPE_END_PROTECT(a)
687 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688}
689
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000690static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000691float_classic_div(PyObject *v, PyObject *w)
692{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000693 double a,b;
694 CONVERT_TO_DOUBLE(v, a);
695 CONVERT_TO_DOUBLE(w, b);
696 if (Py_DivisionWarningFlag >= 2 &&
697 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
698 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000699#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 if (b == 0.0) {
701 PyErr_SetString(PyExc_ZeroDivisionError,
702 "float division by zero");
703 return NULL;
704 }
Christian Heimes6f341092008-04-18 23:13:07 +0000705#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 PyFPE_START_PROTECT("divide", return 0)
707 a = a / b;
708 PyFPE_END_PROTECT(a)
709 return PyFloat_FromDouble(a);
Guido van Rossum393661d2001-08-31 17:40:15 +0000710}
711
712static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000713float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000714{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000715 double vx, wx;
716 double mod;
717 CONVERT_TO_DOUBLE(v, vx);
718 CONVERT_TO_DOUBLE(w, wx);
Christian Heimes6f341092008-04-18 23:13:07 +0000719#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000720 if (wx == 0.0) {
721 PyErr_SetString(PyExc_ZeroDivisionError,
722 "float modulo");
723 return NULL;
724 }
Christian Heimes6f341092008-04-18 23:13:07 +0000725#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000726 PyFPE_START_PROTECT("modulo", return 0)
727 mod = fmod(vx, wx);
Mark Dickinsonecf8ec62010-12-04 12:30:41 +0000728 if (mod) {
729 /* ensure the remainder has the same sign as the denominator */
730 if ((wx < 0) != (mod < 0)) {
731 mod += wx;
732 }
733 }
734 else {
735 /* the remainder is zero, and in the presence of signed zeroes
736 fmod returns different results across platforms; ensure
737 it has the same sign as the denominator; we'd like to do
738 "mod = wx * 0.0", but that may get optimized away */
739 mod *= mod; /* hide "mod = +0" from optimizer */
740 if (wx < 0.0)
741 mod = -mod;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 }
743 PyFPE_END_PROTECT(mod)
744 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000745}
746
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000748float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000749{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 double vx, wx;
751 double div, mod, floordiv;
752 CONVERT_TO_DOUBLE(v, vx);
753 CONVERT_TO_DOUBLE(w, wx);
754 if (wx == 0.0) {
755 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
756 return NULL;
757 }
758 PyFPE_START_PROTECT("divmod", return 0)
759 mod = fmod(vx, wx);
760 /* fmod is typically exact, so vx-mod is *mathematically* an
761 exact multiple of wx. But this is fp arithmetic, and fp
762 vx - mod is an approximation; the result is that div may
763 not be an exact integral value after the division, although
764 it will always be very close to one.
765 */
766 div = (vx - mod) / wx;
767 if (mod) {
768 /* ensure the remainder has the same sign as the denominator */
769 if ((wx < 0) != (mod < 0)) {
770 mod += wx;
771 div -= 1.0;
772 }
773 }
774 else {
775 /* the remainder is zero, and in the presence of signed zeroes
776 fmod returns different results across platforms; ensure
777 it has the same sign as the denominator; we'd like to do
778 "mod = wx * 0.0", but that may get optimized away */
779 mod *= mod; /* hide "mod = +0" from optimizer */
780 if (wx < 0.0)
781 mod = -mod;
782 }
783 /* snap quotient to nearest integral value */
784 if (div) {
785 floordiv = floor(div);
786 if (div - floordiv > 0.5)
787 floordiv += 1.0;
788 }
789 else {
790 /* div is zero - get the same sign as the true quotient */
791 div *= div; /* hide "div = +0" from optimizers */
792 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
793 }
794 PyFPE_END_PROTECT(floordiv)
795 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000796}
797
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000798static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000799float_floor_div(PyObject *v, PyObject *w)
800{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000801 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000802
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 t = float_divmod(v, w);
804 if (t == NULL || t == Py_NotImplemented)
805 return t;
806 assert(PyTuple_CheckExact(t));
807 r = PyTuple_GET_ITEM(t, 0);
808 Py_INCREF(r);
809 Py_DECREF(t);
810 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000811}
812
Mark Dickinson99d652e2009-12-30 12:12:23 +0000813/* determine whether x is an odd integer or not; assumes that
814 x is not an infinity or nan. */
815#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
816
Tim Peters63a35712001-12-11 19:57:24 +0000817static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000818float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000820 double iv, iw, ix;
821 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000822
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 if ((PyObject *)z != Py_None) {
824 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
825 "allowed unless all arguments are integers");
826 return NULL;
827 }
Tim Peters32f453e2001-09-03 08:35:41 +0000828
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000829 CONVERT_TO_DOUBLE(v, iv);
830 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000831
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000832 /* Sort out special cases here instead of relying on pow() */
833 if (iw == 0) { /* v**0 is 1, even 0**0 */
834 return PyFloat_FromDouble(1.0);
835 }
836 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
837 return PyFloat_FromDouble(iv);
838 }
839 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
840 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
841 }
842 if (Py_IS_INFINITY(iw)) {
843 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
844 * abs(v) > 1 (including case where v infinite)
845 *
846 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
847 * abs(v) > 1 (including case where v infinite)
848 */
849 iv = fabs(iv);
850 if (iv == 1.0)
851 return PyFloat_FromDouble(1.0);
852 else if ((iw > 0.0) == (iv > 1.0))
853 return PyFloat_FromDouble(fabs(iw)); /* return inf */
854 else
855 return PyFloat_FromDouble(0.0);
856 }
857 if (Py_IS_INFINITY(iv)) {
858 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
859 * both cases, we need to add the appropriate sign if w is
860 * an odd integer.
861 */
862 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
863 if (iw > 0.0)
864 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
865 else
866 return PyFloat_FromDouble(iw_is_odd ?
867 copysign(0.0, iv) : 0.0);
868 }
869 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
870 (already dealt with above), and an error
871 if w is negative. */
872 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
873 if (iw < 0.0) {
874 PyErr_SetString(PyExc_ZeroDivisionError,
875 "0.0 cannot be raised to a "
876 "negative power");
877 return NULL;
878 }
879 /* use correct sign if iw is odd */
880 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
881 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000882
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000883 if (iv < 0.0) {
884 /* Whether this is an error is a mess, and bumps into libm
885 * bugs so we have to figure it out ourselves.
886 */
887 if (iw != floor(iw)) {
888 PyErr_SetString(PyExc_ValueError, "negative number "
889 "cannot be raised to a fractional power");
890 return NULL;
891 }
892 /* iw is an exact integer, albeit perhaps a very large
893 * one. Replace iv by its absolute value and remember
894 * to negate the pow result if iw is odd.
895 */
896 iv = -iv;
897 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
898 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000899
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000900 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
901 /* (-1) ** large_integer also ends up here. Here's an
902 * extract from the comments for the previous
903 * implementation explaining why this special case is
904 * necessary:
905 *
906 * -1 raised to an exact integer should never be exceptional.
907 * Alas, some libms (chiefly glibc as of early 2003) return
908 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
909 * happen to be representable in a *C* integer. That's a
910 * bug.
911 */
912 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
913 }
Mark Dickinson99d652e2009-12-30 12:12:23 +0000914
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 /* Now iv and iw are finite, iw is nonzero, and iv is
916 * positive and not equal to 1.0. We finally allow
917 * the platform pow to step in and do the rest.
918 */
919 errno = 0;
920 PyFPE_START_PROTECT("pow", return NULL)
921 ix = pow(iv, iw);
922 PyFPE_END_PROTECT(ix)
923 Py_ADJUST_ERANGE1(ix);
924 if (negate_result)
925 ix = -ix;
Mark Dickinson99d652e2009-12-30 12:12:23 +0000926
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000927 if (errno != 0) {
928 /* We don't expect any errno value other than ERANGE, but
929 * the range of libm bugs appears unbounded.
930 */
931 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
932 PyExc_ValueError);
933 return NULL;
934 }
935 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000936}
937
Mark Dickinson99d652e2009-12-30 12:12:23 +0000938#undef DOUBLE_IS_ODD_INTEGER
939
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000940static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000941float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000944}
945
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000947float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000948{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000950}
951
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000952static int
Fred Drakefd99de62000-07-09 05:02:18 +0000953float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000954{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000955 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000956}
957
Guido van Rossum234f9421993-06-17 12:35:49 +0000958static int
Fred Drakefd99de62000-07-09 05:02:18 +0000959float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000960{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 if (PyInt_Check(*pw)) {
962 long x = PyInt_AsLong(*pw);
963 *pw = PyFloat_FromDouble((double)x);
964 Py_INCREF(*pv);
965 return 0;
966 }
967 else if (PyLong_Check(*pw)) {
968 double x = PyLong_AsDouble(*pw);
969 if (x == -1.0 && PyErr_Occurred())
970 return -1;
971 *pw = PyFloat_FromDouble(x);
972 Py_INCREF(*pv);
973 return 0;
974 }
975 else if (PyFloat_Check(*pw)) {
976 Py_INCREF(*pv);
977 Py_INCREF(*pw);
978 return 0;
979 }
980 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +0000981}
982
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000984float_is_integer(PyObject *v)
985{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000986 double x = PyFloat_AsDouble(v);
987 PyObject *o;
988
989 if (x == -1.0 && PyErr_Occurred())
990 return NULL;
991 if (!Py_IS_FINITE(x))
992 Py_RETURN_FALSE;
993 errno = 0;
994 PyFPE_START_PROTECT("is_integer", return NULL)
995 o = (floor(x) == x) ? Py_True : Py_False;
996 PyFPE_END_PROTECT(x)
997 if (errno != 0) {
998 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
999 PyExc_ValueError);
1000 return NULL;
1001 }
1002 Py_INCREF(o);
1003 return o;
Christian Heimes6f341092008-04-18 23:13:07 +00001004}
1005
1006#if 0
1007static PyObject *
1008float_is_inf(PyObject *v)
1009{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 double x = PyFloat_AsDouble(v);
1011 if (x == -1.0 && PyErr_Occurred())
1012 return NULL;
1013 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001014}
1015
1016static PyObject *
1017float_is_nan(PyObject *v)
1018{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001019 double x = PyFloat_AsDouble(v);
1020 if (x == -1.0 && PyErr_Occurred())
1021 return NULL;
1022 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001023}
1024
1025static PyObject *
1026float_is_finite(PyObject *v)
1027{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001028 double x = PyFloat_AsDouble(v);
1029 if (x == -1.0 && PyErr_Occurred())
1030 return NULL;
1031 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes6f341092008-04-18 23:13:07 +00001032}
1033#endif
1034
1035static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001036float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 double x = PyFloat_AsDouble(v);
1039 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001040
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001041 (void)modf(x, &wholepart);
1042 /* Try to get out cheap if this fits in a Python int. The attempt
1043 * to cast to long must be protected, as C doesn't define what
1044 * happens if the double is too big to fit in a long. Some rare
1045 * systems raise an exception then (RISCOS was mentioned as one,
1046 * and someone using a non-default option on Sun also bumped into
Mark Dickinson874d59e2011-03-26 12:18:00 +00001047 * that). Note that checking for <= LONG_MAX is unsafe: if a long
1048 * has more bits of precision than a double, casting LONG_MAX to
1049 * double may yield an approximation, and if that's rounded up,
1050 * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
1051 * expression wholepart<=LONG_MAX, despite that wholepart is
1052 * actually greater than LONG_MAX. However, assuming a two's complement
1053 * machine with no trap representation, LONG_MIN will be a power of 2 (and
1054 * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
1055 * the comparisons with (double)LONG_MIN below should be safe.
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001056 */
Mark Dickinson874d59e2011-03-26 12:18:00 +00001057 if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 const long aslong = (long)wholepart;
1059 return PyInt_FromLong(aslong);
1060 }
1061 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001062}
1063
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001064static PyObject *
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001065float_long(PyObject *v)
1066{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001067 double x = PyFloat_AsDouble(v);
1068 return PyLong_FromDouble(x);
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001069}
1070
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001071/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
1072 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
1073 ndigits <= 323). Returns a Python float, or sets a Python error and
1074 returns NULL on failure (OverflowError and memory errors are possible). */
1075
1076#ifndef PY_NO_SHORT_FLOAT_REPR
1077/* version of _Py_double_round that uses the correctly-rounded string<->double
1078 conversions from Python/dtoa.c */
1079
1080/* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
1081 a double. Since we're using the code in Python/dtoa.c, it should be safe
1082 to assume that C doubles are IEEE 754 binary64 format. To be on the safe
1083 side, we check this. */
1084#if DBL_MANT_DIG == 53
1085#define FIVE_POW_LIMIT 22
1086#else
1087#error "C doubles do not appear to be IEEE 754 binary64 format"
1088#endif
1089
1090PyObject *
1091_Py_double_round(double x, int ndigits) {
1092
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001093 double rounded, m;
1094 Py_ssize_t buflen, mybuflen=100;
1095 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
1096 int decpt, sign, val, halfway_case;
1097 PyObject *result = NULL;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001098 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001099
Mark Dickinson115bc792012-11-17 20:18:52 +00001100 /* Easy path for the common case ndigits == 0. */
1101 if (ndigits == 0) {
1102 rounded = round(x);
1103 if (fabs(rounded - x) == 0.5)
1104 /* halfway between two integers; use round-away-from-zero */
1105 rounded = x + (x > 0.0 ? 0.5 : -0.5);
1106 return PyFloat_FromDouble(rounded);
1107 }
1108
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001109 /* The basic idea is very simple: convert and round the double to a
1110 decimal string using _Py_dg_dtoa, then convert that decimal string
1111 back to a double with _Py_dg_strtod. There's one minor difficulty:
1112 Python 2.x expects round to do round-half-away-from-zero, while
1113 _Py_dg_dtoa does round-half-to-even. So we need some way to detect
1114 and correct the halfway cases.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001116 Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
1117 some odd integer k. Or in other words, a rational number x is
1118 exactly halfway between two multiples of 10**-ndigits if its
1119 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
1120 -ndigits. For ndigits >= 0 the latter condition is automatically
1121 satisfied for a binary float x, since any such float has
1122 nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
1123 integral multiple of 5**-ndigits; we can check this using fmod.
1124 For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
1125 to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
1126 23 takes at least 54 bits of precision to represent exactly.
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001127
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001128 Correction: a simple strategy for dealing with halfway cases is to
1129 (for the halfway cases only) call _Py_dg_dtoa with an argument of
1130 ndigits+1 instead of ndigits (thus doing an exact conversion to
1131 decimal), round the resulting string manually, and then convert
1132 back using _Py_dg_strtod.
1133 */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001134
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001135 /* nans, infinities and zeros should have already been dealt
1136 with by the caller (in this case, builtin_round) */
1137 assert(Py_IS_FINITE(x) && x != 0.0);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001138
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001139 /* find 2-valuation val of x */
1140 m = frexp(x, &val);
1141 while (m != floor(m)) {
1142 m *= 2.0;
1143 val--;
1144 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001145
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001146 /* determine whether this is a halfway case */
1147 if (val == -ndigits-1) {
1148 if (ndigits >= 0)
1149 halfway_case = 1;
1150 else if (ndigits >= -FIVE_POW_LIMIT) {
1151 double five_pow = 1.0;
1152 int i;
1153 for (i=0; i < -ndigits; i++)
1154 five_pow *= 5.0;
1155 halfway_case = fmod(x, five_pow) == 0.0;
1156 }
1157 else
1158 halfway_case = 0;
1159 }
1160 else
1161 halfway_case = 0;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001162
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001163 /* round to a decimal string; use an extra place for halfway case */
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001164 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001165 buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001166 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001167 if (buf == NULL) {
1168 PyErr_NoMemory();
1169 return NULL;
1170 }
1171 buflen = buf_end - buf;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001172
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001173 /* in halfway case, do the round-half-away-from-zero manually */
1174 if (halfway_case) {
1175 int i, carry;
1176 /* sanity check: _Py_dg_dtoa should not have stripped
1177 any zeros from the result: there should be exactly
1178 ndigits+1 places following the decimal point, and
1179 the last digit in the buffer should be a '5'.*/
1180 assert(buflen - decpt == ndigits+1);
1181 assert(buf[buflen-1] == '5');
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001182
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001183 /* increment and shift right at the same time. */
1184 decpt += 1;
1185 carry = 1;
1186 for (i=buflen-1; i-- > 0;) {
1187 carry += buf[i] - '0';
1188 buf[i+1] = carry % 10 + '0';
1189 carry /= 10;
1190 }
1191 buf[0] = carry + '0';
1192 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001193
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001194 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
1195 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
1196 if (buflen + 8 > mybuflen) {
1197 mybuflen = buflen+8;
1198 mybuf = (char *)PyMem_Malloc(mybuflen);
1199 if (mybuf == NULL) {
1200 PyErr_NoMemory();
1201 goto exit;
1202 }
1203 }
1204 /* copy buf to mybuf, adding exponent, sign and leading 0 */
1205 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
1206 buf, decpt - (int)buflen);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001207
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001208 /* and convert the resulting string back to a double */
1209 errno = 0;
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001210 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001211 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson1abe6cd2012-01-27 21:16:01 +00001212 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 if (errno == ERANGE && fabs(rounded) >= 1.)
1214 PyErr_SetString(PyExc_OverflowError,
1215 "rounded value too large to represent");
1216 else
1217 result = PyFloat_FromDouble(rounded);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001218
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001219 /* done computing value; now clean up */
1220 if (mybuf != shortbuf)
1221 PyMem_Free(mybuf);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001222 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 _Py_dg_freedtoa(buf);
1224 return result;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001225}
1226
1227#undef FIVE_POW_LIMIT
1228
1229#else /* PY_NO_SHORT_FLOAT_REPR */
1230
1231/* fallback version, to be used when correctly rounded binary<->decimal
1232 conversions aren't available */
1233
1234PyObject *
1235_Py_double_round(double x, int ndigits) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001236 double pow1, pow2, y, z;
1237 if (ndigits >= 0) {
1238 if (ndigits > 22) {
1239 /* pow1 and pow2 are each safe from overflow, but
1240 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
1241 pow1 = pow(10.0, (double)(ndigits-22));
1242 pow2 = 1e22;
1243 }
1244 else {
1245 pow1 = pow(10.0, (double)ndigits);
1246 pow2 = 1.0;
1247 }
1248 y = (x*pow1)*pow2;
1249 /* if y overflows, then rounded value is exactly x */
1250 if (!Py_IS_FINITE(y))
1251 return PyFloat_FromDouble(x);
1252 }
1253 else {
1254 pow1 = pow(10.0, (double)-ndigits);
1255 pow2 = 1.0; /* unused; silences a gcc compiler warning */
1256 y = x / pow1;
1257 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001258
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001259 z = round(y);
1260 if (fabs(y-z) == 0.5)
1261 /* halfway between two integers; use round-away-from-zero */
1262 z = y + copysign(0.5, y);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001263
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001264 if (ndigits >= 0)
1265 z = (z / pow2) / pow1;
1266 else
1267 z *= pow1;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001268
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001269 /* if computation resulted in overflow, raise OverflowError */
1270 if (!Py_IS_FINITE(z)) {
1271 PyErr_SetString(PyExc_OverflowError,
1272 "overflow occurred during round");
1273 return NULL;
1274 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001275
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001276 return PyFloat_FromDouble(z);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00001277}
1278
1279#endif /* PY_NO_SHORT_FLOAT_REPR */
1280
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +00001281static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001282float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 if (PyFloat_CheckExact(v))
1285 Py_INCREF(v);
1286 else
1287 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1288 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001289}
1290
Mark Dickinson7103aa42008-07-15 19:08:33 +00001291/* turn ASCII hex characters into integer values and vice versa */
1292
1293static char
1294char_from_hex(int x)
1295{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001296 assert(0 <= x && x < 16);
1297 return "0123456789abcdef"[x];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001298}
1299
1300static int
1301hex_from_char(char c) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001302 int x;
1303 switch(c) {
1304 case '0':
1305 x = 0;
1306 break;
1307 case '1':
1308 x = 1;
1309 break;
1310 case '2':
1311 x = 2;
1312 break;
1313 case '3':
1314 x = 3;
1315 break;
1316 case '4':
1317 x = 4;
1318 break;
1319 case '5':
1320 x = 5;
1321 break;
1322 case '6':
1323 x = 6;
1324 break;
1325 case '7':
1326 x = 7;
1327 break;
1328 case '8':
1329 x = 8;
1330 break;
1331 case '9':
1332 x = 9;
1333 break;
1334 case 'a':
1335 case 'A':
1336 x = 10;
1337 break;
1338 case 'b':
1339 case 'B':
1340 x = 11;
1341 break;
1342 case 'c':
1343 case 'C':
1344 x = 12;
1345 break;
1346 case 'd':
1347 case 'D':
1348 x = 13;
1349 break;
1350 case 'e':
1351 case 'E':
1352 x = 14;
1353 break;
1354 case 'f':
1355 case 'F':
1356 x = 15;
1357 break;
1358 default:
1359 x = -1;
1360 break;
1361 }
1362 return x;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001363}
1364
1365/* convert a float to a hexadecimal string */
1366
1367/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1368 of the form 4k+1. */
1369#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1370
1371static PyObject *
1372float_hex(PyObject *v)
1373{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374 double x, m;
1375 int e, shift, i, si, esign;
1376 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1377 trailing NUL byte. */
1378 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson7103aa42008-07-15 19:08:33 +00001379
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001380 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001381
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001382 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
1383 return float_str((PyFloatObject *)v);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 if (x == 0.0) {
Benjamin Petersoncf76d1f2010-07-02 19:41:39 +00001386 if (copysign(1.0, x) == -1.0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001387 return PyString_FromString("-0x0.0p+0");
1388 else
1389 return PyString_FromString("0x0.0p+0");
1390 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 m = frexp(fabs(x), &e);
1393 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1394 m = ldexp(m, shift);
1395 e -= shift;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001396
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001397 si = 0;
1398 s[si] = char_from_hex((int)m);
1399 si++;
1400 m -= (int)m;
1401 s[si] = '.';
1402 si++;
1403 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1404 m *= 16.0;
1405 s[si] = char_from_hex((int)m);
1406 si++;
1407 m -= (int)m;
1408 }
1409 s[si] = '\0';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001410
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001411 if (e < 0) {
1412 esign = (int)'-';
1413 e = -e;
1414 }
1415 else
1416 esign = (int)'+';
Mark Dickinson7103aa42008-07-15 19:08:33 +00001417
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 if (x < 0.0)
1419 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
1420 else
1421 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001422}
1423
1424PyDoc_STRVAR(float_hex_doc,
1425"float.hex() -> string\n\
1426\n\
1427Return a hexadecimal representation of a floating-point number.\n\
1428>>> (-0.1).hex()\n\
1429'-0x1.999999999999ap-4'\n\
1430>>> 3.14159.hex()\n\
1431'0x1.921f9f01b866ep+1'");
1432
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001433/* Case-insensitive locale-independent string match used for nan and inf
1434 detection. t should be lower-case and null-terminated. Return a nonzero
1435 result if the first strlen(t) characters of s match t and 0 otherwise. */
1436
1437static int
1438case_insensitive_match(const char *s, const char *t)
1439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 while(*t && Py_TOLOWER(*s) == *t) {
1441 s++;
1442 t++;
1443 }
1444 return *t ? 0 : 1;
Mark Dickinsonb1d45852009-05-11 15:33:08 +00001445}
1446
Mark Dickinson7103aa42008-07-15 19:08:33 +00001447/* Convert a hexadecimal string to a float. */
1448
1449static PyObject *
1450float_fromhex(PyObject *cls, PyObject *arg)
1451{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001452 PyObject *result_as_float, *result;
1453 double x;
1454 long exp, top_exp, lsb, key_digit;
1455 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1456 int half_eps, digit, round_up, sign=1;
1457 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001458
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001459 /*
1460 * For the sake of simplicity and correctness, we impose an artificial
1461 * limit on ndigits, the total number of hex digits in the coefficient
1462 * The limit is chosen to ensure that, writing exp for the exponent,
1463 *
1464 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1465 * guaranteed to overflow (provided it's nonzero)
1466 *
1467 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1468 * guaranteed to underflow to 0.
1469 *
1470 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1471 * overflow in the calculation of exp and top_exp below.
1472 *
1473 * More specifically, ndigits is assumed to satisfy the following
1474 * inequalities:
1475 *
1476 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1477 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1478 *
1479 * If either of these inequalities is not satisfied, a ValueError is
1480 * raised. Otherwise, write x for the value of the hex string, and
1481 * assume x is nonzero. Then
1482 *
1483 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1484 *
1485 * Now if exp > LONG_MAX/2 then:
1486 *
1487 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1488 * = DBL_MAX_EXP
1489 *
1490 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1491 * double, so overflows. If exp < LONG_MIN/2, then
1492 *
1493 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1494 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1495 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1496 *
1497 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1498 * when converted to a C double.
1499 *
1500 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1501 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1502 */
Mark Dickinson7103aa42008-07-15 19:08:33 +00001503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001504 if (PyString_AsStringAndSize(arg, &s, &length))
1505 return NULL;
1506 s_end = s + length;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001508 /********************
1509 * Parse the string *
1510 ********************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001511
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001512 /* leading whitespace and optional sign */
1513 while (Py_ISSPACE(*s))
1514 s++;
1515 if (*s == '-') {
1516 s++;
1517 sign = -1;
1518 }
1519 else if (*s == '+')
1520 s++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001522 /* infinities and nans */
1523 if (*s == 'i' || *s == 'I') {
1524 if (!case_insensitive_match(s+1, "nf"))
1525 goto parse_error;
1526 s += 3;
1527 x = Py_HUGE_VAL;
1528 if (case_insensitive_match(s, "inity"))
1529 s += 5;
1530 goto finished;
1531 }
1532 if (*s == 'n' || *s == 'N') {
1533 if (!case_insensitive_match(s+1, "an"))
1534 goto parse_error;
1535 s += 3;
1536 x = Py_NAN;
1537 goto finished;
1538 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001539
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001540 /* [0x] */
1541 s_store = s;
1542 if (*s == '0') {
1543 s++;
1544 if (*s == 'x' || *s == 'X')
1545 s++;
1546 else
1547 s = s_store;
1548 }
Mark Dickinson7103aa42008-07-15 19:08:33 +00001549
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 /* coefficient: <integer> [. <fraction>] */
1551 coeff_start = s;
1552 while (hex_from_char(*s) >= 0)
1553 s++;
1554 s_store = s;
1555 if (*s == '.') {
1556 s++;
1557 while (hex_from_char(*s) >= 0)
1558 s++;
1559 coeff_end = s-1;
1560 }
1561 else
1562 coeff_end = s;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001564 /* ndigits = total # of hex digits; fdigits = # after point */
1565 ndigits = coeff_end - coeff_start;
1566 fdigits = coeff_end - s_store;
1567 if (ndigits == 0)
1568 goto parse_error;
1569 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1570 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1571 goto insane_length_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001572
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001573 /* [p <exponent>] */
1574 if (*s == 'p' || *s == 'P') {
1575 s++;
1576 exp_start = s;
1577 if (*s == '-' || *s == '+')
1578 s++;
1579 if (!('0' <= *s && *s <= '9'))
1580 goto parse_error;
1581 s++;
1582 while ('0' <= *s && *s <= '9')
1583 s++;
1584 exp = strtol(exp_start, NULL, 10);
1585 }
1586 else
1587 exp = 0;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001588
Mark Dickinson7103aa42008-07-15 19:08:33 +00001589/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001590#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1591 coeff_end-(j) : \
1592 coeff_end-1-(j)))
Mark Dickinson7103aa42008-07-15 19:08:33 +00001593
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001594 /*******************************************
1595 * Compute rounded value of the hex string *
1596 *******************************************/
Mark Dickinson7103aa42008-07-15 19:08:33 +00001597
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001598 /* Discard leading zeros, and catch extreme overflow and underflow */
1599 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1600 ndigits--;
1601 if (ndigits == 0 || exp < LONG_MIN/2) {
1602 x = 0.0;
1603 goto finished;
1604 }
1605 if (exp > LONG_MAX/2)
1606 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001607
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001608 /* Adjust exponent for fractional part. */
1609 exp = exp - 4*((long)fdigits);
Mark Dickinson7103aa42008-07-15 19:08:33 +00001610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001611 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1612 top_exp = exp + 4*((long)ndigits - 1);
1613 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1614 top_exp++;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001616 /* catch almost all nonextreme cases of overflow and underflow here */
1617 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1618 x = 0.0;
1619 goto finished;
1620 }
1621 if (top_exp > DBL_MAX_EXP)
1622 goto overflow_error;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001623
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001624 /* lsb = exponent of least significant bit of the *rounded* value.
1625 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1626 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001627
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001628 x = 0.0;
1629 if (exp >= lsb) {
1630 /* no rounding required */
1631 for (i = ndigits-1; i >= 0; i--)
1632 x = 16.0*x + HEX_DIGIT(i);
1633 x = ldexp(x, (int)(exp));
1634 goto finished;
1635 }
1636 /* rounding required. key_digit is the index of the hex digit
1637 containing the first bit to be rounded away. */
1638 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1639 key_digit = (lsb - exp - 1) / 4;
1640 for (i = ndigits-1; i > key_digit; i--)
1641 x = 16.0*x + HEX_DIGIT(i);
1642 digit = HEX_DIGIT(key_digit);
1643 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001644
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001645 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1646 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1647 if ((digit & half_eps) != 0) {
1648 round_up = 0;
1649 if ((digit & (3*half_eps-1)) != 0 ||
1650 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1651 round_up = 1;
1652 else
1653 for (i = key_digit-1; i >= 0; i--)
1654 if (HEX_DIGIT(i) != 0) {
1655 round_up = 1;
1656 break;
1657 }
1658 if (round_up == 1) {
1659 x += 2*half_eps;
1660 if (top_exp == DBL_MAX_EXP &&
1661 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1662 /* overflow corner case: pre-rounded value <
1663 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1664 goto overflow_error;
1665 }
1666 }
1667 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson7103aa42008-07-15 19:08:33 +00001668
1669 finished:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001670 /* optional trailing whitespace leading to the end of the string */
1671 while (Py_ISSPACE(*s))
1672 s++;
1673 if (s != s_end)
1674 goto parse_error;
1675 result_as_float = Py_BuildValue("(d)", sign * x);
1676 if (result_as_float == NULL)
1677 return NULL;
1678 result = PyObject_CallObject(cls, result_as_float);
1679 Py_DECREF(result_as_float);
1680 return result;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001681
1682 overflow_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001683 PyErr_SetString(PyExc_OverflowError,
1684 "hexadecimal value too large to represent as a float");
1685 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001686
1687 parse_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 PyErr_SetString(PyExc_ValueError,
1689 "invalid hexadecimal floating-point string");
1690 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001691
1692 insane_length_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001693 PyErr_SetString(PyExc_ValueError,
1694 "hexadecimal string too long to convert");
1695 return NULL;
Mark Dickinson7103aa42008-07-15 19:08:33 +00001696}
1697
1698PyDoc_STRVAR(float_fromhex_doc,
1699"float.fromhex(string) -> float\n\
1700\n\
1701Create a floating-point number from a hexadecimal string.\n\
1702>>> float.fromhex('0x1.ffffp10')\n\
17032047.984375\n\
1704>>> float.fromhex('-0x1p-1074')\n\
1705-4.9406564584124654e-324");
1706
1707
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001708static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001709float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001710{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001711 double self;
1712 double float_part;
1713 int exponent;
1714 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001716 PyObject *prev;
1717 PyObject *py_exponent = NULL;
1718 PyObject *numerator = NULL;
1719 PyObject *denominator = NULL;
1720 PyObject *result_pair = NULL;
1721 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001722
1723#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 prev = obj; \
1725 obj = call; \
1726 Py_DECREF(prev); \
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001727
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001728 CONVERT_TO_DOUBLE(v, self);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001730 if (Py_IS_INFINITY(self)) {
1731 PyErr_SetString(PyExc_OverflowError,
1732 "Cannot pass infinity to float.as_integer_ratio.");
1733 return NULL;
1734 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001735#ifdef Py_NAN
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 if (Py_IS_NAN(self)) {
1737 PyErr_SetString(PyExc_ValueError,
1738 "Cannot pass NaN to float.as_integer_ratio.");
1739 return NULL;
1740 }
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001741#endif
1742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001743 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1744 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1745 PyFPE_END_PROTECT(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001747 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1748 float_part *= 2.0;
1749 exponent--;
1750 }
1751 /* self == float_part * 2**exponent exactly and float_part is integral.
1752 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1753 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001755 numerator = PyLong_FromDouble(float_part);
1756 if (numerator == NULL) goto error;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001758 /* fold in 2**exponent */
1759 denominator = PyLong_FromLong(1);
1760 py_exponent = PyLong_FromLong(labs((long)exponent));
1761 if (py_exponent == NULL) goto error;
1762 INPLACE_UPDATE(py_exponent,
1763 long_methods->nb_lshift(denominator, py_exponent));
1764 if (py_exponent == NULL) goto error;
1765 if (exponent > 0) {
1766 INPLACE_UPDATE(numerator,
1767 long_methods->nb_multiply(numerator, py_exponent));
1768 if (numerator == NULL) goto error;
1769 }
1770 else {
1771 Py_DECREF(denominator);
1772 denominator = py_exponent;
1773 py_exponent = NULL;
1774 }
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001775
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001776 /* Returns ints instead of longs where possible */
1777 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1778 if (numerator == NULL) goto error;
1779 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1780 if (denominator == NULL) goto error;
1781
1782 result_pair = PyTuple_Pack(2, numerator, denominator);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001783
1784#undef INPLACE_UPDATE
1785error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001786 Py_XDECREF(py_exponent);
1787 Py_XDECREF(denominator);
1788 Py_XDECREF(numerator);
1789 return result_pair;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001790}
1791
1792PyDoc_STRVAR(float_as_integer_ratio_doc,
1793"float.as_integer_ratio() -> (int, int)\n"
1794"\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001795"Return a pair of integers, whose ratio is exactly equal to the original\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001796"float and with a positive denominator.\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001797"Raise OverflowError on infinities and a ValueError on NaNs.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001798"\n"
1799">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001800"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001801">>> (0.0).as_integer_ratio()\n"
1802"(0, 1)\n"
1803">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001804"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001805
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001806
Jeremy Hylton938ace62002-07-17 16:30:39 +00001807static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001808float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1809
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810static PyObject *
1811float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1812{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 PyObject *x = Py_False; /* Integer zero */
1814 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 if (type != &PyFloat_Type)
1817 return float_subtype_new(type, args, kwds); /* Wimp out */
1818 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1819 return NULL;
1820 /* If it's a string, but not a string subclass, use
1821 PyFloat_FromString. */
1822 if (PyString_CheckExact(x))
1823 return PyFloat_FromString(x, NULL);
1824 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825}
1826
Guido van Rossumbef14172001-08-29 15:47:46 +00001827/* Wimpy, slow approach to tp_new calls for subtypes of float:
1828 first create a regular float from whatever arguments we got,
1829 then allocate a subtype instance and initialize its ob_fval
1830 from the regular float. The regular float is then thrown away.
1831*/
1832static PyObject *
1833float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1834{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001835 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001836
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001837 assert(PyType_IsSubtype(type, &PyFloat_Type));
1838 tmp = float_new(&PyFloat_Type, args, kwds);
1839 if (tmp == NULL)
1840 return NULL;
Serhiy Storchaka8d30ad72015-11-25 15:55:54 +02001841 assert(PyFloat_Check(tmp));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001842 newobj = type->tp_alloc(type, 0);
1843 if (newobj == NULL) {
1844 Py_DECREF(tmp);
1845 return NULL;
1846 }
1847 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1848 Py_DECREF(tmp);
1849 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001850}
1851
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001852static PyObject *
1853float_getnewargs(PyFloatObject *v)
1854{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001855 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001856}
1857
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001858/* this is for the benefit of the pack/unpack routines below */
1859
1860typedef enum {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001862} float_format_type;
1863
1864static float_format_type double_format, float_format;
1865static float_format_type detected_double_format, detected_float_format;
1866
1867static PyObject *
1868float_getformat(PyTypeObject *v, PyObject* arg)
1869{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001870 char* s;
1871 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001872
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001873 if (!PyString_Check(arg)) {
1874 PyErr_Format(PyExc_TypeError,
1875 "__getformat__() argument must be string, not %.500s",
1876 Py_TYPE(arg)->tp_name);
1877 return NULL;
1878 }
1879 s = PyString_AS_STRING(arg);
1880 if (strcmp(s, "double") == 0) {
1881 r = double_format;
1882 }
1883 else if (strcmp(s, "float") == 0) {
1884 r = float_format;
1885 }
1886 else {
1887 PyErr_SetString(PyExc_ValueError,
1888 "__getformat__() argument 1 must be "
1889 "'double' or 'float'");
1890 return NULL;
1891 }
1892
1893 switch (r) {
1894 case unknown_format:
1895 return PyString_FromString("unknown");
1896 case ieee_little_endian_format:
1897 return PyString_FromString("IEEE, little-endian");
1898 case ieee_big_endian_format:
1899 return PyString_FromString("IEEE, big-endian");
1900 default:
1901 Py_FatalError("insane float_format or double_format");
1902 return NULL;
1903 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001904}
1905
1906PyDoc_STRVAR(float_getformat_doc,
1907"float.__getformat__(typestr) -> string\n"
1908"\n"
1909"You probably don't want to use this function. It exists mainly to be\n"
1910"used in Python's test suite.\n"
1911"\n"
1912"typestr must be 'double' or 'float'. This function returns whichever of\n"
1913"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1914"format of floating point numbers used by the C type named by typestr.");
1915
1916static PyObject *
1917float_setformat(PyTypeObject *v, PyObject* args)
1918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 char* typestr;
1920 char* format;
1921 float_format_type f;
1922 float_format_type detected;
1923 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1926 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001927
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 if (strcmp(typestr, "double") == 0) {
1929 p = &double_format;
1930 detected = detected_double_format;
1931 }
1932 else if (strcmp(typestr, "float") == 0) {
1933 p = &float_format;
1934 detected = detected_float_format;
1935 }
1936 else {
1937 PyErr_SetString(PyExc_ValueError,
1938 "__setformat__() argument 1 must "
1939 "be 'double' or 'float'");
1940 return NULL;
1941 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001942
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 if (strcmp(format, "unknown") == 0) {
1944 f = unknown_format;
1945 }
1946 else if (strcmp(format, "IEEE, little-endian") == 0) {
1947 f = ieee_little_endian_format;
1948 }
1949 else if (strcmp(format, "IEEE, big-endian") == 0) {
1950 f = ieee_big_endian_format;
1951 }
1952 else {
1953 PyErr_SetString(PyExc_ValueError,
1954 "__setformat__() argument 2 must be "
1955 "'unknown', 'IEEE, little-endian' or "
1956 "'IEEE, big-endian'");
1957 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001958
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001959 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001960
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001961 if (f != unknown_format && f != detected) {
1962 PyErr_Format(PyExc_ValueError,
1963 "can only set %s format to 'unknown' or the "
1964 "detected platform value", typestr);
1965 return NULL;
1966 }
1967
1968 *p = f;
1969 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001970}
1971
1972PyDoc_STRVAR(float_setformat_doc,
1973"float.__setformat__(typestr, fmt) -> None\n"
1974"\n"
1975"You probably don't want to use this function. It exists mainly to be\n"
1976"used in Python's test suite.\n"
1977"\n"
1978"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1979"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1980"one of the latter two if it appears to match the underlying C reality.\n"
1981"\n"
Ezio Melotti38386142013-10-06 00:44:32 +03001982"Override the automatic determination of C-level floating point type.\n"
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001983"This affects how floats are converted to and from binary strings.");
1984
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001985static PyObject *
1986float_getzero(PyObject *v, void *closure)
1987{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001988 return PyFloat_FromDouble(0.0);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001989}
1990
Eric Smitha9f7d622008-02-17 19:46:49 +00001991static PyObject *
1992float__format__(PyObject *self, PyObject *args)
1993{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001994 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001995
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001996 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1997 return NULL;
1998 if (PyBytes_Check(format_spec))
1999 return _PyFloat_FormatAdvanced(self,
2000 PyBytes_AS_STRING(format_spec),
2001 PyBytes_GET_SIZE(format_spec));
2002 if (PyUnicode_Check(format_spec)) {
2003 /* Convert format_spec to a str */
2004 PyObject *result;
2005 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00002006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002007 if (str_spec == NULL)
2008 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002009
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002010 result = _PyFloat_FormatAdvanced(self,
2011 PyBytes_AS_STRING(str_spec),
2012 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00002013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 Py_DECREF(str_spec);
2015 return result;
2016 }
2017 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
2018 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002019}
2020
2021PyDoc_STRVAR(float__format__doc,
2022"float.__format__(format_spec) -> string\n"
2023"\n"
2024"Formats the float according to format_spec.");
2025
2026
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002027static PyMethodDef float_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002028 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002029 "Return self, the complex conjugate of any float."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002030 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002031 "Return the Integral closest to x between 0 and x."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002032 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
2033 float_as_integer_ratio_doc},
2034 {"fromhex", (PyCFunction)float_fromhex,
2035 METH_O|METH_CLASS, float_fromhex_doc},
2036 {"hex", (PyCFunction)float_hex,
2037 METH_NOARGS, float_hex_doc},
2038 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002039 "Return True if the float is an integer."},
Christian Heimes6f341092008-04-18 23:13:07 +00002040#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002041 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002042 "Return True if the float is positive or negative infinite."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002043 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002044 "Return True if the float is finite, neither infinite nor NaN."},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002045 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
Ezio Melotti38386142013-10-06 00:44:32 +03002046 "Return True if the float is not a number (NaN)."},
Christian Heimes6f341092008-04-18 23:13:07 +00002047#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002048 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
2049 {"__getformat__", (PyCFunction)float_getformat,
2050 METH_O|METH_CLASS, float_getformat_doc},
2051 {"__setformat__", (PyCFunction)float_setformat,
2052 METH_VARARGS|METH_CLASS, float_setformat_doc},
2053 {"__format__", (PyCFunction)float__format__,
2054 METH_VARARGS, float__format__doc},
2055 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00002056};
2057
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002058static PyGetSetDef float_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002059 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002060 (getter)float_float, (setter)NULL,
2061 "the real part of a complex number",
2062 NULL},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002063 {"imag",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002064 (getter)float_getzero, (setter)NULL,
2065 "the imaginary part of a complex number",
2066 NULL},
2067 {NULL} /* Sentinel */
2068};
2069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002070PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002071"float(x) -> floating point number\n\
2072\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002073Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074
2075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002076static PyNumberMethods float_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002077 float_add, /*nb_add*/
2078 float_sub, /*nb_subtract*/
2079 float_mul, /*nb_multiply*/
2080 float_classic_div, /*nb_divide*/
2081 float_rem, /*nb_remainder*/
2082 float_divmod, /*nb_divmod*/
2083 float_pow, /*nb_power*/
2084 (unaryfunc)float_neg, /*nb_negative*/
2085 (unaryfunc)float_float, /*nb_positive*/
2086 (unaryfunc)float_abs, /*nb_absolute*/
2087 (inquiry)float_nonzero, /*nb_nonzero*/
2088 0, /*nb_invert*/
2089 0, /*nb_lshift*/
2090 0, /*nb_rshift*/
2091 0, /*nb_and*/
2092 0, /*nb_xor*/
2093 0, /*nb_or*/
2094 float_coerce, /*nb_coerce*/
2095 float_trunc, /*nb_int*/
2096 float_long, /*nb_long*/
2097 float_float, /*nb_float*/
2098 0, /* nb_oct */
2099 0, /* nb_hex */
2100 0, /* nb_inplace_add */
2101 0, /* nb_inplace_subtract */
2102 0, /* nb_inplace_multiply */
2103 0, /* nb_inplace_divide */
2104 0, /* nb_inplace_remainder */
2105 0, /* nb_inplace_power */
2106 0, /* nb_inplace_lshift */
2107 0, /* nb_inplace_rshift */
2108 0, /* nb_inplace_and */
2109 0, /* nb_inplace_xor */
2110 0, /* nb_inplace_or */
2111 float_floor_div, /* nb_floor_divide */
2112 float_div, /* nb_true_divide */
2113 0, /* nb_inplace_floor_divide */
2114 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002115};
2116
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117PyTypeObject PyFloat_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2119 "float",
2120 sizeof(PyFloatObject),
2121 0,
2122 (destructor)float_dealloc, /* tp_dealloc */
2123 (printfunc)float_print, /* tp_print */
2124 0, /* tp_getattr */
2125 0, /* tp_setattr */
2126 0, /* tp_compare */
2127 (reprfunc)float_repr, /* tp_repr */
2128 &float_as_number, /* tp_as_number */
2129 0, /* tp_as_sequence */
2130 0, /* tp_as_mapping */
2131 (hashfunc)float_hash, /* tp_hash */
2132 0, /* tp_call */
2133 (reprfunc)float_str, /* tp_str */
2134 PyObject_GenericGetAttr, /* tp_getattro */
2135 0, /* tp_setattro */
2136 0, /* tp_as_buffer */
2137 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2138 Py_TPFLAGS_BASETYPE, /* tp_flags */
2139 float_doc, /* tp_doc */
2140 0, /* tp_traverse */
2141 0, /* tp_clear */
2142 float_richcompare, /* tp_richcompare */
2143 0, /* tp_weaklistoffset */
2144 0, /* tp_iter */
2145 0, /* tp_iternext */
2146 float_methods, /* tp_methods */
2147 0, /* tp_members */
2148 float_getset, /* tp_getset */
2149 0, /* tp_base */
2150 0, /* tp_dict */
2151 0, /* tp_descr_get */
2152 0, /* tp_descr_set */
2153 0, /* tp_dictoffset */
2154 0, /* tp_init */
2155 0, /* tp_alloc */
2156 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002157};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002158
2159void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002160_PyFloat_Init(void)
2161{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002162 /* We attempt to determine if this machine is using IEEE
2163 floating point formats by peering at the bits of some
2164 carefully chosen values. If it looks like we are on an
2165 IEEE platform, the float packing/unpacking routines can
2166 just copy bits, if not they resort to arithmetic & shifts
2167 and masks. The shifts & masks approach works on all finite
2168 values, but what happens to infinities, NaNs and signed
2169 zeroes on packing is an accident, and attempting to unpack
2170 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002171
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002172 Note that if we're on some whacked-out platform which uses
2173 IEEE formats but isn't strictly little-endian or big-
2174 endian, we will fall back to the portable shifts & masks
2175 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002176
2177#if SIZEOF_DOUBLE == 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002178 {
2179 double x = 9006104071832581.0;
2180 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
2181 detected_double_format = ieee_big_endian_format;
2182 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
2183 detected_double_format = ieee_little_endian_format;
2184 else
2185 detected_double_format = unknown_format;
2186 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002187#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002188 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002189#endif
2190
2191#if SIZEOF_FLOAT == 4
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002192 {
2193 float y = 16711938.0;
2194 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
2195 detected_float_format = ieee_big_endian_format;
2196 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
2197 detected_float_format = ieee_little_endian_format;
2198 else
2199 detected_float_format = unknown_format;
2200 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002202 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002203#endif
2204
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002205 double_format = detected_double_format;
2206 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00002207
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002208 /* Init float info */
2209 if (FloatInfoType.tp_name == 0)
2210 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002211}
2212
Gregory P. Smith2fe77062008-07-06 03:35:58 +00002213int
2214PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002215{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002216 PyFloatObject *p;
2217 PyFloatBlock *list, *next;
2218 int i;
2219 int u; /* remaining unfreed ints per block */
2220 int freelist_size = 0;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00002221
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002222 list = block_list;
2223 block_list = NULL;
2224 free_list = NULL;
2225 while (list != NULL) {
2226 u = 0;
2227 for (i = 0, p = &list->objects[0];
2228 i < N_FLOATOBJECTS;
2229 i++, p++) {
2230 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
2231 u++;
2232 }
2233 next = list->next;
2234 if (u) {
2235 list->next = block_list;
2236 block_list = list;
2237 for (i = 0, p = &list->objects[0];
2238 i < N_FLOATOBJECTS;
2239 i++, p++) {
2240 if (!PyFloat_CheckExact(p) ||
2241 Py_REFCNT(p) == 0) {
2242 Py_TYPE(p) = (struct _typeobject *)
2243 free_list;
2244 free_list = p;
2245 }
2246 }
2247 }
2248 else {
2249 PyMem_FREE(list);
2250 }
2251 freelist_size += u;
2252 list = next;
2253 }
2254 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00002255}
2256
2257void
2258PyFloat_Fini(void)
2259{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002260 PyFloatObject *p;
2261 PyFloatBlock *list;
2262 int i;
2263 int u; /* total unfreed floats per block */
Christian Heimes422051a2008-02-04 18:00:12 +00002264
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002265 u = PyFloat_ClearFreeList();
Christian Heimes422051a2008-02-04 18:00:12 +00002266
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002267 if (!Py_VerboseFlag)
2268 return;
2269 fprintf(stderr, "# cleanup floats");
2270 if (!u) {
2271 fprintf(stderr, "\n");
2272 }
2273 else {
2274 fprintf(stderr,
2275 ": %d unfreed float%s\n",
2276 u, u == 1 ? "" : "s");
2277 }
2278 if (Py_VerboseFlag > 1) {
2279 list = block_list;
2280 while (list != NULL) {
2281 for (i = 0, p = &list->objects[0];
2282 i < N_FLOATOBJECTS;
2283 i++, p++) {
2284 if (PyFloat_CheckExact(p) &&
2285 Py_REFCNT(p) != 0) {
2286 char *buf = PyOS_double_to_string(
2287 PyFloat_AS_DOUBLE(p), 'r',
2288 0, 0, NULL);
2289 if (buf) {
2290 /* XXX(twouters) cast
2291 refcount to long
2292 until %zd is
2293 universally
2294 available
2295 */
2296 fprintf(stderr,
2297 "# <float at %p, refcnt=%ld, val=%s>\n",
2298 p, (long)Py_REFCNT(p), buf);
2299 PyMem_Free(buf);
2300 }
2301 }
2302 }
2303 list = list->next;
2304 }
2305 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00002306}
Tim Peters9905b942003-03-20 20:53:32 +00002307
2308/*----------------------------------------------------------------------------
2309 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00002310 */
2311int
2312_PyFloat_Pack4(double x, unsigned char *p, int le)
2313{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002314 if (float_format == unknown_format) {
2315 unsigned char sign;
2316 int e;
2317 double f;
2318 unsigned int fbits;
2319 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002320
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 if (le) {
2322 p += 3;
2323 incr = -1;
2324 }
Tim Peters9905b942003-03-20 20:53:32 +00002325
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002326 if (x < 0) {
2327 sign = 1;
2328 x = -x;
2329 }
2330 else
2331 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002332
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002333 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002334
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002335 /* Normalize f to be in the range [1.0, 2.0) */
2336 if (0.5 <= f && f < 1.0) {
2337 f *= 2.0;
2338 e--;
2339 }
2340 else if (f == 0.0)
2341 e = 0;
2342 else {
2343 PyErr_SetString(PyExc_SystemError,
2344 "frexp() result out of range");
2345 return -1;
2346 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002347
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002348 if (e >= 128)
2349 goto Overflow;
2350 else if (e < -126) {
2351 /* Gradual underflow */
2352 f = ldexp(f, 126 + e);
2353 e = 0;
2354 }
2355 else if (!(e == 0 && f == 0.0)) {
2356 e += 127;
2357 f -= 1.0; /* Get rid of leading 1 */
2358 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002359
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002360 f *= 8388608.0; /* 2**23 */
2361 fbits = (unsigned int)(f + 0.5); /* Round */
2362 assert(fbits <= 8388608);
2363 if (fbits >> 23) {
2364 /* The carry propagated out of a string of 23 1 bits. */
2365 fbits = 0;
2366 ++e;
2367 if (e >= 255)
2368 goto Overflow;
2369 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 /* First byte */
2372 *p = (sign << 7) | (e >> 1);
2373 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002374
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002375 /* Second byte */
2376 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2377 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002379 /* Third byte */
2380 *p = (fbits >> 8) & 0xFF;
2381 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002383 /* Fourth byte */
2384 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002385
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002386 /* Done */
2387 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002388
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002389 }
2390 else {
2391 float y = (float)x;
2392 const char *s = (char*)&y;
2393 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002394
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002395 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2396 goto Overflow;
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002398 if ((float_format == ieee_little_endian_format && !le)
2399 || (float_format == ieee_big_endian_format && le)) {
2400 p += 3;
2401 incr = -1;
2402 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002403
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002404 for (i = 0; i < 4; i++) {
2405 *p = *s++;
2406 p += incr;
2407 }
2408 return 0;
2409 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00002410 Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002411 PyErr_SetString(PyExc_OverflowError,
2412 "float too large to pack with f format");
2413 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002414}
2415
2416int
2417_PyFloat_Pack8(double x, unsigned char *p, int le)
2418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002419 if (double_format == unknown_format) {
2420 unsigned char sign;
2421 int e;
2422 double f;
2423 unsigned int fhi, flo;
2424 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002425
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002426 if (le) {
2427 p += 7;
2428 incr = -1;
2429 }
Tim Peters9905b942003-03-20 20:53:32 +00002430
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002431 if (x < 0) {
2432 sign = 1;
2433 x = -x;
2434 }
2435 else
2436 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002437
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002438 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002439
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002440 /* Normalize f to be in the range [1.0, 2.0) */
2441 if (0.5 <= f && f < 1.0) {
2442 f *= 2.0;
2443 e--;
2444 }
2445 else if (f == 0.0)
2446 e = 0;
2447 else {
2448 PyErr_SetString(PyExc_SystemError,
2449 "frexp() result out of range");
2450 return -1;
2451 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002452
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002453 if (e >= 1024)
2454 goto Overflow;
2455 else if (e < -1022) {
2456 /* Gradual underflow */
2457 f = ldexp(f, 1022 + e);
2458 e = 0;
2459 }
2460 else if (!(e == 0 && f == 0.0)) {
2461 e += 1023;
2462 f -= 1.0; /* Get rid of leading 1 */
2463 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002464
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002465 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2466 f *= 268435456.0; /* 2**28 */
2467 fhi = (unsigned int)f; /* Truncate */
2468 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002469
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002470 f -= (double)fhi;
2471 f *= 16777216.0; /* 2**24 */
2472 flo = (unsigned int)(f + 0.5); /* Round */
2473 assert(flo <= 16777216);
2474 if (flo >> 24) {
2475 /* The carry propagated out of a string of 24 1 bits. */
2476 flo = 0;
2477 ++fhi;
2478 if (fhi >> 28) {
2479 /* And it also progagated out of the next 28 bits. */
2480 fhi = 0;
2481 ++e;
2482 if (e >= 2047)
2483 goto Overflow;
2484 }
2485 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002487 /* First byte */
2488 *p = (sign << 7) | (e >> 4);
2489 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002490
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002491 /* Second byte */
2492 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2493 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002494
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002495 /* Third byte */
2496 *p = (fhi >> 16) & 0xFF;
2497 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002499 /* Fourth byte */
2500 *p = (fhi >> 8) & 0xFF;
2501 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002503 /* Fifth byte */
2504 *p = fhi & 0xFF;
2505 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 /* Sixth byte */
2508 *p = (flo >> 16) & 0xFF;
2509 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002511 /* Seventh byte */
2512 *p = (flo >> 8) & 0xFF;
2513 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002514
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002515 /* Eighth byte */
2516 *p = flo & 0xFF;
2517 /* p += incr; Unneeded (for now) */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002518
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002519 /* Done */
2520 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 Overflow:
2523 PyErr_SetString(PyExc_OverflowError,
2524 "float too large to pack with d format");
2525 return -1;
2526 }
2527 else {
2528 const char *s = (char*)&x;
2529 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002530
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002531 if ((double_format == ieee_little_endian_format && !le)
2532 || (double_format == ieee_big_endian_format && le)) {
2533 p += 7;
2534 incr = -1;
2535 }
2536
2537 for (i = 0; i < 8; i++) {
2538 *p = *s++;
2539 p += incr;
2540 }
2541 return 0;
2542 }
Tim Peters9905b942003-03-20 20:53:32 +00002543}
2544
2545double
2546_PyFloat_Unpack4(const unsigned char *p, int le)
2547{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002548 if (float_format == unknown_format) {
2549 unsigned char sign;
2550 int e;
2551 unsigned int f;
2552 double x;
2553 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002555 if (le) {
2556 p += 3;
2557 incr = -1;
2558 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002560 /* First byte */
2561 sign = (*p >> 7) & 1;
2562 e = (*p & 0x7F) << 1;
2563 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002564
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002565 /* Second byte */
2566 e |= (*p >> 7) & 1;
2567 f = (*p & 0x7F) << 16;
2568 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002569
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002570 if (e == 255) {
2571 PyErr_SetString(
2572 PyExc_ValueError,
2573 "can't unpack IEEE 754 special value "
2574 "on non-IEEE platform");
2575 return -1;
2576 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002577
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002578 /* Third byte */
2579 f |= *p << 8;
2580 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002581
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002582 /* Fourth byte */
2583 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002584
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002585 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002586
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002587 /* XXX This sadly ignores Inf/NaN issues */
2588 if (e == 0)
2589 e = -126;
2590 else {
2591 x += 1.0;
2592 e -= 127;
2593 }
2594 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002595
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002596 if (sign)
2597 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002598
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002599 return x;
2600 }
2601 else {
2602 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002603
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002604 if ((float_format == ieee_little_endian_format && !le)
2605 || (float_format == ieee_big_endian_format && le)) {
2606 char buf[4];
2607 char *d = &buf[3];
2608 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002609
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 for (i = 0; i < 4; i++) {
2611 *d-- = *p++;
2612 }
2613 memcpy(&x, buf, 4);
2614 }
2615 else {
2616 memcpy(&x, p, 4);
2617 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002618
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002619 return x;
2620 }
Tim Peters9905b942003-03-20 20:53:32 +00002621}
2622
2623double
2624_PyFloat_Unpack8(const unsigned char *p, int le)
2625{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 if (double_format == unknown_format) {
2627 unsigned char sign;
2628 int e;
2629 unsigned int fhi, flo;
2630 double x;
2631 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002632
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002633 if (le) {
2634 p += 7;
2635 incr = -1;
2636 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002637
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002638 /* First byte */
2639 sign = (*p >> 7) & 1;
2640 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002641
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002642 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002643
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002644 /* Second byte */
2645 e |= (*p >> 4) & 0xF;
2646 fhi = (*p & 0xF) << 24;
2647 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002648
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002649 if (e == 2047) {
2650 PyErr_SetString(
2651 PyExc_ValueError,
2652 "can't unpack IEEE 754 special value "
2653 "on non-IEEE platform");
2654 return -1.0;
2655 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 /* Third byte */
2658 fhi |= *p << 16;
2659 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002661 /* Fourth byte */
2662 fhi |= *p << 8;
2663 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 /* Fifth byte */
2666 fhi |= *p;
2667 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002668
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002669 /* Sixth byte */
2670 flo = *p << 16;
2671 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002672
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002673 /* Seventh byte */
2674 flo |= *p << 8;
2675 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002676
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002677 /* Eighth byte */
2678 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002679
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002680 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2681 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002682
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002683 if (e == 0)
2684 e = -1022;
2685 else {
2686 x += 1.0;
2687 e -= 1023;
2688 }
2689 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 if (sign)
2692 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002693
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002694 return x;
2695 }
2696 else {
2697 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002698
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002699 if ((double_format == ieee_little_endian_format && !le)
2700 || (double_format == ieee_big_endian_format && le)) {
2701 char buf[8];
2702 char *d = &buf[7];
2703 int i;
2704
2705 for (i = 0; i < 8; i++) {
2706 *d-- = *p++;
2707 }
2708 memcpy(&x, buf, 8);
2709 }
2710 else {
2711 memcpy(&x, p, 8);
2712 }
2713
2714 return x;
2715 }
Tim Peters9905b942003-03-20 20:53:32 +00002716}