blob: 07d31b296ac57770f800cee536cd058a51a3b3d1 [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;
270 char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
Mark Dickinson388122d2010-08-04 20:56:28 +0000271 'r', 0,
Eric Smith63376222009-05-05 14:04:18 +0000272 Py_DTSF_ADD_DOT_0,
Eric Smith0923d1d2009-04-16 20:16:10 +0000273 NULL);
274 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000275 return PyErr_NoMemory();
Eric Smith0923d1d2009-04-16 20:16:10 +0000276 result = PyUnicode_FromString(buf);
277 PyMem_Free(buf);
278 return result;
279}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000280
Tim Peters307fa782004-09-23 08:06:40 +0000281/* Comparison is pretty much a nightmare. When comparing float to float,
282 * we do it as straightforwardly (and long-windedly) as conceivable, so
283 * that, e.g., Python x == y delivers the same result as the platform
284 * C x == y when x and/or y is a NaN.
285 * When mixing float with an integer type, there's no good *uniform* approach.
286 * Converting the double to an integer obviously doesn't work, since we
287 * may lose info from fractional bits. Converting the integer to a double
288 * also has two failure modes: (1) a long int may trigger overflow (too
289 * large to fit in the dynamic range of a C double); (2) even a C long may have
290 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
291 * 63 bits of precision, but a C double probably has only 53), and then
292 * we can falsely claim equality when low-order integer bits are lost by
293 * coercion to double. So this part is painful too.
294 */
295
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000296static PyObject*
297float_richcompare(PyObject *v, PyObject *w, int op)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 double i, j;
300 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 assert(PyFloat_Check(v));
303 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 /* Switch on the type of w. Set i and j to doubles to be compared,
306 * and op to the richcomp to use.
307 */
308 if (PyFloat_Check(w))
309 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 else if (!Py_IS_FINITE(i)) {
312 if (PyLong_Check(w))
313 /* If i is an infinity, its magnitude exceeds any
314 * finite integer, so it doesn't matter which int we
315 * compare i with. If i is a NaN, similarly.
316 */
317 j = 0.0;
318 else
319 goto Unimplemented;
320 }
Tim Peters307fa782004-09-23 08:06:40 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 else if (PyLong_Check(w)) {
323 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
324 int wsign = _PyLong_Sign(w);
325 size_t nbits;
326 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (vsign != wsign) {
329 /* Magnitudes are irrelevant -- the signs alone
330 * determine the outcome.
331 */
332 i = (double)vsign;
333 j = (double)wsign;
334 goto Compare;
335 }
336 /* The signs are the same. */
337 /* Convert w to a double if it fits. In particular, 0 fits. */
338 nbits = _PyLong_NumBits(w);
339 if (nbits == (size_t)-1 && PyErr_Occurred()) {
340 /* This long is so large that size_t isn't big enough
341 * to hold the # of bits. Replace with little doubles
342 * that give the same outcome -- w is so large that
343 * its magnitude must exceed the magnitude of any
344 * finite float.
345 */
346 PyErr_Clear();
347 i = (double)vsign;
348 assert(wsign != 0);
349 j = wsign * 2.0;
350 goto Compare;
351 }
352 if (nbits <= 48) {
353 j = PyLong_AsDouble(w);
354 /* It's impossible that <= 48 bits overflowed. */
355 assert(j != -1.0 || ! PyErr_Occurred());
356 goto Compare;
357 }
358 assert(wsign != 0); /* else nbits was 0 */
359 assert(vsign != 0); /* if vsign were 0, then since wsign is
360 * not 0, we would have taken the
361 * vsign != wsign branch at the start */
362 /* We want to work with non-negative numbers. */
363 if (vsign < 0) {
364 /* "Multiply both sides" by -1; this also swaps the
365 * comparator.
366 */
367 i = -i;
368 op = _Py_SwappedOp[op];
369 }
370 assert(i > 0.0);
371 (void) frexp(i, &exponent);
372 /* exponent is the # of bits in v before the radix point;
373 * we know that nbits (the # of bits in w) > 48 at this point
374 */
375 if (exponent < 0 || (size_t)exponent < nbits) {
376 i = 1.0;
377 j = 2.0;
378 goto Compare;
379 }
380 if ((size_t)exponent > nbits) {
381 i = 2.0;
382 j = 1.0;
383 goto Compare;
384 }
385 /* v and w have the same number of bits before the radix
386 * point. Construct two longs that have the same comparison
387 * outcome.
388 */
389 {
390 double fracpart;
391 double intpart;
392 PyObject *result = NULL;
393 PyObject *one = NULL;
394 PyObject *vv = NULL;
395 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (wsign < 0) {
398 ww = PyNumber_Negative(w);
399 if (ww == NULL)
400 goto Error;
401 }
402 else
403 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 fracpart = modf(i, &intpart);
406 vv = PyLong_FromDouble(intpart);
407 if (vv == NULL)
408 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (fracpart != 0.0) {
411 /* Shift left, and or a 1 bit into vv
412 * to represent the lost fraction.
413 */
414 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 one = PyLong_FromLong(1);
417 if (one == NULL)
418 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 temp = PyNumber_Lshift(ww, one);
421 if (temp == NULL)
422 goto Error;
423 Py_DECREF(ww);
424 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 temp = PyNumber_Lshift(vv, one);
427 if (temp == NULL)
428 goto Error;
429 Py_DECREF(vv);
430 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 temp = PyNumber_Or(vv, one);
433 if (temp == NULL)
434 goto Error;
435 Py_DECREF(vv);
436 vv = temp;
437 }
Tim Peters307fa782004-09-23 08:06:40 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 r = PyObject_RichCompareBool(vv, ww, op);
440 if (r < 0)
441 goto Error;
442 result = PyBool_FromLong(r);
443 Error:
444 Py_XDECREF(vv);
445 Py_XDECREF(ww);
446 Py_XDECREF(one);
447 return result;
448 }
449 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 else /* w isn't float, int, or long */
452 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000453
454 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 PyFPE_START_PROTECT("richcompare", return NULL)
456 switch (op) {
457 case Py_EQ:
458 r = i == j;
459 break;
460 case Py_NE:
461 r = i != j;
462 break;
463 case Py_LE:
464 r = i <= j;
465 break;
466 case Py_GE:
467 r = i >= j;
468 break;
469 case Py_LT:
470 r = i < j;
471 break;
472 case Py_GT:
473 r = i > j;
474 break;
475 }
476 PyFPE_END_PROTECT(r)
477 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000478
479 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500480 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000481}
482
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000483static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000484float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000487}
488
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000490float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 double a,b;
493 CONVERT_TO_DOUBLE(v, a);
494 CONVERT_TO_DOUBLE(w, b);
495 PyFPE_START_PROTECT("add", return 0)
496 a = a + b;
497 PyFPE_END_PROTECT(a)
498 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000499}
500
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000501static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000502float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 double a,b;
505 CONVERT_TO_DOUBLE(v, a);
506 CONVERT_TO_DOUBLE(w, b);
507 PyFPE_START_PROTECT("subtract", return 0)
508 a = a - b;
509 PyFPE_END_PROTECT(a)
510 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511}
512
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000514float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 double a,b;
517 CONVERT_TO_DOUBLE(v, a);
518 CONVERT_TO_DOUBLE(w, b);
519 PyFPE_START_PROTECT("multiply", return 0)
520 a = a * b;
521 PyFPE_END_PROTECT(a)
522 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523}
524
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000525static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000526float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 double a,b;
529 CONVERT_TO_DOUBLE(v, a);
530 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (b == 0.0) {
532 PyErr_SetString(PyExc_ZeroDivisionError,
533 "float division by zero");
534 return NULL;
535 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 PyFPE_START_PROTECT("divide", return 0)
537 a = a / b;
538 PyFPE_END_PROTECT(a)
539 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000543float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 double vx, wx;
546 double mod;
547 CONVERT_TO_DOUBLE(v, vx);
548 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (wx == 0.0) {
550 PyErr_SetString(PyExc_ZeroDivisionError,
551 "float modulo");
552 return NULL;
553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 PyFPE_START_PROTECT("modulo", return 0)
555 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000556 if (mod) {
557 /* ensure the remainder has the same sign as the denominator */
558 if ((wx < 0) != (mod < 0)) {
559 mod += wx;
560 }
561 }
562 else {
563 /* the remainder is zero, and in the presence of signed zeroes
564 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000565 it has the same sign as the denominator. */
566 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
568 PyFPE_END_PROTECT(mod)
569 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double vx, wx;
576 double div, mod, floordiv;
577 CONVERT_TO_DOUBLE(v, vx);
578 CONVERT_TO_DOUBLE(w, wx);
579 if (wx == 0.0) {
580 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
581 return NULL;
582 }
583 PyFPE_START_PROTECT("divmod", return 0)
584 mod = fmod(vx, wx);
585 /* fmod is typically exact, so vx-mod is *mathematically* an
586 exact multiple of wx. But this is fp arithmetic, and fp
587 vx - mod is an approximation; the result is that div may
588 not be an exact integral value after the division, although
589 it will always be very close to one.
590 */
591 div = (vx - mod) / wx;
592 if (mod) {
593 /* ensure the remainder has the same sign as the denominator */
594 if ((wx < 0) != (mod < 0)) {
595 mod += wx;
596 div -= 1.0;
597 }
598 }
599 else {
600 /* the remainder is zero, and in the presence of signed zeroes
601 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000602 it has the same sign as the denominator. */
603 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 }
605 /* snap quotient to nearest integral value */
606 if (div) {
607 floordiv = floor(div);
608 if (div - floordiv > 0.5)
609 floordiv += 1.0;
610 }
611 else {
612 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000613 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 }
615 PyFPE_END_PROTECT(floordiv)
616 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000617}
618
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000620float_floor_div(PyObject *v, PyObject *w)
621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 t = float_divmod(v, w);
625 if (t == NULL || t == Py_NotImplemented)
626 return t;
627 assert(PyTuple_CheckExact(t));
628 r = PyTuple_GET_ITEM(t, 0);
629 Py_INCREF(r);
630 Py_DECREF(t);
631 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000632}
633
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000634/* determine whether x is an odd integer or not; assumes that
635 x is not an infinity or nan. */
636#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
637
Tim Peters63a35712001-12-11 19:57:24 +0000638static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000639float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 double iv, iw, ix;
642 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if ((PyObject *)z != Py_None) {
645 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
646 "allowed unless all arguments are integers");
647 return NULL;
648 }
Tim Peters32f453e2001-09-03 08:35:41 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 CONVERT_TO_DOUBLE(v, iv);
651 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Sort out special cases here instead of relying on pow() */
654 if (iw == 0) { /* v**0 is 1, even 0**0 */
655 return PyFloat_FromDouble(1.0);
656 }
657 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
658 return PyFloat_FromDouble(iv);
659 }
660 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
661 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
662 }
663 if (Py_IS_INFINITY(iw)) {
664 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
665 * abs(v) > 1 (including case where v infinite)
666 *
667 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
668 * abs(v) > 1 (including case where v infinite)
669 */
670 iv = fabs(iv);
671 if (iv == 1.0)
672 return PyFloat_FromDouble(1.0);
673 else if ((iw > 0.0) == (iv > 1.0))
674 return PyFloat_FromDouble(fabs(iw)); /* return inf */
675 else
676 return PyFloat_FromDouble(0.0);
677 }
678 if (Py_IS_INFINITY(iv)) {
679 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
680 * both cases, we need to add the appropriate sign if w is
681 * an odd integer.
682 */
683 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
684 if (iw > 0.0)
685 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
686 else
687 return PyFloat_FromDouble(iw_is_odd ?
688 copysign(0.0, iv) : 0.0);
689 }
690 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
691 (already dealt with above), and an error
692 if w is negative. */
693 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
694 if (iw < 0.0) {
695 PyErr_SetString(PyExc_ZeroDivisionError,
696 "0.0 cannot be raised to a "
697 "negative power");
698 return NULL;
699 }
700 /* use correct sign if iw is odd */
701 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
702 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (iv < 0.0) {
705 /* Whether this is an error is a mess, and bumps into libm
706 * bugs so we have to figure it out ourselves.
707 */
708 if (iw != floor(iw)) {
709 /* Negative numbers raised to fractional powers
710 * become complex.
711 */
712 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
713 }
714 /* iw is an exact integer, albeit perhaps a very large
715 * one. Replace iv by its absolute value and remember
716 * to negate the pow result if iw is odd.
717 */
718 iv = -iv;
719 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
720 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
723 /* (-1) ** large_integer also ends up here. Here's an
724 * extract from the comments for the previous
725 * implementation explaining why this special case is
726 * necessary:
727 *
728 * -1 raised to an exact integer should never be exceptional.
729 * Alas, some libms (chiefly glibc as of early 2003) return
730 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
731 * happen to be representable in a *C* integer. That's a
732 * bug.
733 */
734 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
735 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 /* Now iv and iw are finite, iw is nonzero, and iv is
738 * positive and not equal to 1.0. We finally allow
739 * the platform pow to step in and do the rest.
740 */
741 errno = 0;
742 PyFPE_START_PROTECT("pow", return NULL)
743 ix = pow(iv, iw);
744 PyFPE_END_PROTECT(ix)
745 Py_ADJUST_ERANGE1(ix);
746 if (negate_result)
747 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (errno != 0) {
750 /* We don't expect any errno value other than ERANGE, but
751 * the range of libm bugs appears unbounded.
752 */
753 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
754 PyExc_ValueError);
755 return NULL;
756 }
757 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000758}
759
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000760#undef DOUBLE_IS_ODD_INTEGER
761
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000762static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000763float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766}
767
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000768static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000769float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772}
773
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000774static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000775float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000778}
779
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000780static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000781float_is_integer(PyObject *v)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 double x = PyFloat_AsDouble(v);
784 PyObject *o;
785
786 if (x == -1.0 && PyErr_Occurred())
787 return NULL;
788 if (!Py_IS_FINITE(x))
789 Py_RETURN_FALSE;
790 errno = 0;
791 PyFPE_START_PROTECT("is_integer", return NULL)
792 o = (floor(x) == x) ? Py_True : Py_False;
793 PyFPE_END_PROTECT(x)
794 if (errno != 0) {
795 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
796 PyExc_ValueError);
797 return NULL;
798 }
799 Py_INCREF(o);
800 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000801}
802
803#if 0
804static PyObject *
805float_is_inf(PyObject *v)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 double x = PyFloat_AsDouble(v);
808 if (x == -1.0 && PyErr_Occurred())
809 return NULL;
810 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000811}
812
813static PyObject *
814float_is_nan(PyObject *v)
815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 double x = PyFloat_AsDouble(v);
817 if (x == -1.0 && PyErr_Occurred())
818 return NULL;
819 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000820}
821
822static PyObject *
823float_is_finite(PyObject *v)
824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 double x = PyFloat_AsDouble(v);
826 if (x == -1.0 && PyErr_Occurred())
827 return NULL;
828 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000829}
830#endif
831
832static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000833float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 double x = PyFloat_AsDouble(v);
836 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 (void)modf(x, &wholepart);
839 /* Try to get out cheap if this fits in a Python int. The attempt
840 * to cast to long must be protected, as C doesn't define what
841 * happens if the double is too big to fit in a long. Some rare
842 * systems raise an exception then (RISCOS was mentioned as one,
843 * and someone using a non-default option on Sun also bumped into
844 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
845 * still be vulnerable: if a long has more bits of precision than
846 * a double, casting MIN/MAX to double may yield an approximation,
847 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
848 * yield true from the C expression wholepart<=LONG_MAX, despite
849 * that wholepart is actually greater than LONG_MAX.
850 */
851 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
852 const long aslong = (long)wholepart;
853 return PyLong_FromLong(aslong);
854 }
855 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000856}
857
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000858/* double_round: rounds a finite double to the closest multiple of
859 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
860 ndigits <= 323). Returns a Python float, or sets a Python error and
861 returns NULL on failure (OverflowError and memory errors are possible). */
862
863#ifndef PY_NO_SHORT_FLOAT_REPR
864/* version of double_round that uses the correctly-rounded string<->double
865 conversions from Python/dtoa.c */
866
867static PyObject *
868double_round(double x, int ndigits) {
869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 double rounded;
871 Py_ssize_t buflen, mybuflen=100;
872 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
873 int decpt, sign;
874 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000875 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000878 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000880 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (buf == NULL) {
882 PyErr_NoMemory();
883 return NULL;
884 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
887 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
888 buflen = buf_end - buf;
889 if (buflen + 8 > mybuflen) {
890 mybuflen = buflen+8;
891 mybuf = (char *)PyMem_Malloc(mybuflen);
892 if (mybuf == NULL) {
893 PyErr_NoMemory();
894 goto exit;
895 }
896 }
897 /* copy buf to mybuf, adding exponent, sign and leading 0 */
898 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
899 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* and convert the resulting string back to a double */
902 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000903 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000905 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (errno == ERANGE && fabs(rounded) >= 1.)
907 PyErr_SetString(PyExc_OverflowError,
908 "rounded value too large to represent");
909 else
910 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* done computing value; now clean up */
913 if (mybuf != shortbuf)
914 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 _Py_dg_freedtoa(buf);
917 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000918}
919
920#else /* PY_NO_SHORT_FLOAT_REPR */
921
922/* fallback version, to be used when correctly rounded binary<->decimal
923 conversions aren't available */
924
925static PyObject *
926double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 double pow1, pow2, y, z;
928 if (ndigits >= 0) {
929 if (ndigits > 22) {
930 /* pow1 and pow2 are each safe from overflow, but
931 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
932 pow1 = pow(10.0, (double)(ndigits-22));
933 pow2 = 1e22;
934 }
935 else {
936 pow1 = pow(10.0, (double)ndigits);
937 pow2 = 1.0;
938 }
939 y = (x*pow1)*pow2;
940 /* if y overflows, then rounded value is exactly x */
941 if (!Py_IS_FINITE(y))
942 return PyFloat_FromDouble(x);
943 }
944 else {
945 pow1 = pow(10.0, (double)-ndigits);
946 pow2 = 1.0; /* unused; silences a gcc compiler warning */
947 y = x / pow1;
948 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 z = round(y);
951 if (fabs(y-z) == 0.5)
952 /* halfway between two integers; use round-half-even */
953 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (ndigits >= 0)
956 z = (z / pow2) / pow1;
957 else
958 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* if computation resulted in overflow, raise OverflowError */
961 if (!Py_IS_FINITE(z)) {
962 PyErr_SetString(PyExc_OverflowError,
963 "overflow occurred during round");
964 return NULL;
965 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000968}
969
970#endif /* PY_NO_SHORT_FLOAT_REPR */
971
972/* round a Python float v to the closest multiple of 10**-ndigits */
973
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000974static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000975float_round(PyObject *v, PyObject *args)
976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 double x, rounded;
978 PyObject *o_ndigits = NULL;
979 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 x = PyFloat_AsDouble(v);
982 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
983 return NULL;
984 if (o_ndigits == NULL) {
985 /* single-argument round: round to nearest integer */
986 rounded = round(x);
987 if (fabs(x-rounded) == 0.5)
988 /* halfway case: round to even */
989 rounded = 2.0*round(x/2.0);
990 return PyLong_FromDouble(rounded);
991 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* interpret second argument as a Py_ssize_t; clips on overflow */
994 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
995 if (ndigits == -1 && PyErr_Occurred())
996 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* nans and infinities round to themselves */
999 if (!Py_IS_FINITE(x))
1000 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1003 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1004 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001005#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1006#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (ndigits > NDIGITS_MAX)
1008 /* return x */
1009 return PyFloat_FromDouble(x);
1010 else if (ndigits < NDIGITS_MIN)
1011 /* return 0.0, but with sign of x */
1012 return PyFloat_FromDouble(0.0*x);
1013 else
1014 /* finite x, and ndigits is not unreasonably large */
1015 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001016#undef NDIGITS_MAX
1017#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001018}
1019
1020static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001021float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (PyFloat_CheckExact(v))
1024 Py_INCREF(v);
1025 else
1026 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1027 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001028}
1029
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001030/* turn ASCII hex characters into integer values and vice versa */
1031
1032static char
1033char_from_hex(int x)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001036 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001037}
1038
1039static int
1040hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 int x;
1042 switch(c) {
1043 case '0':
1044 x = 0;
1045 break;
1046 case '1':
1047 x = 1;
1048 break;
1049 case '2':
1050 x = 2;
1051 break;
1052 case '3':
1053 x = 3;
1054 break;
1055 case '4':
1056 x = 4;
1057 break;
1058 case '5':
1059 x = 5;
1060 break;
1061 case '6':
1062 x = 6;
1063 break;
1064 case '7':
1065 x = 7;
1066 break;
1067 case '8':
1068 x = 8;
1069 break;
1070 case '9':
1071 x = 9;
1072 break;
1073 case 'a':
1074 case 'A':
1075 x = 10;
1076 break;
1077 case 'b':
1078 case 'B':
1079 x = 11;
1080 break;
1081 case 'c':
1082 case 'C':
1083 x = 12;
1084 break;
1085 case 'd':
1086 case 'D':
1087 x = 13;
1088 break;
1089 case 'e':
1090 case 'E':
1091 x = 14;
1092 break;
1093 case 'f':
1094 case 'F':
1095 x = 15;
1096 break;
1097 default:
1098 x = -1;
1099 break;
1100 }
1101 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001102}
1103
1104/* convert a float to a hexadecimal string */
1105
1106/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1107 of the form 4k+1. */
1108#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1109
1110static PyObject *
1111float_hex(PyObject *v)
1112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 double x, m;
1114 int e, shift, i, si, esign;
1115 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1116 trailing NUL byte. */
1117 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001122 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001125 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return PyUnicode_FromString("-0x0.0p+0");
1127 else
1128 return PyUnicode_FromString("0x0.0p+0");
1129 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 m = frexp(fabs(x), &e);
1132 shift = 1 - MAX(DBL_MIN_EXP - e, 0);
1133 m = ldexp(m, shift);
1134 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 si = 0;
1137 s[si] = char_from_hex((int)m);
1138 si++;
1139 m -= (int)m;
1140 s[si] = '.';
1141 si++;
1142 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1143 m *= 16.0;
1144 s[si] = char_from_hex((int)m);
1145 si++;
1146 m -= (int)m;
1147 }
1148 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (e < 0) {
1151 esign = (int)'-';
1152 e = -e;
1153 }
1154 else
1155 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (x < 0.0)
1158 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1159 else
1160 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001161}
1162
1163PyDoc_STRVAR(float_hex_doc,
1164"float.hex() -> string\n\
1165\n\
1166Return a hexadecimal representation of a floating-point number.\n\
1167>>> (-0.1).hex()\n\
1168'-0x1.999999999999ap-4'\n\
1169>>> 3.14159.hex()\n\
1170'0x1.921f9f01b866ep+1'");
1171
1172/* Convert a hexadecimal string to a float. */
1173
1174static PyObject *
1175float_fromhex(PyObject *cls, PyObject *arg)
1176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 PyObject *result_as_float, *result;
1178 double x;
1179 long exp, top_exp, lsb, key_digit;
1180 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1181 int half_eps, digit, round_up, negate=0;
1182 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /*
1185 * For the sake of simplicity and correctness, we impose an artificial
1186 * limit on ndigits, the total number of hex digits in the coefficient
1187 * The limit is chosen to ensure that, writing exp for the exponent,
1188 *
1189 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1190 * guaranteed to overflow (provided it's nonzero)
1191 *
1192 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1193 * guaranteed to underflow to 0.
1194 *
1195 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1196 * overflow in the calculation of exp and top_exp below.
1197 *
1198 * More specifically, ndigits is assumed to satisfy the following
1199 * inequalities:
1200 *
1201 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1202 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1203 *
1204 * If either of these inequalities is not satisfied, a ValueError is
1205 * raised. Otherwise, write x for the value of the hex string, and
1206 * assume x is nonzero. Then
1207 *
1208 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1209 *
1210 * Now if exp > LONG_MAX/2 then:
1211 *
1212 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1213 * = DBL_MAX_EXP
1214 *
1215 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1216 * double, so overflows. If exp < LONG_MIN/2, then
1217 *
1218 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1219 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1220 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1221 *
1222 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1223 * when converted to a C double.
1224 *
1225 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1226 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1227 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 s = _PyUnicode_AsStringAndSize(arg, &length);
1230 if (s == NULL)
1231 return NULL;
1232 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /********************
1235 * Parse the string *
1236 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 /* leading whitespace */
1239 while (Py_ISSPACE(*s))
1240 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 /* infinities and nans */
1243 x = _Py_parse_inf_or_nan(s, &coeff_end);
1244 if (coeff_end != s) {
1245 s = coeff_end;
1246 goto finished;
1247 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 /* optional sign */
1250 if (*s == '-') {
1251 s++;
1252 negate = 1;
1253 }
1254 else if (*s == '+')
1255 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 /* [0x] */
1258 s_store = s;
1259 if (*s == '0') {
1260 s++;
1261 if (*s == 'x' || *s == 'X')
1262 s++;
1263 else
1264 s = s_store;
1265 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* coefficient: <integer> [. <fraction>] */
1268 coeff_start = s;
1269 while (hex_from_char(*s) >= 0)
1270 s++;
1271 s_store = s;
1272 if (*s == '.') {
1273 s++;
1274 while (hex_from_char(*s) >= 0)
1275 s++;
1276 coeff_end = s-1;
1277 }
1278 else
1279 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 /* ndigits = total # of hex digits; fdigits = # after point */
1282 ndigits = coeff_end - coeff_start;
1283 fdigits = coeff_end - s_store;
1284 if (ndigits == 0)
1285 goto parse_error;
1286 if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1287 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
1288 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 /* [p <exponent>] */
1291 if (*s == 'p' || *s == 'P') {
1292 s++;
1293 exp_start = s;
1294 if (*s == '-' || *s == '+')
1295 s++;
1296 if (!('0' <= *s && *s <= '9'))
1297 goto parse_error;
1298 s++;
1299 while ('0' <= *s && *s <= '9')
1300 s++;
1301 exp = strtol(exp_start, NULL, 10);
1302 }
1303 else
1304 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001305
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001306/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1308 coeff_end-(j) : \
1309 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 /*******************************************
1312 * Compute rounded value of the hex string *
1313 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /* Discard leading zeros, and catch extreme overflow and underflow */
1316 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1317 ndigits--;
1318 if (ndigits == 0 || exp < LONG_MIN/2) {
1319 x = 0.0;
1320 goto finished;
1321 }
1322 if (exp > LONG_MAX/2)
1323 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* Adjust exponent for fractional part. */
1326 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1329 top_exp = exp + 4*((long)ndigits - 1);
1330 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1331 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 /* catch almost all nonextreme cases of overflow and underflow here */
1334 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1335 x = 0.0;
1336 goto finished;
1337 }
1338 if (top_exp > DBL_MAX_EXP)
1339 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* lsb = exponent of least significant bit of the *rounded* value.
1342 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
1343 lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 x = 0.0;
1346 if (exp >= lsb) {
1347 /* no rounding required */
1348 for (i = ndigits-1; i >= 0; i--)
1349 x = 16.0*x + HEX_DIGIT(i);
1350 x = ldexp(x, (int)(exp));
1351 goto finished;
1352 }
1353 /* rounding required. key_digit is the index of the hex digit
1354 containing the first bit to be rounded away. */
1355 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1356 key_digit = (lsb - exp - 1) / 4;
1357 for (i = ndigits-1; i > key_digit; i--)
1358 x = 16.0*x + HEX_DIGIT(i);
1359 digit = HEX_DIGIT(key_digit);
1360 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1363 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1364 if ((digit & half_eps) != 0) {
1365 round_up = 0;
1366 if ((digit & (3*half_eps-1)) != 0 ||
1367 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1368 round_up = 1;
1369 else
1370 for (i = key_digit-1; i >= 0; i--)
1371 if (HEX_DIGIT(i) != 0) {
1372 round_up = 1;
1373 break;
1374 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001375 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 x += 2*half_eps;
1377 if (top_exp == DBL_MAX_EXP &&
1378 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1379 /* overflow corner case: pre-rounded value <
1380 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1381 goto overflow_error;
1382 }
1383 }
1384 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001385
1386 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 /* optional trailing whitespace leading to the end of the string */
1388 while (Py_ISSPACE(*s))
1389 s++;
1390 if (s != s_end)
1391 goto parse_error;
1392 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1393 if (result_as_float == NULL)
1394 return NULL;
1395 result = PyObject_CallObject(cls, result_as_float);
1396 Py_DECREF(result_as_float);
1397 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001398
1399 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyErr_SetString(PyExc_OverflowError,
1401 "hexadecimal value too large to represent as a float");
1402 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001403
1404 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyErr_SetString(PyExc_ValueError,
1406 "invalid hexadecimal floating-point string");
1407 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001408
1409 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyErr_SetString(PyExc_ValueError,
1411 "hexadecimal string too long to convert");
1412 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001413}
1414
1415PyDoc_STRVAR(float_fromhex_doc,
1416"float.fromhex(string) -> float\n\
1417\n\
1418Create a floating-point number from a hexadecimal string.\n\
1419>>> float.fromhex('0x1.ffffp10')\n\
14202047.984375\n\
1421>>> float.fromhex('-0x1p-1074')\n\
1422-4.9406564584124654e-324");
1423
1424
Christian Heimes26855632008-01-27 23:50:43 +00001425static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001426float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 double self;
1429 double float_part;
1430 int exponent;
1431 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 PyObject *prev;
1434 PyObject *py_exponent = NULL;
1435 PyObject *numerator = NULL;
1436 PyObject *denominator = NULL;
1437 PyObject *result_pair = NULL;
1438 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001439
1440#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 prev = obj; \
1442 obj = call; \
1443 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (Py_IS_INFINITY(self)) {
1448 PyErr_SetString(PyExc_OverflowError,
1449 "Cannot pass infinity to float.as_integer_ratio.");
1450 return NULL;
1451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (Py_IS_NAN(self)) {
1453 PyErr_SetString(PyExc_ValueError,
1454 "Cannot pass NaN to float.as_integer_ratio.");
1455 return NULL;
1456 }
Christian Heimes26855632008-01-27 23:50:43 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1459 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1460 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1463 float_part *= 2.0;
1464 exponent--;
1465 }
1466 /* self == float_part * 2**exponent exactly and float_part is integral.
1467 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1468 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 numerator = PyLong_FromDouble(float_part);
1471 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 /* fold in 2**exponent */
1474 denominator = PyLong_FromLong(1);
1475 py_exponent = PyLong_FromLong(labs((long)exponent));
1476 if (py_exponent == NULL) goto error;
1477 INPLACE_UPDATE(py_exponent,
1478 long_methods->nb_lshift(denominator, py_exponent));
1479 if (py_exponent == NULL) goto error;
1480 if (exponent > 0) {
1481 INPLACE_UPDATE(numerator,
1482 long_methods->nb_multiply(numerator, py_exponent));
1483 if (numerator == NULL) goto error;
1484 }
1485 else {
1486 Py_DECREF(denominator);
1487 denominator = py_exponent;
1488 py_exponent = NULL;
1489 }
1490
1491 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001492
1493#undef INPLACE_UPDATE
1494error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 Py_XDECREF(py_exponent);
1496 Py_XDECREF(denominator);
1497 Py_XDECREF(numerator);
1498 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001499}
1500
1501PyDoc_STRVAR(float_as_integer_ratio_doc,
1502"float.as_integer_ratio() -> (int, int)\n"
1503"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001504"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1505"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001506"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001507"\n"
1508">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001509"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001510">>> (0.0).as_integer_ratio()\n"
1511"(0, 1)\n"
1512">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001513"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001514
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001515
Jeremy Hylton938ace62002-07-17 16:30:39 +00001516static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001517float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1518
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519static PyObject *
1520float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyObject *x = Py_False; /* Integer zero */
1523 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (type != &PyFloat_Type)
1526 return float_subtype_new(type, args, kwds); /* Wimp out */
1527 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1528 return NULL;
1529 /* If it's a string, but not a string subclass, use
1530 PyFloat_FromString. */
1531 if (PyUnicode_CheckExact(x))
1532 return PyFloat_FromString(x);
1533 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534}
1535
Guido van Rossumbef14172001-08-29 15:47:46 +00001536/* Wimpy, slow approach to tp_new calls for subtypes of float:
1537 first create a regular float from whatever arguments we got,
1538 then allocate a subtype instance and initialize its ob_fval
1539 from the regular float. The regular float is then thrown away.
1540*/
1541static PyObject *
1542float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 assert(PyType_IsSubtype(type, &PyFloat_Type));
1547 tmp = float_new(&PyFloat_Type, args, kwds);
1548 if (tmp == NULL)
1549 return NULL;
1550 assert(PyFloat_CheckExact(tmp));
1551 newobj = type->tp_alloc(type, 0);
1552 if (newobj == NULL) {
1553 Py_DECREF(tmp);
1554 return NULL;
1555 }
1556 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1557 Py_DECREF(tmp);
1558 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001559}
1560
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001561static PyObject *
1562float_getnewargs(PyFloatObject *v)
1563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001565}
1566
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001567/* this is for the benefit of the pack/unpack routines below */
1568
1569typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001571} float_format_type;
1572
1573static float_format_type double_format, float_format;
1574static float_format_type detected_double_format, detected_float_format;
1575
1576static PyObject *
1577float_getformat(PyTypeObject *v, PyObject* arg)
1578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 char* s;
1580 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (!PyUnicode_Check(arg)) {
1583 PyErr_Format(PyExc_TypeError,
1584 "__getformat__() argument must be string, not %.500s",
1585 Py_TYPE(arg)->tp_name);
1586 return NULL;
1587 }
1588 s = _PyUnicode_AsString(arg);
1589 if (s == NULL)
1590 return NULL;
1591 if (strcmp(s, "double") == 0) {
1592 r = double_format;
1593 }
1594 else if (strcmp(s, "float") == 0) {
1595 r = float_format;
1596 }
1597 else {
1598 PyErr_SetString(PyExc_ValueError,
1599 "__getformat__() argument 1 must be "
1600 "'double' or 'float'");
1601 return NULL;
1602 }
1603
1604 switch (r) {
1605 case unknown_format:
1606 return PyUnicode_FromString("unknown");
1607 case ieee_little_endian_format:
1608 return PyUnicode_FromString("IEEE, little-endian");
1609 case ieee_big_endian_format:
1610 return PyUnicode_FromString("IEEE, big-endian");
1611 default:
1612 Py_FatalError("insane float_format or double_format");
1613 return NULL;
1614 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001615}
1616
1617PyDoc_STRVAR(float_getformat_doc,
1618"float.__getformat__(typestr) -> string\n"
1619"\n"
1620"You probably don't want to use this function. It exists mainly to be\n"
1621"used in Python's test suite.\n"
1622"\n"
1623"typestr must be 'double' or 'float'. This function returns whichever of\n"
1624"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1625"format of floating point numbers used by the C type named by typestr.");
1626
1627static PyObject *
1628float_setformat(PyTypeObject *v, PyObject* args)
1629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 char* typestr;
1631 char* format;
1632 float_format_type f;
1633 float_format_type detected;
1634 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1637 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (strcmp(typestr, "double") == 0) {
1640 p = &double_format;
1641 detected = detected_double_format;
1642 }
1643 else if (strcmp(typestr, "float") == 0) {
1644 p = &float_format;
1645 detected = detected_float_format;
1646 }
1647 else {
1648 PyErr_SetString(PyExc_ValueError,
1649 "__setformat__() argument 1 must "
1650 "be 'double' or 'float'");
1651 return NULL;
1652 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (strcmp(format, "unknown") == 0) {
1655 f = unknown_format;
1656 }
1657 else if (strcmp(format, "IEEE, little-endian") == 0) {
1658 f = ieee_little_endian_format;
1659 }
1660 else if (strcmp(format, "IEEE, big-endian") == 0) {
1661 f = ieee_big_endian_format;
1662 }
1663 else {
1664 PyErr_SetString(PyExc_ValueError,
1665 "__setformat__() argument 2 must be "
1666 "'unknown', 'IEEE, little-endian' or "
1667 "'IEEE, big-endian'");
1668 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (f != unknown_format && f != detected) {
1673 PyErr_Format(PyExc_ValueError,
1674 "can only set %s format to 'unknown' or the "
1675 "detected platform value", typestr);
1676 return NULL;
1677 }
1678
1679 *p = f;
1680 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001681}
1682
1683PyDoc_STRVAR(float_setformat_doc,
1684"float.__setformat__(typestr, fmt) -> None\n"
1685"\n"
1686"You probably don't want to use this function. It exists mainly to be\n"
1687"used in Python's test suite.\n"
1688"\n"
1689"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1690"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1691"one of the latter two if it appears to match the underlying C reality.\n"
1692"\n"
1693"Overrides the automatic determination of C-level floating point type.\n"
1694"This affects how floats are converted to and from binary strings.");
1695
Guido van Rossumb43daf72007-08-01 18:08:08 +00001696static PyObject *
1697float_getzero(PyObject *v, void *closure)
1698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001700}
1701
Eric Smith8c663262007-08-25 02:26:07 +00001702static PyObject *
1703float__format__(PyObject *self, PyObject *args)
1704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1708 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 return _PyFloat_FormatAdvanced(self, format_spec, 0,
1710 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00001711}
1712
1713PyDoc_STRVAR(float__format__doc,
1714"float.__format__(format_spec) -> string\n"
1715"\n"
1716"Formats the float according to format_spec.");
1717
1718
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001719static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1721 "Returns self, the complex conjugate of any float."},
1722 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1723 "Returns the Integral closest to x between 0 and x."},
1724 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1725 "Returns the Integral closest to x, rounding half toward even.\n"
1726 "When an argument is passed, works like built-in round(x, ndigits)."},
1727 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1728 float_as_integer_ratio_doc},
1729 {"fromhex", (PyCFunction)float_fromhex,
1730 METH_O|METH_CLASS, float_fromhex_doc},
1731 {"hex", (PyCFunction)float_hex,
1732 METH_NOARGS, float_hex_doc},
1733 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1734 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001735#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1737 "Returns True if the float is positive or negative infinite."},
1738 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1739 "Returns True if the float is finite, neither infinite nor NaN."},
1740 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1741 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001742#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1744 {"__getformat__", (PyCFunction)float_getformat,
1745 METH_O|METH_CLASS, float_getformat_doc},
1746 {"__setformat__", (PyCFunction)float_setformat,
1747 METH_VARARGS|METH_CLASS, float_setformat_doc},
1748 {"__format__", (PyCFunction)float__format__,
1749 METH_VARARGS, float__format__doc},
1750 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001751};
1752
Guido van Rossumb43daf72007-08-01 18:08:08 +00001753static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001755 (getter)float_float, (setter)NULL,
1756 "the real part of a complex number",
1757 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001759 (getter)float_getzero, (setter)NULL,
1760 "the imaginary part of a complex number",
1761 NULL},
1762 {NULL} /* Sentinel */
1763};
1764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001765PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766"float(x) -> floating point number\n\
1767\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001768Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769
1770
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 float_add, /*nb_add*/
1773 float_sub, /*nb_subtract*/
1774 float_mul, /*nb_multiply*/
1775 float_rem, /*nb_remainder*/
1776 float_divmod, /*nb_divmod*/
1777 float_pow, /*nb_power*/
1778 (unaryfunc)float_neg, /*nb_negative*/
1779 (unaryfunc)float_float, /*nb_positive*/
1780 (unaryfunc)float_abs, /*nb_absolute*/
1781 (inquiry)float_bool, /*nb_bool*/
1782 0, /*nb_invert*/
1783 0, /*nb_lshift*/
1784 0, /*nb_rshift*/
1785 0, /*nb_and*/
1786 0, /*nb_xor*/
1787 0, /*nb_or*/
1788 float_trunc, /*nb_int*/
1789 0, /*nb_reserved*/
1790 float_float, /*nb_float*/
1791 0, /* nb_inplace_add */
1792 0, /* nb_inplace_subtract */
1793 0, /* nb_inplace_multiply */
1794 0, /* nb_inplace_remainder */
1795 0, /* nb_inplace_power */
1796 0, /* nb_inplace_lshift */
1797 0, /* nb_inplace_rshift */
1798 0, /* nb_inplace_and */
1799 0, /* nb_inplace_xor */
1800 0, /* nb_inplace_or */
1801 float_floor_div, /* nb_floor_divide */
1802 float_div, /* nb_true_divide */
1803 0, /* nb_inplace_floor_divide */
1804 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001805};
1806
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001807PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1809 "float",
1810 sizeof(PyFloatObject),
1811 0,
1812 (destructor)float_dealloc, /* tp_dealloc */
1813 0, /* tp_print */
1814 0, /* tp_getattr */
1815 0, /* tp_setattr */
1816 0, /* tp_reserved */
1817 (reprfunc)float_repr, /* tp_repr */
1818 &float_as_number, /* tp_as_number */
1819 0, /* tp_as_sequence */
1820 0, /* tp_as_mapping */
1821 (hashfunc)float_hash, /* tp_hash */
1822 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001823 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyObject_GenericGetAttr, /* tp_getattro */
1825 0, /* tp_setattro */
1826 0, /* tp_as_buffer */
1827 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1828 float_doc, /* tp_doc */
1829 0, /* tp_traverse */
1830 0, /* tp_clear */
1831 float_richcompare, /* tp_richcompare */
1832 0, /* tp_weaklistoffset */
1833 0, /* tp_iter */
1834 0, /* tp_iternext */
1835 float_methods, /* tp_methods */
1836 0, /* tp_members */
1837 float_getset, /* tp_getset */
1838 0, /* tp_base */
1839 0, /* tp_dict */
1840 0, /* tp_descr_get */
1841 0, /* tp_descr_set */
1842 0, /* tp_dictoffset */
1843 0, /* tp_init */
1844 0, /* tp_alloc */
1845 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001847
1848void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001849_PyFloat_Init(void)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 /* We attempt to determine if this machine is using IEEE
1852 floating point formats by peering at the bits of some
1853 carefully chosen values. If it looks like we are on an
1854 IEEE platform, the float packing/unpacking routines can
1855 just copy bits, if not they resort to arithmetic & shifts
1856 and masks. The shifts & masks approach works on all finite
1857 values, but what happens to infinities, NaNs and signed
1858 zeroes on packing is an accident, and attempting to unpack
1859 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 Note that if we're on some whacked-out platform which uses
1862 IEEE formats but isn't strictly little-endian or big-
1863 endian, we will fall back to the portable shifts & masks
1864 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001865
1866#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 {
1868 double x = 9006104071832581.0;
1869 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1870 detected_double_format = ieee_big_endian_format;
1871 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1872 detected_double_format = ieee_little_endian_format;
1873 else
1874 detected_double_format = unknown_format;
1875 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001876#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001878#endif
1879
1880#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 {
1882 float y = 16711938.0;
1883 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1884 detected_float_format = ieee_big_endian_format;
1885 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1886 detected_float_format = ieee_little_endian_format;
1887 else
1888 detected_float_format = unknown_format;
1889 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001890#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892#endif
1893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 double_format = detected_double_format;
1895 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 /* Init float info */
1898 if (FloatInfoType.tp_name == 0)
1899 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001900}
1901
Georg Brandl2ee470f2008-07-16 12:55:28 +00001902int
1903PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001904{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001905 PyFloatObject *f = free_list, *next;
1906 int i = numfree;
1907 while (f) {
1908 next = (PyFloatObject*) Py_TYPE(f);
1909 PyObject_FREE(f);
1910 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001912 free_list = NULL;
1913 numfree = 0;
1914 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001915}
1916
1917void
1918PyFloat_Fini(void)
1919{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001920 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001921}
Tim Peters9905b942003-03-20 20:53:32 +00001922
1923/*----------------------------------------------------------------------------
1924 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001925 */
1926int
1927_PyFloat_Pack4(double x, unsigned char *p, int le)
1928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (float_format == unknown_format) {
1930 unsigned char sign;
1931 int e;
1932 double f;
1933 unsigned int fbits;
1934 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (le) {
1937 p += 3;
1938 incr = -1;
1939 }
Tim Peters9905b942003-03-20 20:53:32 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (x < 0) {
1942 sign = 1;
1943 x = -x;
1944 }
1945 else
1946 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 /* Normalize f to be in the range [1.0, 2.0) */
1951 if (0.5 <= f && f < 1.0) {
1952 f *= 2.0;
1953 e--;
1954 }
1955 else if (f == 0.0)
1956 e = 0;
1957 else {
1958 PyErr_SetString(PyExc_SystemError,
1959 "frexp() result out of range");
1960 return -1;
1961 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (e >= 128)
1964 goto Overflow;
1965 else if (e < -126) {
1966 /* Gradual underflow */
1967 f = ldexp(f, 126 + e);
1968 e = 0;
1969 }
1970 else if (!(e == 0 && f == 0.0)) {
1971 e += 127;
1972 f -= 1.0; /* Get rid of leading 1 */
1973 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 f *= 8388608.0; /* 2**23 */
1976 fbits = (unsigned int)(f + 0.5); /* Round */
1977 assert(fbits <= 8388608);
1978 if (fbits >> 23) {
1979 /* The carry propagated out of a string of 23 1 bits. */
1980 fbits = 0;
1981 ++e;
1982 if (e >= 255)
1983 goto Overflow;
1984 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 /* First byte */
1987 *p = (sign << 7) | (e >> 1);
1988 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 /* Second byte */
1991 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1992 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* Third byte */
1995 *p = (fbits >> 8) & 0xFF;
1996 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* Fourth byte */
1999 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 /* Done */
2002 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 }
2005 else {
2006 float y = (float)x;
2007 const char *s = (char*)&y;
2008 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2011 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if ((float_format == ieee_little_endian_format && !le)
2014 || (float_format == ieee_big_endian_format && le)) {
2015 p += 3;
2016 incr = -1;
2017 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 for (i = 0; i < 4; i++) {
2020 *p = *s++;
2021 p += incr;
2022 }
2023 return 0;
2024 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002025 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyErr_SetString(PyExc_OverflowError,
2027 "float too large to pack with f format");
2028 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002029}
2030
2031int
2032_PyFloat_Pack8(double x, unsigned char *p, int le)
2033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (double_format == unknown_format) {
2035 unsigned char sign;
2036 int e;
2037 double f;
2038 unsigned int fhi, flo;
2039 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 if (le) {
2042 p += 7;
2043 incr = -1;
2044 }
Tim Peters9905b942003-03-20 20:53:32 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (x < 0) {
2047 sign = 1;
2048 x = -x;
2049 }
2050 else
2051 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 /* Normalize f to be in the range [1.0, 2.0) */
2056 if (0.5 <= f && f < 1.0) {
2057 f *= 2.0;
2058 e--;
2059 }
2060 else if (f == 0.0)
2061 e = 0;
2062 else {
2063 PyErr_SetString(PyExc_SystemError,
2064 "frexp() result out of range");
2065 return -1;
2066 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (e >= 1024)
2069 goto Overflow;
2070 else if (e < -1022) {
2071 /* Gradual underflow */
2072 f = ldexp(f, 1022 + e);
2073 e = 0;
2074 }
2075 else if (!(e == 0 && f == 0.0)) {
2076 e += 1023;
2077 f -= 1.0; /* Get rid of leading 1 */
2078 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2081 f *= 268435456.0; /* 2**28 */
2082 fhi = (unsigned int)f; /* Truncate */
2083 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 f -= (double)fhi;
2086 f *= 16777216.0; /* 2**24 */
2087 flo = (unsigned int)(f + 0.5); /* Round */
2088 assert(flo <= 16777216);
2089 if (flo >> 24) {
2090 /* The carry propagated out of a string of 24 1 bits. */
2091 flo = 0;
2092 ++fhi;
2093 if (fhi >> 28) {
2094 /* And it also progagated out of the next 28 bits. */
2095 fhi = 0;
2096 ++e;
2097 if (e >= 2047)
2098 goto Overflow;
2099 }
2100 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* First byte */
2103 *p = (sign << 7) | (e >> 4);
2104 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* Second byte */
2107 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2108 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* Third byte */
2111 *p = (fhi >> 16) & 0xFF;
2112 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Fourth byte */
2115 *p = (fhi >> 8) & 0xFF;
2116 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* Fifth byte */
2119 *p = fhi & 0xFF;
2120 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 /* Sixth byte */
2123 *p = (flo >> 16) & 0xFF;
2124 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 /* Seventh byte */
2127 *p = (flo >> 8) & 0xFF;
2128 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 /* Eighth byte */
2131 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002132 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 /* Done */
2135 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 Overflow:
2138 PyErr_SetString(PyExc_OverflowError,
2139 "float too large to pack with d format");
2140 return -1;
2141 }
2142 else {
2143 const char *s = (char*)&x;
2144 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if ((double_format == ieee_little_endian_format && !le)
2147 || (double_format == ieee_big_endian_format && le)) {
2148 p += 7;
2149 incr = -1;
2150 }
2151
2152 for (i = 0; i < 8; i++) {
2153 *p = *s++;
2154 p += incr;
2155 }
2156 return 0;
2157 }
Tim Peters9905b942003-03-20 20:53:32 +00002158}
2159
2160double
2161_PyFloat_Unpack4(const unsigned char *p, int le)
2162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (float_format == unknown_format) {
2164 unsigned char sign;
2165 int e;
2166 unsigned int f;
2167 double x;
2168 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (le) {
2171 p += 3;
2172 incr = -1;
2173 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* First byte */
2176 sign = (*p >> 7) & 1;
2177 e = (*p & 0x7F) << 1;
2178 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* Second byte */
2181 e |= (*p >> 7) & 1;
2182 f = (*p & 0x7F) << 16;
2183 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (e == 255) {
2186 PyErr_SetString(
2187 PyExc_ValueError,
2188 "can't unpack IEEE 754 special value "
2189 "on non-IEEE platform");
2190 return -1;
2191 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 /* Third byte */
2194 f |= *p << 8;
2195 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* Fourth byte */
2198 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* XXX This sadly ignores Inf/NaN issues */
2203 if (e == 0)
2204 e = -126;
2205 else {
2206 x += 1.0;
2207 e -= 127;
2208 }
2209 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (sign)
2212 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 return x;
2215 }
2216 else {
2217 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if ((float_format == ieee_little_endian_format && !le)
2220 || (float_format == ieee_big_endian_format && le)) {
2221 char buf[4];
2222 char *d = &buf[3];
2223 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 for (i = 0; i < 4; i++) {
2226 *d-- = *p++;
2227 }
2228 memcpy(&x, buf, 4);
2229 }
2230 else {
2231 memcpy(&x, p, 4);
2232 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 return x;
2235 }
Tim Peters9905b942003-03-20 20:53:32 +00002236}
2237
2238double
2239_PyFloat_Unpack8(const unsigned char *p, int le)
2240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (double_format == unknown_format) {
2242 unsigned char sign;
2243 int e;
2244 unsigned int fhi, flo;
2245 double x;
2246 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (le) {
2249 p += 7;
2250 incr = -1;
2251 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 /* First byte */
2254 sign = (*p >> 7) & 1;
2255 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* Second byte */
2260 e |= (*p >> 4) & 0xF;
2261 fhi = (*p & 0xF) << 24;
2262 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (e == 2047) {
2265 PyErr_SetString(
2266 PyExc_ValueError,
2267 "can't unpack IEEE 754 special value "
2268 "on non-IEEE platform");
2269 return -1.0;
2270 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 /* Third byte */
2273 fhi |= *p << 16;
2274 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 /* Fourth byte */
2277 fhi |= *p << 8;
2278 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* Fifth byte */
2281 fhi |= *p;
2282 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Sixth byte */
2285 flo = *p << 16;
2286 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* Seventh byte */
2289 flo |= *p << 8;
2290 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 /* Eighth byte */
2293 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2296 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 if (e == 0)
2299 e = -1022;
2300 else {
2301 x += 1.0;
2302 e -= 1023;
2303 }
2304 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 if (sign)
2307 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 return x;
2310 }
2311 else {
2312 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 if ((double_format == ieee_little_endian_format && !le)
2315 || (double_format == ieee_big_endian_format && le)) {
2316 char buf[8];
2317 char *d = &buf[7];
2318 int i;
2319
2320 for (i = 0; i < 8; i++) {
2321 *d-- = *p++;
2322 }
2323 memcpy(&x, buf, 8);
2324 }
2325 else {
2326 memcpy(&x, p, 8);
2327 }
2328
2329 return x;
2330 }
Tim Peters9905b942003-03-20 20:53:32 +00002331}