blob: a42be71c23ba493913689a4fe05291aaf721eae8 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000010#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Mark Dickinson65fe25e2008-07-16 11:30:51 +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
Guido van Rossum6923e131990-11-02 17:50:43 +000017
Mark Dickinsond19052c2010-06-27 18:19:09 +000018/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000019 free_list is a singly-linked list of available PyFloatObjects, linked
20 via abuse of their ob_type members.
21*/
22
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000023#ifndef PyFloat_MAXFREELIST
24#define PyFloat_MAXFREELIST 100
25#endif
26static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000027static PyFloatObject *free_list = NULL;
28
Christian Heimes93852662007-12-01 12:22:32 +000029double
30PyFloat_GetMax(void)
31{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000033}
34
35double
36PyFloat_GetMin(void)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000039}
40
Christian Heimesd32ed6f2008-01-14 18:49:24 +000041static PyTypeObject FloatInfoType;
42
43PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000044"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000045\n\
46A structseq holding information about the float type. It contains low level\n\
47information about the precision and internal representation. Please study\n\
48your system's :file:`float.h` for more information.");
49
50static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 {"max", "DBL_MAX -- maximum representable finite float"},
52 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
53 "is representable"},
54 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
55 "is representable"},
56 {"min", "DBL_MIN -- Minimum positive normalizer float"},
57 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
58 "is a normalized float"},
59 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
60 "a normalized"},
61 {"dig", "DBL_DIG -- digits"},
62 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
63 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
64 "representable float"},
65 {"radix", "FLT_RADIX -- radix of exponent"},
66 {"rounds", "FLT_ROUNDS -- addition rounds"},
67 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000068};
69
70static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 "sys.float_info", /* name */
72 floatinfo__doc__, /* doc */
73 floatinfo_fields, /* fields */
74 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000075};
76
Christian Heimes93852662007-12-01 12:22:32 +000077PyObject *
78PyFloat_GetInfo(void)
79{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 PyObject* floatinfo;
81 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 floatinfo = PyStructSequence_New(&FloatInfoType);
84 if (floatinfo == NULL) {
85 return NULL;
86 }
Christian Heimes93852662007-12-01 12:22:32 +000087
Christian Heimesd32ed6f2008-01-14 18:49:24 +000088#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000090#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 SetDblFlag(DBL_MAX);
94 SetIntFlag(DBL_MAX_EXP);
95 SetIntFlag(DBL_MAX_10_EXP);
96 SetDblFlag(DBL_MIN);
97 SetIntFlag(DBL_MIN_EXP);
98 SetIntFlag(DBL_MIN_10_EXP);
99 SetIntFlag(DBL_DIG);
100 SetIntFlag(DBL_MANT_DIG);
101 SetDblFlag(DBL_EPSILON);
102 SetIntFlag(FLT_RADIX);
103 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000104#undef SetIntFlag
105#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106
107 if (PyErr_Occurred()) {
108 Py_CLEAR(floatinfo);
109 return NULL;
110 }
111 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000112}
113
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000117 register PyFloatObject *op = free_list;
118 if (op != NULL) {
119 free_list = (PyFloatObject *) Py_TYPE(op);
120 numfree--;
121 } else {
122 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
123 if (!op)
124 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
126 /* Inline PyObject_New */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyObject_INIT(op, &PyFloat_Type);
128 op->ob_fval = fval;
129 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000132PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000133PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 const char *s, *last, *end;
136 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000137 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 Py_ssize_t len;
139 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200142 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000144 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200145 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000146 if (s == NULL) {
147 Py_DECREF(s_buffer);
148 return NULL;
149 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 }
151 else if (PyObject_AsCharBuffer(v, &s, &len)) {
152 PyErr_SetString(PyExc_TypeError,
153 "float() argument must be a string or a number");
154 return NULL;
155 }
156 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000157 /* strip space */
158 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000160 while (s < last - 1 && Py_ISSPACE(last[-1]))
161 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* We don't care about overflow or underflow. If the platform
163 * supports them, infinities and signed zeroes (on underflow) are
164 * fine. */
165 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000166 if (end != last) {
167 PyErr_Format(PyExc_ValueError,
168 "could not convert string to float: "
169 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 result = NULL;
171 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000172 else if (x == -1.0 && PyErr_Occurred())
173 result = NULL;
174 else
175 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000176
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000177 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179}
180
Guido van Rossum234f9421993-06-17 12:35:49 +0000181static void
Fred Drakefd99de62000-07-09 05:02:18 +0000182float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000185 if (numfree >= PyFloat_MAXFREELIST) {
186 PyObject_FREE(op);
187 return;
188 }
189 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 Py_TYPE(op) = (struct _typeobject *)free_list;
191 free_list = op;
192 }
193 else
194 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000195}
196
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197double
Fred Drakefd99de62000-07-09 05:02:18 +0000198PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyNumberMethods *nb;
201 PyFloatObject *fo;
202 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 if (op && PyFloat_Check(op))
205 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (op == NULL) {
208 PyErr_BadArgument();
209 return -1;
210 }
Tim Petersd2364e82001-11-01 20:09:42 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
213 PyErr_SetString(PyExc_TypeError, "a float is required");
214 return -1;
215 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 fo = (PyFloatObject*) (*nb->nb_float) (op);
218 if (fo == NULL)
219 return -1;
220 if (!PyFloat_Check(fo)) {
221 PyErr_SetString(PyExc_TypeError,
222 "nb_float should return float object");
223 return -1;
224 }
Tim Petersd2364e82001-11-01 20:09:42 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 val = PyFloat_AS_DOUBLE(fo);
227 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000230}
231
Neil Schemenauer32117e52001-01-04 01:44:34 +0000232/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000233 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000234 set to NULL, and the function invoking this macro returns NULL. If
235 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
236 stored in obj, and returned from the function invoking this macro.
237*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238#define CONVERT_TO_DOUBLE(obj, dbl) \
239 if (PyFloat_Check(obj)) \
240 dbl = PyFloat_AS_DOUBLE(obj); \
241 else if (convert_to_double(&(obj), &(dbl)) < 0) \
242 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000243
Eric Smith0923d1d2009-04-16 20:16:10 +0000244/* Methods */
245
Neil Schemenauer32117e52001-01-04 01:44:34 +0000246static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000247convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (PyLong_Check(obj)) {
252 *dbl = PyLong_AsDouble(obj);
253 if (*dbl == -1.0 && PyErr_Occurred()) {
254 *v = NULL;
255 return -1;
256 }
257 }
258 else {
259 Py_INCREF(Py_NotImplemented);
260 *v = Py_NotImplemented;
261 return -1;
262 }
263 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000264}
265
Eric Smith0923d1d2009-04-16 20:16:10 +0000266static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000267float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000268{
269 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200270 char *buf;
271
272 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
273 'r', 0,
274 Py_DTSF_ADD_DOT_0,
275 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000276 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000277 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200278 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000279 PyMem_Free(buf);
280 return result;
281}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000282
Tim Peters307fa782004-09-23 08:06:40 +0000283/* Comparison is pretty much a nightmare. When comparing float to float,
284 * we do it as straightforwardly (and long-windedly) as conceivable, so
285 * that, e.g., Python x == y delivers the same result as the platform
286 * C x == y when x and/or y is a NaN.
287 * When mixing float with an integer type, there's no good *uniform* approach.
288 * Converting the double to an integer obviously doesn't work, since we
289 * may lose info from fractional bits. Converting the integer to a double
290 * also has two failure modes: (1) a long int may trigger overflow (too
291 * large to fit in the dynamic range of a C double); (2) even a C long may have
292 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
293 * 63 bits of precision, but a C double probably has only 53), and then
294 * we can falsely claim equality when low-order integer bits are lost by
295 * coercion to double. So this part is painful too.
296 */
297
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000298static PyObject*
299float_richcompare(PyObject *v, PyObject *w, int op)
300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 double i, j;
302 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 assert(PyFloat_Check(v));
305 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 /* Switch on the type of w. Set i and j to doubles to be compared,
308 * and op to the richcomp to use.
309 */
310 if (PyFloat_Check(w))
311 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 else if (!Py_IS_FINITE(i)) {
314 if (PyLong_Check(w))
315 /* If i is an infinity, its magnitude exceeds any
316 * finite integer, so it doesn't matter which int we
317 * compare i with. If i is a NaN, similarly.
318 */
319 j = 0.0;
320 else
321 goto Unimplemented;
322 }
Tim Peters307fa782004-09-23 08:06:40 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 else if (PyLong_Check(w)) {
325 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
326 int wsign = _PyLong_Sign(w);
327 size_t nbits;
328 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (vsign != wsign) {
331 /* Magnitudes are irrelevant -- the signs alone
332 * determine the outcome.
333 */
334 i = (double)vsign;
335 j = (double)wsign;
336 goto Compare;
337 }
338 /* The signs are the same. */
339 /* Convert w to a double if it fits. In particular, 0 fits. */
340 nbits = _PyLong_NumBits(w);
341 if (nbits == (size_t)-1 && PyErr_Occurred()) {
342 /* This long is so large that size_t isn't big enough
343 * to hold the # of bits. Replace with little doubles
344 * that give the same outcome -- w is so large that
345 * its magnitude must exceed the magnitude of any
346 * finite float.
347 */
348 PyErr_Clear();
349 i = (double)vsign;
350 assert(wsign != 0);
351 j = wsign * 2.0;
352 goto Compare;
353 }
354 if (nbits <= 48) {
355 j = PyLong_AsDouble(w);
356 /* It's impossible that <= 48 bits overflowed. */
357 assert(j != -1.0 || ! PyErr_Occurred());
358 goto Compare;
359 }
360 assert(wsign != 0); /* else nbits was 0 */
361 assert(vsign != 0); /* if vsign were 0, then since wsign is
362 * not 0, we would have taken the
363 * vsign != wsign branch at the start */
364 /* We want to work with non-negative numbers. */
365 if (vsign < 0) {
366 /* "Multiply both sides" by -1; this also swaps the
367 * comparator.
368 */
369 i = -i;
370 op = _Py_SwappedOp[op];
371 }
372 assert(i > 0.0);
373 (void) frexp(i, &exponent);
374 /* exponent is the # of bits in v before the radix point;
375 * we know that nbits (the # of bits in w) > 48 at this point
376 */
377 if (exponent < 0 || (size_t)exponent < nbits) {
378 i = 1.0;
379 j = 2.0;
380 goto Compare;
381 }
382 if ((size_t)exponent > nbits) {
383 i = 2.0;
384 j = 1.0;
385 goto Compare;
386 }
387 /* v and w have the same number of bits before the radix
388 * point. Construct two longs that have the same comparison
389 * outcome.
390 */
391 {
392 double fracpart;
393 double intpart;
394 PyObject *result = NULL;
395 PyObject *one = NULL;
396 PyObject *vv = NULL;
397 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (wsign < 0) {
400 ww = PyNumber_Negative(w);
401 if (ww == NULL)
402 goto Error;
403 }
404 else
405 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 fracpart = modf(i, &intpart);
408 vv = PyLong_FromDouble(intpart);
409 if (vv == NULL)
410 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (fracpart != 0.0) {
413 /* Shift left, and or a 1 bit into vv
414 * to represent the lost fraction.
415 */
416 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 one = PyLong_FromLong(1);
419 if (one == NULL)
420 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 temp = PyNumber_Lshift(ww, one);
423 if (temp == NULL)
424 goto Error;
425 Py_DECREF(ww);
426 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 temp = PyNumber_Lshift(vv, one);
429 if (temp == NULL)
430 goto Error;
431 Py_DECREF(vv);
432 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 temp = PyNumber_Or(vv, one);
435 if (temp == NULL)
436 goto Error;
437 Py_DECREF(vv);
438 vv = temp;
439 }
Tim Peters307fa782004-09-23 08:06:40 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 r = PyObject_RichCompareBool(vv, ww, op);
442 if (r < 0)
443 goto Error;
444 result = PyBool_FromLong(r);
445 Error:
446 Py_XDECREF(vv);
447 Py_XDECREF(ww);
448 Py_XDECREF(one);
449 return result;
450 }
451 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 else /* w isn't float, int, or long */
454 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000455
456 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 PyFPE_START_PROTECT("richcompare", return NULL)
458 switch (op) {
459 case Py_EQ:
460 r = i == j;
461 break;
462 case Py_NE:
463 r = i != j;
464 break;
465 case Py_LE:
466 r = i <= j;
467 break;
468 case Py_GE:
469 r = i >= j;
470 break;
471 case Py_LT:
472 r = i < j;
473 break;
474 case Py_GT:
475 r = i > j;
476 break;
477 }
478 PyFPE_END_PROTECT(r)
479 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000480
481 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500482 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000483}
484
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000485static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000486float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000489}
490
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000492float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 double a,b;
495 CONVERT_TO_DOUBLE(v, a);
496 CONVERT_TO_DOUBLE(w, b);
497 PyFPE_START_PROTECT("add", return 0)
498 a = a + b;
499 PyFPE_END_PROTECT(a)
500 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501}
502
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000503static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000504float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 double a,b;
507 CONVERT_TO_DOUBLE(v, a);
508 CONVERT_TO_DOUBLE(w, b);
509 PyFPE_START_PROTECT("subtract", return 0)
510 a = a - b;
511 PyFPE_END_PROTECT(a)
512 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513}
514
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000515static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000516float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 double a,b;
519 CONVERT_TO_DOUBLE(v, a);
520 CONVERT_TO_DOUBLE(w, b);
521 PyFPE_START_PROTECT("multiply", return 0)
522 a = a * b;
523 PyFPE_END_PROTECT(a)
524 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525}
526
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000527static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000528float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 double a,b;
531 CONVERT_TO_DOUBLE(v, a);
532 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (b == 0.0) {
534 PyErr_SetString(PyExc_ZeroDivisionError,
535 "float division by zero");
536 return NULL;
537 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyFPE_START_PROTECT("divide", return 0)
539 a = a / b;
540 PyFPE_END_PROTECT(a)
541 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542}
543
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000545float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 double vx, wx;
548 double mod;
549 CONVERT_TO_DOUBLE(v, vx);
550 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (wx == 0.0) {
552 PyErr_SetString(PyExc_ZeroDivisionError,
553 "float modulo");
554 return NULL;
555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyFPE_START_PROTECT("modulo", return 0)
557 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000558 if (mod) {
559 /* ensure the remainder has the same sign as the denominator */
560 if ((wx < 0) != (mod < 0)) {
561 mod += wx;
562 }
563 }
564 else {
565 /* the remainder is zero, and in the presence of signed zeroes
566 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000567 it has the same sign as the denominator. */
568 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 }
570 PyFPE_END_PROTECT(mod)
571 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000572}
573
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000575float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 double vx, wx;
578 double div, mod, floordiv;
579 CONVERT_TO_DOUBLE(v, vx);
580 CONVERT_TO_DOUBLE(w, wx);
581 if (wx == 0.0) {
582 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
583 return NULL;
584 }
585 PyFPE_START_PROTECT("divmod", return 0)
586 mod = fmod(vx, wx);
587 /* fmod is typically exact, so vx-mod is *mathematically* an
588 exact multiple of wx. But this is fp arithmetic, and fp
589 vx - mod is an approximation; the result is that div may
590 not be an exact integral value after the division, although
591 it will always be very close to one.
592 */
593 div = (vx - mod) / wx;
594 if (mod) {
595 /* ensure the remainder has the same sign as the denominator */
596 if ((wx < 0) != (mod < 0)) {
597 mod += wx;
598 div -= 1.0;
599 }
600 }
601 else {
602 /* the remainder is zero, and in the presence of signed zeroes
603 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000604 it has the same sign as the denominator. */
605 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
607 /* snap quotient to nearest integral value */
608 if (div) {
609 floordiv = floor(div);
610 if (div - floordiv > 0.5)
611 floordiv += 1.0;
612 }
613 else {
614 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000615 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
617 PyFPE_END_PROTECT(floordiv)
618 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000619}
620
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000622float_floor_div(PyObject *v, PyObject *w)
623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 t = float_divmod(v, w);
627 if (t == NULL || t == Py_NotImplemented)
628 return t;
629 assert(PyTuple_CheckExact(t));
630 r = PyTuple_GET_ITEM(t, 0);
631 Py_INCREF(r);
632 Py_DECREF(t);
633 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000634}
635
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000636/* determine whether x is an odd integer or not; assumes that
637 x is not an infinity or nan. */
638#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
639
Tim Peters63a35712001-12-11 19:57:24 +0000640static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000641float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 double iv, iw, ix;
644 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if ((PyObject *)z != Py_None) {
647 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
648 "allowed unless all arguments are integers");
649 return NULL;
650 }
Tim Peters32f453e2001-09-03 08:35:41 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 CONVERT_TO_DOUBLE(v, iv);
653 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* Sort out special cases here instead of relying on pow() */
656 if (iw == 0) { /* v**0 is 1, even 0**0 */
657 return PyFloat_FromDouble(1.0);
658 }
659 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
660 return PyFloat_FromDouble(iv);
661 }
662 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
663 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
664 }
665 if (Py_IS_INFINITY(iw)) {
666 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
667 * abs(v) > 1 (including case where v infinite)
668 *
669 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
670 * abs(v) > 1 (including case where v infinite)
671 */
672 iv = fabs(iv);
673 if (iv == 1.0)
674 return PyFloat_FromDouble(1.0);
675 else if ((iw > 0.0) == (iv > 1.0))
676 return PyFloat_FromDouble(fabs(iw)); /* return inf */
677 else
678 return PyFloat_FromDouble(0.0);
679 }
680 if (Py_IS_INFINITY(iv)) {
681 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
682 * both cases, we need to add the appropriate sign if w is
683 * an odd integer.
684 */
685 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
686 if (iw > 0.0)
687 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
688 else
689 return PyFloat_FromDouble(iw_is_odd ?
690 copysign(0.0, iv) : 0.0);
691 }
692 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
693 (already dealt with above), and an error
694 if w is negative. */
695 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
696 if (iw < 0.0) {
697 PyErr_SetString(PyExc_ZeroDivisionError,
698 "0.0 cannot be raised to a "
699 "negative power");
700 return NULL;
701 }
702 /* use correct sign if iw is odd */
703 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
704 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (iv < 0.0) {
707 /* Whether this is an error is a mess, and bumps into libm
708 * bugs so we have to figure it out ourselves.
709 */
710 if (iw != floor(iw)) {
711 /* Negative numbers raised to fractional powers
712 * become complex.
713 */
714 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
715 }
716 /* iw is an exact integer, albeit perhaps a very large
717 * one. Replace iv by its absolute value and remember
718 * to negate the pow result if iw is odd.
719 */
720 iv = -iv;
721 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
722 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
725 /* (-1) ** large_integer also ends up here. Here's an
726 * extract from the comments for the previous
727 * implementation explaining why this special case is
728 * necessary:
729 *
730 * -1 raised to an exact integer should never be exceptional.
731 * Alas, some libms (chiefly glibc as of early 2003) return
732 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
733 * happen to be representable in a *C* integer. That's a
734 * bug.
735 */
736 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
737 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 /* Now iv and iw are finite, iw is nonzero, and iv is
740 * positive and not equal to 1.0. We finally allow
741 * the platform pow to step in and do the rest.
742 */
743 errno = 0;
744 PyFPE_START_PROTECT("pow", return NULL)
745 ix = pow(iv, iw);
746 PyFPE_END_PROTECT(ix)
747 Py_ADJUST_ERANGE1(ix);
748 if (negate_result)
749 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (errno != 0) {
752 /* We don't expect any errno value other than ERANGE, but
753 * the range of libm bugs appears unbounded.
754 */
755 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
756 PyExc_ValueError);
757 return NULL;
758 }
759 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760}
761
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000762#undef DOUBLE_IS_ODD_INTEGER
763
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000765float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768}
769
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000771float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774}
775
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000776static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000777float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000780}
781
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000782static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000783float_is_integer(PyObject *v)
784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 double x = PyFloat_AsDouble(v);
786 PyObject *o;
787
788 if (x == -1.0 && PyErr_Occurred())
789 return NULL;
790 if (!Py_IS_FINITE(x))
791 Py_RETURN_FALSE;
792 errno = 0;
793 PyFPE_START_PROTECT("is_integer", return NULL)
794 o = (floor(x) == x) ? Py_True : Py_False;
795 PyFPE_END_PROTECT(x)
796 if (errno != 0) {
797 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
798 PyExc_ValueError);
799 return NULL;
800 }
801 Py_INCREF(o);
802 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000803}
804
805#if 0
806static PyObject *
807float_is_inf(PyObject *v)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 double x = PyFloat_AsDouble(v);
810 if (x == -1.0 && PyErr_Occurred())
811 return NULL;
812 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000813}
814
815static PyObject *
816float_is_nan(PyObject *v)
817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 double x = PyFloat_AsDouble(v);
819 if (x == -1.0 && PyErr_Occurred())
820 return NULL;
821 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000822}
823
824static PyObject *
825float_is_finite(PyObject *v)
826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 double x = PyFloat_AsDouble(v);
828 if (x == -1.0 && PyErr_Occurred())
829 return NULL;
830 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000831}
832#endif
833
834static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000835float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 double x = PyFloat_AsDouble(v);
838 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 (void)modf(x, &wholepart);
841 /* Try to get out cheap if this fits in a Python int. The attempt
842 * to cast to long must be protected, as C doesn't define what
843 * happens if the double is too big to fit in a long. Some rare
844 * systems raise an exception then (RISCOS was mentioned as one,
845 * and someone using a non-default option on Sun also bumped into
846 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
847 * still be vulnerable: if a long has more bits of precision than
848 * a double, casting MIN/MAX to double may yield an approximation,
849 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
850 * yield true from the C expression wholepart<=LONG_MAX, despite
851 * that wholepart is actually greater than LONG_MAX.
852 */
853 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
854 const long aslong = (long)wholepart;
855 return PyLong_FromLong(aslong);
856 }
857 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000858}
859
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000860/* double_round: rounds a finite double to the closest multiple of
861 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
862 ndigits <= 323). Returns a Python float, or sets a Python error and
863 returns NULL on failure (OverflowError and memory errors are possible). */
864
865#ifndef PY_NO_SHORT_FLOAT_REPR
866/* version of double_round that uses the correctly-rounded string<->double
867 conversions from Python/dtoa.c */
868
869static PyObject *
870double_round(double x, int ndigits) {
871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 double rounded;
873 Py_ssize_t buflen, mybuflen=100;
874 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
875 int decpt, sign;
876 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000877 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000880 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000882 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (buf == NULL) {
884 PyErr_NoMemory();
885 return NULL;
886 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
889 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
890 buflen = buf_end - buf;
891 if (buflen + 8 > mybuflen) {
892 mybuflen = buflen+8;
893 mybuf = (char *)PyMem_Malloc(mybuflen);
894 if (mybuf == NULL) {
895 PyErr_NoMemory();
896 goto exit;
897 }
898 }
899 /* copy buf to mybuf, adding exponent, sign and leading 0 */
900 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
901 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* and convert the resulting string back to a double */
904 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000905 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000907 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (errno == ERANGE && fabs(rounded) >= 1.)
909 PyErr_SetString(PyExc_OverflowError,
910 "rounded value too large to represent");
911 else
912 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* done computing value; now clean up */
915 if (mybuf != shortbuf)
916 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000917 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 _Py_dg_freedtoa(buf);
919 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000920}
921
922#else /* PY_NO_SHORT_FLOAT_REPR */
923
924/* fallback version, to be used when correctly rounded binary<->decimal
925 conversions aren't available */
926
927static PyObject *
928double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 double pow1, pow2, y, z;
930 if (ndigits >= 0) {
931 if (ndigits > 22) {
932 /* pow1 and pow2 are each safe from overflow, but
933 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
934 pow1 = pow(10.0, (double)(ndigits-22));
935 pow2 = 1e22;
936 }
937 else {
938 pow1 = pow(10.0, (double)ndigits);
939 pow2 = 1.0;
940 }
941 y = (x*pow1)*pow2;
942 /* if y overflows, then rounded value is exactly x */
943 if (!Py_IS_FINITE(y))
944 return PyFloat_FromDouble(x);
945 }
946 else {
947 pow1 = pow(10.0, (double)-ndigits);
948 pow2 = 1.0; /* unused; silences a gcc compiler warning */
949 y = x / pow1;
950 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 z = round(y);
953 if (fabs(y-z) == 0.5)
954 /* halfway between two integers; use round-half-even */
955 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (ndigits >= 0)
958 z = (z / pow2) / pow1;
959 else
960 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* if computation resulted in overflow, raise OverflowError */
963 if (!Py_IS_FINITE(z)) {
964 PyErr_SetString(PyExc_OverflowError,
965 "overflow occurred during round");
966 return NULL;
967 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000970}
971
972#endif /* PY_NO_SHORT_FLOAT_REPR */
973
974/* round a Python float v to the closest multiple of 10**-ndigits */
975
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000976static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000977float_round(PyObject *v, PyObject *args)
978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 double x, rounded;
980 PyObject *o_ndigits = NULL;
981 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 x = PyFloat_AsDouble(v);
984 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
985 return NULL;
986 if (o_ndigits == NULL) {
987 /* single-argument round: round to nearest integer */
988 rounded = round(x);
989 if (fabs(x-rounded) == 0.5)
990 /* halfway case: round to even */
991 rounded = 2.0*round(x/2.0);
992 return PyLong_FromDouble(rounded);
993 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* interpret second argument as a Py_ssize_t; clips on overflow */
996 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
997 if (ndigits == -1 && PyErr_Occurred())
998 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* nans and infinities round to themselves */
1001 if (!Py_IS_FINITE(x))
1002 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1005 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1006 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001007#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1008#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (ndigits > NDIGITS_MAX)
1010 /* return x */
1011 return PyFloat_FromDouble(x);
1012 else if (ndigits < NDIGITS_MIN)
1013 /* return 0.0, but with sign of x */
1014 return PyFloat_FromDouble(0.0*x);
1015 else
1016 /* finite x, and ndigits is not unreasonably large */
1017 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001018#undef NDIGITS_MAX
1019#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001020}
1021
1022static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001023float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (PyFloat_CheckExact(v))
1026 Py_INCREF(v);
1027 else
1028 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1029 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001030}
1031
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001032/* turn ASCII hex characters into integer values and vice versa */
1033
1034static char
1035char_from_hex(int x)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001038 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001039}
1040
1041static int
1042hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 int x;
1044 switch(c) {
1045 case '0':
1046 x = 0;
1047 break;
1048 case '1':
1049 x = 1;
1050 break;
1051 case '2':
1052 x = 2;
1053 break;
1054 case '3':
1055 x = 3;
1056 break;
1057 case '4':
1058 x = 4;
1059 break;
1060 case '5':
1061 x = 5;
1062 break;
1063 case '6':
1064 x = 6;
1065 break;
1066 case '7':
1067 x = 7;
1068 break;
1069 case '8':
1070 x = 8;
1071 break;
1072 case '9':
1073 x = 9;
1074 break;
1075 case 'a':
1076 case 'A':
1077 x = 10;
1078 break;
1079 case 'b':
1080 case 'B':
1081 x = 11;
1082 break;
1083 case 'c':
1084 case 'C':
1085 x = 12;
1086 break;
1087 case 'd':
1088 case 'D':
1089 x = 13;
1090 break;
1091 case 'e':
1092 case 'E':
1093 x = 14;
1094 break;
1095 case 'f':
1096 case 'F':
1097 x = 15;
1098 break;
1099 default:
1100 x = -1;
1101 break;
1102 }
1103 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001104}
1105
1106/* convert a float to a hexadecimal string */
1107
1108/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1109 of the form 4k+1. */
1110#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1111
1112static PyObject *
1113float_hex(PyObject *v)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 double x, m;
1116 int e, shift, i, si, esign;
1117 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1118 trailing NUL byte. */
1119 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001124 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001127 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 return PyUnicode_FromString("-0x0.0p+0");
1129 else
1130 return PyUnicode_FromString("0x0.0p+0");
1131 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 m = frexp(fabs(x), &e);
1134 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1135 m = ldexp(m, shift);
1136 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 si = 0;
1139 s[si] = char_from_hex((int)m);
1140 si++;
1141 m -= (int)m;
1142 s[si] = '.';
1143 si++;
1144 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1145 m *= 16.0;
1146 s[si] = char_from_hex((int)m);
1147 si++;
1148 m -= (int)m;
1149 }
1150 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (e < 0) {
1153 esign = (int)'-';
1154 e = -e;
1155 }
1156 else
1157 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (x < 0.0)
1160 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1161 else
1162 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001163}
1164
1165PyDoc_STRVAR(float_hex_doc,
1166"float.hex() -> string\n\
1167\n\
1168Return a hexadecimal representation of a floating-point number.\n\
1169>>> (-0.1).hex()\n\
1170'-0x1.999999999999ap-4'\n\
1171>>> 3.14159.hex()\n\
1172'0x1.921f9f01b866ep+1'");
1173
1174/* Convert a hexadecimal string to a float. */
1175
1176static PyObject *
1177float_fromhex(PyObject *cls, PyObject *arg)
1178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 PyObject *result_as_float, *result;
1180 double x;
1181 long exp, top_exp, lsb, key_digit;
1182 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1183 int half_eps, digit, round_up, negate=0;
1184 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 /*
1187 * For the sake of simplicity and correctness, we impose an artificial
1188 * limit on ndigits, the total number of hex digits in the coefficient
1189 * The limit is chosen to ensure that, writing exp for the exponent,
1190 *
1191 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1192 * guaranteed to overflow (provided it's nonzero)
1193 *
1194 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1195 * guaranteed to underflow to 0.
1196 *
1197 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1198 * overflow in the calculation of exp and top_exp below.
1199 *
1200 * More specifically, ndigits is assumed to satisfy the following
1201 * inequalities:
1202 *
1203 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1204 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1205 *
1206 * If either of these inequalities is not satisfied, a ValueError is
1207 * raised. Otherwise, write x for the value of the hex string, and
1208 * assume x is nonzero. Then
1209 *
1210 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1211 *
1212 * Now if exp > LONG_MAX/2 then:
1213 *
1214 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1215 * = DBL_MAX_EXP
1216 *
1217 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1218 * double, so overflows. If exp < LONG_MIN/2, then
1219 *
1220 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1221 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1222 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1223 *
1224 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1225 * when converted to a C double.
1226 *
1227 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1228 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1229 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 s = _PyUnicode_AsStringAndSize(arg, &length);
1232 if (s == NULL)
1233 return NULL;
1234 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /********************
1237 * Parse the string *
1238 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* leading whitespace */
1241 while (Py_ISSPACE(*s))
1242 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 /* infinities and nans */
1245 x = _Py_parse_inf_or_nan(s, &coeff_end);
1246 if (coeff_end != s) {
1247 s = coeff_end;
1248 goto finished;
1249 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 /* optional sign */
1252 if (*s == '-') {
1253 s++;
1254 negate = 1;
1255 }
1256 else if (*s == '+')
1257 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* [0x] */
1260 s_store = s;
1261 if (*s == '0') {
1262 s++;
1263 if (*s == 'x' || *s == 'X')
1264 s++;
1265 else
1266 s = s_store;
1267 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* coefficient: <integer> [. <fraction>] */
1270 coeff_start = s;
1271 while (hex_from_char(*s) >= 0)
1272 s++;
1273 s_store = s;
1274 if (*s == '.') {
1275 s++;
1276 while (hex_from_char(*s) >= 0)
1277 s++;
1278 coeff_end = s-1;
1279 }
1280 else
1281 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /* ndigits = total # of hex digits; fdigits = # after point */
1284 ndigits = coeff_end - coeff_start;
1285 fdigits = coeff_end - s_store;
1286 if (ndigits == 0)
1287 goto parse_error;
1288 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1289 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1290 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* [p <exponent>] */
1293 if (*s == 'p' || *s == 'P') {
1294 s++;
1295 exp_start = s;
1296 if (*s == '-' || *s == '+')
1297 s++;
1298 if (!('0' <= *s && *s <= '9'))
1299 goto parse_error;
1300 s++;
1301 while ('0' <= *s && *s <= '9')
1302 s++;
1303 exp = strtol(exp_start, NULL, 10);
1304 }
1305 else
1306 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001307
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001308/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1310 coeff_end-(j) : \
1311 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 /*******************************************
1314 * Compute rounded value of the hex string *
1315 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /* Discard leading zeros, and catch extreme overflow and underflow */
1318 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1319 ndigits--;
1320 if (ndigits == 0 || exp < LONG_MIN/2) {
1321 x = 0.0;
1322 goto finished;
1323 }
1324 if (exp > LONG_MAX/2)
1325 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 /* Adjust exponent for fractional part. */
1328 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1331 top_exp = exp + 4*((long)ndigits - 1);
1332 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1333 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* catch almost all nonextreme cases of overflow and underflow here */
1336 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1337 x = 0.0;
1338 goto finished;
1339 }
1340 if (top_exp > DBL_MAX_EXP)
1341 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 /* lsb = exponent of least significant bit of the *rounded* value.
1344 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1345 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 x = 0.0;
1348 if (exp >= lsb) {
1349 /* no rounding required */
1350 for (i = ndigits-1; i >= 0; i--)
1351 x = 16.0*x + HEX_DIGIT(i);
1352 x = ldexp(x, (int)(exp));
1353 goto finished;
1354 }
1355 /* rounding required. key_digit is the index of the hex digit
1356 containing the first bit to be rounded away. */
1357 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1358 key_digit = (lsb - exp - 1) / 4;
1359 for (i = ndigits-1; i > key_digit; i--)
1360 x = 16.0*x + HEX_DIGIT(i);
1361 digit = HEX_DIGIT(key_digit);
1362 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1365 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1366 if ((digit & half_eps) != 0) {
1367 round_up = 0;
1368 if ((digit & (3*half_eps-1)) != 0 ||
1369 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1370 round_up = 1;
1371 else
1372 for (i = key_digit-1; i >= 0; i--)
1373 if (HEX_DIGIT(i) != 0) {
1374 round_up = 1;
1375 break;
1376 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001377 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 x += 2*half_eps;
1379 if (top_exp == DBL_MAX_EXP &&
1380 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1381 /* overflow corner case: pre-rounded value <
1382 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1383 goto overflow_error;
1384 }
1385 }
1386 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001387
1388 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* optional trailing whitespace leading to the end of the string */
1390 while (Py_ISSPACE(*s))
1391 s++;
1392 if (s != s_end)
1393 goto parse_error;
1394 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1395 if (result_as_float == NULL)
1396 return NULL;
1397 result = PyObject_CallObject(cls, result_as_float);
1398 Py_DECREF(result_as_float);
1399 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001400
1401 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 PyErr_SetString(PyExc_OverflowError,
1403 "hexadecimal value too large to represent as a float");
1404 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
1406 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyErr_SetString(PyExc_ValueError,
1408 "invalid hexadecimal floating-point string");
1409 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001410
1411 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyErr_SetString(PyExc_ValueError,
1413 "hexadecimal string too long to convert");
1414 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001415}
1416
1417PyDoc_STRVAR(float_fromhex_doc,
1418"float.fromhex(string) -> float\n\
1419\n\
1420Create a floating-point number from a hexadecimal string.\n\
1421>>> float.fromhex('0x1.ffffp10')\n\
14222047.984375\n\
1423>>> float.fromhex('-0x1p-1074')\n\
1424-4.9406564584124654e-324");
1425
1426
Christian Heimes26855632008-01-27 23:50:43 +00001427static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001428float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 double self;
1431 double float_part;
1432 int exponent;
1433 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyObject *prev;
1436 PyObject *py_exponent = NULL;
1437 PyObject *numerator = NULL;
1438 PyObject *denominator = NULL;
1439 PyObject *result_pair = NULL;
1440 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001441
1442#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 prev = obj; \
1444 obj = call; \
1445 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (Py_IS_INFINITY(self)) {
1450 PyErr_SetString(PyExc_OverflowError,
1451 "Cannot pass infinity to float.as_integer_ratio.");
1452 return NULL;
1453 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (Py_IS_NAN(self)) {
1455 PyErr_SetString(PyExc_ValueError,
1456 "Cannot pass NaN to float.as_integer_ratio.");
1457 return NULL;
1458 }
Christian Heimes26855632008-01-27 23:50:43 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1461 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1462 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1465 float_part *= 2.0;
1466 exponent--;
1467 }
1468 /* self == float_part * 2**exponent exactly and float_part is integral.
1469 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1470 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 numerator = PyLong_FromDouble(float_part);
1473 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 /* fold in 2**exponent */
1476 denominator = PyLong_FromLong(1);
1477 py_exponent = PyLong_FromLong(labs((long)exponent));
1478 if (py_exponent == NULL) goto error;
1479 INPLACE_UPDATE(py_exponent,
1480 long_methods->nb_lshift(denominator, py_exponent));
1481 if (py_exponent == NULL) goto error;
1482 if (exponent > 0) {
1483 INPLACE_UPDATE(numerator,
1484 long_methods->nb_multiply(numerator, py_exponent));
1485 if (numerator == NULL) goto error;
1486 }
1487 else {
1488 Py_DECREF(denominator);
1489 denominator = py_exponent;
1490 py_exponent = NULL;
1491 }
1492
1493 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001494
1495#undef INPLACE_UPDATE
1496error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_XDECREF(py_exponent);
1498 Py_XDECREF(denominator);
1499 Py_XDECREF(numerator);
1500 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001501}
1502
1503PyDoc_STRVAR(float_as_integer_ratio_doc,
1504"float.as_integer_ratio() -> (int, int)\n"
1505"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001506"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1507"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001508"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001509"\n"
1510">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001511"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001512">>> (0.0).as_integer_ratio()\n"
1513"(0, 1)\n"
1514">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001515"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001516
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001517
Jeremy Hylton938ace62002-07-17 16:30:39 +00001518static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001519float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1520
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521static PyObject *
1522float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyObject *x = Py_False; /* Integer zero */
1525 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (type != &PyFloat_Type)
1528 return float_subtype_new(type, args, kwds); /* Wimp out */
1529 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1530 return NULL;
1531 /* If it's a string, but not a string subclass, use
1532 PyFloat_FromString. */
1533 if (PyUnicode_CheckExact(x))
1534 return PyFloat_FromString(x);
1535 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536}
1537
Guido van Rossumbef14172001-08-29 15:47:46 +00001538/* Wimpy, slow approach to tp_new calls for subtypes of float:
1539 first create a regular float from whatever arguments we got,
1540 then allocate a subtype instance and initialize its ob_fval
1541 from the regular float. The regular float is then thrown away.
1542*/
1543static PyObject *
1544float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 assert(PyType_IsSubtype(type, &PyFloat_Type));
1549 tmp = float_new(&PyFloat_Type, args, kwds);
1550 if (tmp == NULL)
1551 return NULL;
1552 assert(PyFloat_CheckExact(tmp));
1553 newobj = type->tp_alloc(type, 0);
1554 if (newobj == NULL) {
1555 Py_DECREF(tmp);
1556 return NULL;
1557 }
1558 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1559 Py_DECREF(tmp);
1560 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001561}
1562
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001563static PyObject *
1564float_getnewargs(PyFloatObject *v)
1565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001567}
1568
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001569/* this is for the benefit of the pack/unpack routines below */
1570
1571typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001573} float_format_type;
1574
1575static float_format_type double_format, float_format;
1576static float_format_type detected_double_format, detected_float_format;
1577
1578static PyObject *
1579float_getformat(PyTypeObject *v, PyObject* arg)
1580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 char* s;
1582 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 if (!PyUnicode_Check(arg)) {
1585 PyErr_Format(PyExc_TypeError,
1586 "__getformat__() argument must be string, not %.500s",
1587 Py_TYPE(arg)->tp_name);
1588 return NULL;
1589 }
1590 s = _PyUnicode_AsString(arg);
1591 if (s == NULL)
1592 return NULL;
1593 if (strcmp(s, "double") == 0) {
1594 r = double_format;
1595 }
1596 else if (strcmp(s, "float") == 0) {
1597 r = float_format;
1598 }
1599 else {
1600 PyErr_SetString(PyExc_ValueError,
1601 "__getformat__() argument 1 must be "
1602 "'double' or 'float'");
1603 return NULL;
1604 }
1605
1606 switch (r) {
1607 case unknown_format:
1608 return PyUnicode_FromString("unknown");
1609 case ieee_little_endian_format:
1610 return PyUnicode_FromString("IEEE, little-endian");
1611 case ieee_big_endian_format:
1612 return PyUnicode_FromString("IEEE, big-endian");
1613 default:
1614 Py_FatalError("insane float_format or double_format");
1615 return NULL;
1616 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001617}
1618
1619PyDoc_STRVAR(float_getformat_doc,
1620"float.__getformat__(typestr) -> string\n"
1621"\n"
1622"You probably don't want to use this function. It exists mainly to be\n"
1623"used in Python's test suite.\n"
1624"\n"
1625"typestr must be 'double' or 'float'. This function returns whichever of\n"
1626"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1627"format of floating point numbers used by the C type named by typestr.");
1628
1629static PyObject *
1630float_setformat(PyTypeObject *v, PyObject* args)
1631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 char* typestr;
1633 char* format;
1634 float_format_type f;
1635 float_format_type detected;
1636 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1639 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 if (strcmp(typestr, "double") == 0) {
1642 p = &double_format;
1643 detected = detected_double_format;
1644 }
1645 else if (strcmp(typestr, "float") == 0) {
1646 p = &float_format;
1647 detected = detected_float_format;
1648 }
1649 else {
1650 PyErr_SetString(PyExc_ValueError,
1651 "__setformat__() argument 1 must "
1652 "be 'double' or 'float'");
1653 return NULL;
1654 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (strcmp(format, "unknown") == 0) {
1657 f = unknown_format;
1658 }
1659 else if (strcmp(format, "IEEE, little-endian") == 0) {
1660 f = ieee_little_endian_format;
1661 }
1662 else if (strcmp(format, "IEEE, big-endian") == 0) {
1663 f = ieee_big_endian_format;
1664 }
1665 else {
1666 PyErr_SetString(PyExc_ValueError,
1667 "__setformat__() argument 2 must be "
1668 "'unknown', 'IEEE, little-endian' or "
1669 "'IEEE, big-endian'");
1670 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (f != unknown_format && f != detected) {
1675 PyErr_Format(PyExc_ValueError,
1676 "can only set %s format to 'unknown' or the "
1677 "detected platform value", typestr);
1678 return NULL;
1679 }
1680
1681 *p = f;
1682 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001683}
1684
1685PyDoc_STRVAR(float_setformat_doc,
1686"float.__setformat__(typestr, fmt) -> None\n"
1687"\n"
1688"You probably don't want to use this function. It exists mainly to be\n"
1689"used in Python's test suite.\n"
1690"\n"
1691"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1692"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1693"one of the latter two if it appears to match the underlying C reality.\n"
1694"\n"
1695"Overrides the automatic determination of C-level floating point type.\n"
1696"This affects how floats are converted to and from binary strings.");
1697
Guido van Rossumb43daf72007-08-01 18:08:08 +00001698static PyObject *
1699float_getzero(PyObject *v, void *closure)
1700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001702}
1703
Eric Smith8c663262007-08-25 02:26:07 +00001704static PyObject *
1705float__format__(PyObject *self, PyObject *args)
1706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 _PyUnicodeWriter writer;
1709 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1712 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001713
1714 _PyUnicodeWriter_Init(&writer, 0);
1715 ret = _PyFloat_FormatAdvancedWriter(
1716 &writer,
1717 self,
1718 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1719 if (ret == -1) {
1720 _PyUnicodeWriter_Dealloc(&writer);
1721 return NULL;
1722 }
1723 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001724}
1725
1726PyDoc_STRVAR(float__format__doc,
1727"float.__format__(format_spec) -> string\n"
1728"\n"
1729"Formats the float according to format_spec.");
1730
1731
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001732static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1734 "Returns self, the complex conjugate of any float."},
1735 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1736 "Returns the Integral closest to x between 0 and x."},
1737 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1738 "Returns the Integral closest to x, rounding half toward even.\n"
1739 "When an argument is passed, works like built-in round(x, ndigits)."},
1740 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1741 float_as_integer_ratio_doc},
1742 {"fromhex", (PyCFunction)float_fromhex,
1743 METH_O|METH_CLASS, float_fromhex_doc},
1744 {"hex", (PyCFunction)float_hex,
1745 METH_NOARGS, float_hex_doc},
1746 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1747 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001748#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1750 "Returns True if the float is positive or negative infinite."},
1751 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1752 "Returns True if the float is finite, neither infinite nor NaN."},
1753 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1754 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001755#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1757 {"__getformat__", (PyCFunction)float_getformat,
1758 METH_O|METH_CLASS, float_getformat_doc},
1759 {"__setformat__", (PyCFunction)float_setformat,
1760 METH_VARARGS|METH_CLASS, float_setformat_doc},
1761 {"__format__", (PyCFunction)float__format__,
1762 METH_VARARGS, float__format__doc},
1763 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001764};
1765
Guido van Rossumb43daf72007-08-01 18:08:08 +00001766static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001768 (getter)float_float, (setter)NULL,
1769 "the real part of a complex number",
1770 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001772 (getter)float_getzero, (setter)NULL,
1773 "the imaginary part of a complex number",
1774 NULL},
1775 {NULL} /* Sentinel */
1776};
1777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001778PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779"float(x) -> floating point number\n\
1780\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001781Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782
1783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 float_add, /*nb_add*/
1786 float_sub, /*nb_subtract*/
1787 float_mul, /*nb_multiply*/
1788 float_rem, /*nb_remainder*/
1789 float_divmod, /*nb_divmod*/
1790 float_pow, /*nb_power*/
1791 (unaryfunc)float_neg, /*nb_negative*/
1792 (unaryfunc)float_float, /*nb_positive*/
1793 (unaryfunc)float_abs, /*nb_absolute*/
1794 (inquiry)float_bool, /*nb_bool*/
1795 0, /*nb_invert*/
1796 0, /*nb_lshift*/
1797 0, /*nb_rshift*/
1798 0, /*nb_and*/
1799 0, /*nb_xor*/
1800 0, /*nb_or*/
1801 float_trunc, /*nb_int*/
1802 0, /*nb_reserved*/
1803 float_float, /*nb_float*/
1804 0, /* nb_inplace_add */
1805 0, /* nb_inplace_subtract */
1806 0, /* nb_inplace_multiply */
1807 0, /* nb_inplace_remainder */
1808 0, /* nb_inplace_power */
1809 0, /* nb_inplace_lshift */
1810 0, /* nb_inplace_rshift */
1811 0, /* nb_inplace_and */
1812 0, /* nb_inplace_xor */
1813 0, /* nb_inplace_or */
1814 float_floor_div, /* nb_floor_divide */
1815 float_div, /* nb_true_divide */
1816 0, /* nb_inplace_floor_divide */
1817 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001818};
1819
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001820PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1822 "float",
1823 sizeof(PyFloatObject),
1824 0,
1825 (destructor)float_dealloc, /* tp_dealloc */
1826 0, /* tp_print */
1827 0, /* tp_getattr */
1828 0, /* tp_setattr */
1829 0, /* tp_reserved */
1830 (reprfunc)float_repr, /* tp_repr */
1831 &float_as_number, /* tp_as_number */
1832 0, /* tp_as_sequence */
1833 0, /* tp_as_mapping */
1834 (hashfunc)float_hash, /* tp_hash */
1835 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001836 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 PyObject_GenericGetAttr, /* tp_getattro */
1838 0, /* tp_setattro */
1839 0, /* tp_as_buffer */
1840 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1841 float_doc, /* tp_doc */
1842 0, /* tp_traverse */
1843 0, /* tp_clear */
1844 float_richcompare, /* tp_richcompare */
1845 0, /* tp_weaklistoffset */
1846 0, /* tp_iter */
1847 0, /* tp_iternext */
1848 float_methods, /* tp_methods */
1849 0, /* tp_members */
1850 float_getset, /* tp_getset */
1851 0, /* tp_base */
1852 0, /* tp_dict */
1853 0, /* tp_descr_get */
1854 0, /* tp_descr_set */
1855 0, /* tp_dictoffset */
1856 0, /* tp_init */
1857 0, /* tp_alloc */
1858 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001859};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001860
1861void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001862_PyFloat_Init(void)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* We attempt to determine if this machine is using IEEE
1865 floating point formats by peering at the bits of some
1866 carefully chosen values. If it looks like we are on an
1867 IEEE platform, the float packing/unpacking routines can
1868 just copy bits, if not they resort to arithmetic & shifts
1869 and masks. The shifts & masks approach works on all finite
1870 values, but what happens to infinities, NaNs and signed
1871 zeroes on packing is an accident, and attempting to unpack
1872 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 Note that if we're on some whacked-out platform which uses
1875 IEEE formats but isn't strictly little-endian or big-
1876 endian, we will fall back to the portable shifts & masks
1877 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001878
1879#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 {
1881 double x = 9006104071832581.0;
1882 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1883 detected_double_format = ieee_big_endian_format;
1884 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1885 detected_double_format = ieee_little_endian_format;
1886 else
1887 detected_double_format = unknown_format;
1888 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001889#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001891#endif
1892
1893#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 {
1895 float y = 16711938.0;
1896 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1897 detected_float_format = ieee_big_endian_format;
1898 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1899 detected_float_format = ieee_little_endian_format;
1900 else
1901 detected_float_format = unknown_format;
1902 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001903#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001905#endif
1906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 double_format = detected_double_format;
1908 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 /* Init float info */
1911 if (FloatInfoType.tp_name == 0)
1912 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001913}
1914
Georg Brandl2ee470f2008-07-16 12:55:28 +00001915int
1916PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001917{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001918 PyFloatObject *f = free_list, *next;
1919 int i = numfree;
1920 while (f) {
1921 next = (PyFloatObject*) Py_TYPE(f);
1922 PyObject_FREE(f);
1923 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001925 free_list = NULL;
1926 numfree = 0;
1927 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001928}
1929
1930void
1931PyFloat_Fini(void)
1932{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001933 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001934}
Tim Peters9905b942003-03-20 20:53:32 +00001935
David Malcolm49526f42012-06-22 14:55:41 -04001936/* Print summary info about the state of the optimized allocator */
1937void
1938_PyFloat_DebugMallocStats(FILE *out)
1939{
1940 _PyDebugAllocatorStats(out,
1941 "free PyFloatObject",
1942 numfree, sizeof(PyFloatObject));
1943}
1944
1945
Tim Peters9905b942003-03-20 20:53:32 +00001946/*----------------------------------------------------------------------------
1947 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001948 */
1949int
1950_PyFloat_Pack4(double x, unsigned char *p, int le)
1951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 if (float_format == unknown_format) {
1953 unsigned char sign;
1954 int e;
1955 double f;
1956 unsigned int fbits;
1957 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 if (le) {
1960 p += 3;
1961 incr = -1;
1962 }
Tim Peters9905b942003-03-20 20:53:32 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (x < 0) {
1965 sign = 1;
1966 x = -x;
1967 }
1968 else
1969 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 /* Normalize f to be in the range [1.0, 2.0) */
1974 if (0.5 <= f && f < 1.0) {
1975 f *= 2.0;
1976 e--;
1977 }
1978 else if (f == 0.0)
1979 e = 0;
1980 else {
1981 PyErr_SetString(PyExc_SystemError,
1982 "frexp() result out of range");
1983 return -1;
1984 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (e >= 128)
1987 goto Overflow;
1988 else if (e < -126) {
1989 /* Gradual underflow */
1990 f = ldexp(f, 126 + e);
1991 e = 0;
1992 }
1993 else if (!(e == 0 && f == 0.0)) {
1994 e += 127;
1995 f -= 1.0; /* Get rid of leading 1 */
1996 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 f *= 8388608.0; /* 2**23 */
1999 fbits = (unsigned int)(f + 0.5); /* Round */
2000 assert(fbits <= 8388608);
2001 if (fbits >> 23) {
2002 /* The carry propagated out of a string of 23 1 bits. */
2003 fbits = 0;
2004 ++e;
2005 if (e >= 255)
2006 goto Overflow;
2007 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 /* First byte */
2010 *p = (sign << 7) | (e >> 1);
2011 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 /* Second byte */
2014 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2015 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 /* Third byte */
2018 *p = (fbits >> 8) & 0xFF;
2019 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Fourth byte */
2022 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Done */
2025 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 }
2028 else {
2029 float y = (float)x;
2030 const char *s = (char*)&y;
2031 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2034 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 if ((float_format == ieee_little_endian_format && !le)
2037 || (float_format == ieee_big_endian_format && le)) {
2038 p += 3;
2039 incr = -1;
2040 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 for (i = 0; i < 4; i++) {
2043 *p = *s++;
2044 p += incr;
2045 }
2046 return 0;
2047 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002048 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 PyErr_SetString(PyExc_OverflowError,
2050 "float too large to pack with f format");
2051 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002052}
2053
2054int
2055_PyFloat_Pack8(double x, unsigned char *p, int le)
2056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (double_format == unknown_format) {
2058 unsigned char sign;
2059 int e;
2060 double f;
2061 unsigned int fhi, flo;
2062 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (le) {
2065 p += 7;
2066 incr = -1;
2067 }
Tim Peters9905b942003-03-20 20:53:32 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (x < 0) {
2070 sign = 1;
2071 x = -x;
2072 }
2073 else
2074 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* Normalize f to be in the range [1.0, 2.0) */
2079 if (0.5 <= f && f < 1.0) {
2080 f *= 2.0;
2081 e--;
2082 }
2083 else if (f == 0.0)
2084 e = 0;
2085 else {
2086 PyErr_SetString(PyExc_SystemError,
2087 "frexp() result out of range");
2088 return -1;
2089 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 if (e >= 1024)
2092 goto Overflow;
2093 else if (e < -1022) {
2094 /* Gradual underflow */
2095 f = ldexp(f, 1022 + e);
2096 e = 0;
2097 }
2098 else if (!(e == 0 && f == 0.0)) {
2099 e += 1023;
2100 f -= 1.0; /* Get rid of leading 1 */
2101 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2104 f *= 268435456.0; /* 2**28 */
2105 fhi = (unsigned int)f; /* Truncate */
2106 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 f -= (double)fhi;
2109 f *= 16777216.0; /* 2**24 */
2110 flo = (unsigned int)(f + 0.5); /* Round */
2111 assert(flo <= 16777216);
2112 if (flo >> 24) {
2113 /* The carry propagated out of a string of 24 1 bits. */
2114 flo = 0;
2115 ++fhi;
2116 if (fhi >> 28) {
2117 /* And it also progagated out of the next 28 bits. */
2118 fhi = 0;
2119 ++e;
2120 if (e >= 2047)
2121 goto Overflow;
2122 }
2123 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* First byte */
2126 *p = (sign << 7) | (e >> 4);
2127 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* Second byte */
2130 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2131 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 /* Third byte */
2134 *p = (fhi >> 16) & 0xFF;
2135 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 /* Fourth byte */
2138 *p = (fhi >> 8) & 0xFF;
2139 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 /* Fifth byte */
2142 *p = fhi & 0xFF;
2143 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 /* Sixth byte */
2146 *p = (flo >> 16) & 0xFF;
2147 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* Seventh byte */
2150 *p = (flo >> 8) & 0xFF;
2151 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 /* Eighth byte */
2154 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002155 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /* Done */
2158 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 Overflow:
2161 PyErr_SetString(PyExc_OverflowError,
2162 "float too large to pack with d format");
2163 return -1;
2164 }
2165 else {
2166 const char *s = (char*)&x;
2167 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if ((double_format == ieee_little_endian_format && !le)
2170 || (double_format == ieee_big_endian_format && le)) {
2171 p += 7;
2172 incr = -1;
2173 }
2174
2175 for (i = 0; i < 8; i++) {
2176 *p = *s++;
2177 p += incr;
2178 }
2179 return 0;
2180 }
Tim Peters9905b942003-03-20 20:53:32 +00002181}
2182
2183double
2184_PyFloat_Unpack4(const unsigned char *p, int le)
2185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (float_format == unknown_format) {
2187 unsigned char sign;
2188 int e;
2189 unsigned int f;
2190 double x;
2191 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (le) {
2194 p += 3;
2195 incr = -1;
2196 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* First byte */
2199 sign = (*p >> 7) & 1;
2200 e = (*p & 0x7F) << 1;
2201 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* Second byte */
2204 e |= (*p >> 7) & 1;
2205 f = (*p & 0x7F) << 16;
2206 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (e == 255) {
2209 PyErr_SetString(
2210 PyExc_ValueError,
2211 "can't unpack IEEE 754 special value "
2212 "on non-IEEE platform");
2213 return -1;
2214 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* Third byte */
2217 f |= *p << 8;
2218 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Fourth byte */
2221 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* XXX This sadly ignores Inf/NaN issues */
2226 if (e == 0)
2227 e = -126;
2228 else {
2229 x += 1.0;
2230 e -= 127;
2231 }
2232 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (sign)
2235 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 return x;
2238 }
2239 else {
2240 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if ((float_format == ieee_little_endian_format && !le)
2243 || (float_format == ieee_big_endian_format && le)) {
2244 char buf[4];
2245 char *d = &buf[3];
2246 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 for (i = 0; i < 4; i++) {
2249 *d-- = *p++;
2250 }
2251 memcpy(&x, buf, 4);
2252 }
2253 else {
2254 memcpy(&x, p, 4);
2255 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return x;
2258 }
Tim Peters9905b942003-03-20 20:53:32 +00002259}
2260
2261double
2262_PyFloat_Unpack8(const unsigned char *p, int le)
2263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (double_format == unknown_format) {
2265 unsigned char sign;
2266 int e;
2267 unsigned int fhi, flo;
2268 double x;
2269 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (le) {
2272 p += 7;
2273 incr = -1;
2274 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 /* First byte */
2277 sign = (*p >> 7) & 1;
2278 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* Second byte */
2283 e |= (*p >> 4) & 0xF;
2284 fhi = (*p & 0xF) << 24;
2285 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (e == 2047) {
2288 PyErr_SetString(
2289 PyExc_ValueError,
2290 "can't unpack IEEE 754 special value "
2291 "on non-IEEE platform");
2292 return -1.0;
2293 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Third byte */
2296 fhi |= *p << 16;
2297 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* Fourth byte */
2300 fhi |= *p << 8;
2301 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* Fifth byte */
2304 fhi |= *p;
2305 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Sixth byte */
2308 flo = *p << 16;
2309 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Seventh byte */
2312 flo |= *p << 8;
2313 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* Eighth byte */
2316 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2319 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 if (e == 0)
2322 e = -1022;
2323 else {
2324 x += 1.0;
2325 e -= 1023;
2326 }
2327 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 if (sign)
2330 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 return x;
2333 }
2334 else {
2335 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if ((double_format == ieee_little_endian_format && !le)
2338 || (double_format == ieee_big_endian_format && le)) {
2339 char buf[8];
2340 char *d = &buf[7];
2341 int i;
2342
2343 for (i = 0; i < 8; i++) {
2344 *d-- = *p++;
2345 }
2346 memcpy(&x, buf, 8);
2347 }
2348 else {
2349 memcpy(&x, p, 8);
2350 }
2351
2352 return x;
2353 }
Tim Peters9905b942003-03-20 20:53:32 +00002354}