blob: 7ee2034f89e3627cb1f659480fae200c9dd40583 [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
Guido van Rossum6923e131990-11-02 17:50:43 +000012
Mark Dickinsond19052c2010-06-27 18:19:09 +000013/* Special free list
Mark Dickinsond19052c2010-06-27 18:19:09 +000014 free_list is a singly-linked list of available PyFloatObjects, linked
15 via abuse of their ob_type members.
16*/
17
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +000018#ifndef PyFloat_MAXFREELIST
19#define PyFloat_MAXFREELIST 100
20#endif
21static int numfree = 0;
Guido van Rossum3fce8831999-03-12 19:43:17 +000022static PyFloatObject *free_list = NULL;
23
Christian Heimes93852662007-12-01 12:22:32 +000024double
25PyFloat_GetMax(void)
26{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 return DBL_MAX;
Christian Heimes93852662007-12-01 12:22:32 +000028}
29
30double
31PyFloat_GetMin(void)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return DBL_MIN;
Christian Heimes93852662007-12-01 12:22:32 +000034}
35
Christian Heimesd32ed6f2008-01-14 18:49:24 +000036static PyTypeObject FloatInfoType;
37
38PyDoc_STRVAR(floatinfo__doc__,
Benjamin Peterson78565b22009-06-28 19:19:51 +000039"sys.float_info\n\
Christian Heimesd32ed6f2008-01-14 18:49:24 +000040\n\
41A structseq holding information about the float type. It contains low level\n\
42information about the precision and internal representation. Please study\n\
43your system's :file:`float.h` for more information.");
44
45static PyStructSequence_Field floatinfo_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 {"max", "DBL_MAX -- maximum representable finite float"},
47 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
48 "is representable"},
49 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
50 "is representable"},
51 {"min", "DBL_MIN -- Minimum positive normalizer float"},
52 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
53 "is a normalized float"},
54 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
55 "a normalized"},
56 {"dig", "DBL_DIG -- digits"},
57 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
58 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
59 "representable float"},
60 {"radix", "FLT_RADIX -- radix of exponent"},
61 {"rounds", "FLT_ROUNDS -- addition rounds"},
62 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +000063};
64
65static PyStructSequence_Desc floatinfo_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 "sys.float_info", /* name */
67 floatinfo__doc__, /* doc */
68 floatinfo_fields, /* fields */
69 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +000070};
71
Christian Heimes93852662007-12-01 12:22:32 +000072PyObject *
73PyFloat_GetInfo(void)
74{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject* floatinfo;
76 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 floatinfo = PyStructSequence_New(&FloatInfoType);
79 if (floatinfo == NULL) {
80 return NULL;
81 }
Christian Heimes93852662007-12-01 12:22:32 +000082
Christian Heimesd32ed6f2008-01-14 18:49:24 +000083#define SetIntFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +000085#define SetDblFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 SetDblFlag(DBL_MAX);
89 SetIntFlag(DBL_MAX_EXP);
90 SetIntFlag(DBL_MAX_10_EXP);
91 SetDblFlag(DBL_MIN);
92 SetIntFlag(DBL_MIN_EXP);
93 SetIntFlag(DBL_MIN_10_EXP);
94 SetIntFlag(DBL_DIG);
95 SetIntFlag(DBL_MANT_DIG);
96 SetDblFlag(DBL_EPSILON);
97 SetIntFlag(FLT_RADIX);
98 SetIntFlag(FLT_ROUNDS);
Christian Heimesd32ed6f2008-01-14 18:49:24 +000099#undef SetIntFlag
100#undef SetDblFlag
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101
102 if (PyErr_Occurred()) {
103 Py_CLEAR(floatinfo);
104 return NULL;
105 }
106 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000107}
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000112 register PyFloatObject *op = free_list;
113 if (op != NULL) {
114 free_list = (PyFloatObject *) Py_TYPE(op);
115 numfree--;
116 } else {
117 op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject));
118 if (!op)
119 return PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
121 /* Inline PyObject_New */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject_INIT(op, &PyFloat_Type);
123 op->ob_fval = fval;
124 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125}
126
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000127PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000128PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 const char *s, *last, *end;
131 double x;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000132 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_ssize_t len;
134 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200137 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000139 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200140 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000141 if (s == NULL) {
142 Py_DECREF(s_buffer);
143 return NULL;
144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 }
146 else if (PyObject_AsCharBuffer(v, &s, &len)) {
147 PyErr_SetString(PyExc_TypeError,
148 "float() argument must be a string or a number");
149 return NULL;
150 }
151 last = s + len;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000152 /* strip space */
153 while (s < last && Py_ISSPACE(*s))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 s++;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000155 while (s < last - 1 && Py_ISSPACE(last[-1]))
156 last--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 /* We don't care about overflow or underflow. If the platform
158 * supports them, infinities and signed zeroes (on underflow) are
159 * fine. */
160 x = PyOS_string_to_double(s, (char **)&end, NULL);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000161 if (end != last) {
162 PyErr_Format(PyExc_ValueError,
163 "could not convert string to float: "
164 "%R", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 result = NULL;
166 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000167 else if (x == -1.0 && PyErr_Occurred())
168 result = NULL;
169 else
170 result = PyFloat_FromDouble(x);
Mark Dickinson725bfd82009-05-03 20:33:40 +0000171
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000172 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000174}
175
Guido van Rossum234f9421993-06-17 12:35:49 +0000176static void
Fred Drakefd99de62000-07-09 05:02:18 +0000177float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (PyFloat_CheckExact(op)) {
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +0000180 if (numfree >= PyFloat_MAXFREELIST) {
181 PyObject_FREE(op);
182 return;
183 }
184 numfree++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_TYPE(op) = (struct _typeobject *)free_list;
186 free_list = op;
187 }
188 else
189 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000190}
191
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192double
Fred Drakefd99de62000-07-09 05:02:18 +0000193PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyNumberMethods *nb;
196 PyFloatObject *fo;
197 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 if (op && PyFloat_Check(op))
200 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if (op == NULL) {
203 PyErr_BadArgument();
204 return -1;
205 }
Tim Petersd2364e82001-11-01 20:09:42 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
208 PyErr_SetString(PyExc_TypeError, "a float is required");
209 return -1;
210 }
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 fo = (PyFloatObject*) (*nb->nb_float) (op);
213 if (fo == NULL)
214 return -1;
215 if (!PyFloat_Check(fo)) {
216 PyErr_SetString(PyExc_TypeError,
217 "nb_float should return float object");
218 return -1;
219 }
Tim Petersd2364e82001-11-01 20:09:42 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 val = PyFloat_AS_DOUBLE(fo);
222 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225}
226
Neil Schemenauer32117e52001-01-04 01:44:34 +0000227/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000228 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000229 set to NULL, and the function invoking this macro returns NULL. If
230 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
231 stored in obj, and returned from the function invoking this macro.
232*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233#define CONVERT_TO_DOUBLE(obj, dbl) \
234 if (PyFloat_Check(obj)) \
235 dbl = PyFloat_AS_DOUBLE(obj); \
236 else if (convert_to_double(&(obj), &(dbl)) < 0) \
237 return obj;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000238
Eric Smith0923d1d2009-04-16 20:16:10 +0000239/* Methods */
240
Neil Schemenauer32117e52001-01-04 01:44:34 +0000241static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000242convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (PyLong_Check(obj)) {
247 *dbl = PyLong_AsDouble(obj);
248 if (*dbl == -1.0 && PyErr_Occurred()) {
249 *v = NULL;
250 return -1;
251 }
252 }
253 else {
254 Py_INCREF(Py_NotImplemented);
255 *v = Py_NotImplemented;
256 return -1;
257 }
258 return 0;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000259}
260
Eric Smith0923d1d2009-04-16 20:16:10 +0000261static PyObject *
Mark Dickinson388122d2010-08-04 20:56:28 +0000262float_repr(PyFloatObject *v)
Eric Smith0923d1d2009-04-16 20:16:10 +0000263{
264 PyObject *result;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200265 char *buf;
266
267 buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
268 'r', 0,
269 Py_DTSF_ADD_DOT_0,
270 NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +0000271 if (!buf)
Mark Dickinson388122d2010-08-04 20:56:28 +0000272 return PyErr_NoMemory();
Victor Stinnerd3f08822012-05-29 12:57:52 +0200273 result = _PyUnicode_FromASCII(buf, strlen(buf));
Eric Smith0923d1d2009-04-16 20:16:10 +0000274 PyMem_Free(buf);
275 return result;
276}
Guido van Rossum57072eb1999-12-23 19:00:28 +0000277
Tim Peters307fa782004-09-23 08:06:40 +0000278/* Comparison is pretty much a nightmare. When comparing float to float,
279 * we do it as straightforwardly (and long-windedly) as conceivable, so
280 * that, e.g., Python x == y delivers the same result as the platform
281 * C x == y when x and/or y is a NaN.
282 * When mixing float with an integer type, there's no good *uniform* approach.
283 * Converting the double to an integer obviously doesn't work, since we
284 * may lose info from fractional bits. Converting the integer to a double
285 * also has two failure modes: (1) a long int may trigger overflow (too
286 * large to fit in the dynamic range of a C double); (2) even a C long may have
Ezio Melotti3f5db392013-01-27 06:20:14 +0200287 * more bits than fit in a C double (e.g., on a 64-bit box long may have
Tim Peters307fa782004-09-23 08:06:40 +0000288 * 63 bits of precision, but a C double probably has only 53), and then
289 * we can falsely claim equality when low-order integer bits are lost by
290 * coercion to double. So this part is painful too.
291 */
292
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000293static PyObject*
294float_richcompare(PyObject *v, PyObject *w, int op)
295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 double i, j;
297 int r = 0;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 assert(PyFloat_Check(v));
300 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* Switch on the type of w. Set i and j to doubles to be compared,
303 * and op to the richcomp to use.
304 */
305 if (PyFloat_Check(w))
306 j = PyFloat_AS_DOUBLE(w);
Tim Peters307fa782004-09-23 08:06:40 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 else if (!Py_IS_FINITE(i)) {
309 if (PyLong_Check(w))
310 /* If i is an infinity, its magnitude exceeds any
311 * finite integer, so it doesn't matter which int we
312 * compare i with. If i is a NaN, similarly.
313 */
314 j = 0.0;
315 else
316 goto Unimplemented;
317 }
Tim Peters307fa782004-09-23 08:06:40 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 else if (PyLong_Check(w)) {
320 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
321 int wsign = _PyLong_Sign(w);
322 size_t nbits;
323 int exponent;
Tim Peters307fa782004-09-23 08:06:40 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (vsign != wsign) {
326 /* Magnitudes are irrelevant -- the signs alone
327 * determine the outcome.
328 */
329 i = (double)vsign;
330 j = (double)wsign;
331 goto Compare;
332 }
333 /* The signs are the same. */
334 /* Convert w to a double if it fits. In particular, 0 fits. */
335 nbits = _PyLong_NumBits(w);
336 if (nbits == (size_t)-1 && PyErr_Occurred()) {
337 /* This long is so large that size_t isn't big enough
338 * to hold the # of bits. Replace with little doubles
339 * that give the same outcome -- w is so large that
340 * its magnitude must exceed the magnitude of any
341 * finite float.
342 */
343 PyErr_Clear();
344 i = (double)vsign;
345 assert(wsign != 0);
346 j = wsign * 2.0;
347 goto Compare;
348 }
349 if (nbits <= 48) {
350 j = PyLong_AsDouble(w);
351 /* It's impossible that <= 48 bits overflowed. */
352 assert(j != -1.0 || ! PyErr_Occurred());
353 goto Compare;
354 }
355 assert(wsign != 0); /* else nbits was 0 */
356 assert(vsign != 0); /* if vsign were 0, then since wsign is
357 * not 0, we would have taken the
358 * vsign != wsign branch at the start */
359 /* We want to work with non-negative numbers. */
360 if (vsign < 0) {
361 /* "Multiply both sides" by -1; this also swaps the
362 * comparator.
363 */
364 i = -i;
365 op = _Py_SwappedOp[op];
366 }
367 assert(i > 0.0);
368 (void) frexp(i, &exponent);
369 /* exponent is the # of bits in v before the radix point;
370 * we know that nbits (the # of bits in w) > 48 at this point
371 */
372 if (exponent < 0 || (size_t)exponent < nbits) {
373 i = 1.0;
374 j = 2.0;
375 goto Compare;
376 }
377 if ((size_t)exponent > nbits) {
378 i = 2.0;
379 j = 1.0;
380 goto Compare;
381 }
382 /* v and w have the same number of bits before the radix
383 * point. Construct two longs that have the same comparison
384 * outcome.
385 */
386 {
387 double fracpart;
388 double intpart;
389 PyObject *result = NULL;
390 PyObject *one = NULL;
391 PyObject *vv = NULL;
392 PyObject *ww = w;
Tim Peters307fa782004-09-23 08:06:40 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (wsign < 0) {
395 ww = PyNumber_Negative(w);
396 if (ww == NULL)
397 goto Error;
398 }
399 else
400 Py_INCREF(ww);
Tim Peters307fa782004-09-23 08:06:40 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 fracpart = modf(i, &intpart);
403 vv = PyLong_FromDouble(intpart);
404 if (vv == NULL)
405 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (fracpart != 0.0) {
408 /* Shift left, and or a 1 bit into vv
409 * to represent the lost fraction.
410 */
411 PyObject *temp;
Tim Peters307fa782004-09-23 08:06:40 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 one = PyLong_FromLong(1);
414 if (one == NULL)
415 goto Error;
Tim Peters307fa782004-09-23 08:06:40 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 temp = PyNumber_Lshift(ww, one);
418 if (temp == NULL)
419 goto Error;
420 Py_DECREF(ww);
421 ww = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 temp = PyNumber_Lshift(vv, one);
424 if (temp == NULL)
425 goto Error;
426 Py_DECREF(vv);
427 vv = temp;
Tim Peters307fa782004-09-23 08:06:40 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 temp = PyNumber_Or(vv, one);
430 if (temp == NULL)
431 goto Error;
432 Py_DECREF(vv);
433 vv = temp;
434 }
Tim Peters307fa782004-09-23 08:06:40 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 r = PyObject_RichCompareBool(vv, ww, op);
437 if (r < 0)
438 goto Error;
439 result = PyBool_FromLong(r);
440 Error:
441 Py_XDECREF(vv);
442 Py_XDECREF(ww);
443 Py_XDECREF(one);
444 return result;
445 }
446 } /* else if (PyLong_Check(w)) */
Tim Peters307fa782004-09-23 08:06:40 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 else /* w isn't float, int, or long */
449 goto Unimplemented;
Tim Peters307fa782004-09-23 08:06:40 +0000450
451 Compare:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyFPE_START_PROTECT("richcompare", return NULL)
453 switch (op) {
454 case Py_EQ:
455 r = i == j;
456 break;
457 case Py_NE:
458 r = i != j;
459 break;
460 case Py_LE:
461 r = i <= j;
462 break;
463 case Py_GE:
464 r = i >= j;
465 break;
466 case Py_LT:
467 r = i < j;
468 break;
469 case Py_GT:
470 r = i > j;
471 break;
472 }
473 PyFPE_END_PROTECT(r)
474 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000475
476 Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500477 Py_RETURN_NOTIMPLEMENTED;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000478}
479
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000480static Py_hash_t
Fred Drakefd99de62000-07-09 05:02:18 +0000481float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000484}
485
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000487float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 double a,b;
490 CONVERT_TO_DOUBLE(v, a);
491 CONVERT_TO_DOUBLE(w, b);
492 PyFPE_START_PROTECT("add", return 0)
493 a = a + b;
494 PyFPE_END_PROTECT(a)
495 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496}
497
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000499float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 double a,b;
502 CONVERT_TO_DOUBLE(v, a);
503 CONVERT_TO_DOUBLE(w, b);
504 PyFPE_START_PROTECT("subtract", return 0)
505 a = a - b;
506 PyFPE_END_PROTECT(a)
507 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000508}
509
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000511float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 double a,b;
514 CONVERT_TO_DOUBLE(v, a);
515 CONVERT_TO_DOUBLE(w, b);
516 PyFPE_START_PROTECT("multiply", return 0)
517 a = a * b;
518 PyFPE_END_PROTECT(a)
519 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000520}
521
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000523float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 double a,b;
526 CONVERT_TO_DOUBLE(v, a);
527 CONVERT_TO_DOUBLE(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (b == 0.0) {
529 PyErr_SetString(PyExc_ZeroDivisionError,
530 "float division by zero");
531 return NULL;
532 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyFPE_START_PROTECT("divide", return 0)
534 a = a / b;
535 PyFPE_END_PROTECT(a)
536 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537}
538
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000540float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 double vx, wx;
543 double mod;
544 CONVERT_TO_DOUBLE(v, vx);
545 CONVERT_TO_DOUBLE(w, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (wx == 0.0) {
547 PyErr_SetString(PyExc_ZeroDivisionError,
548 "float modulo");
549 return NULL;
550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyFPE_START_PROTECT("modulo", return 0)
552 mod = fmod(vx, wx);
Mark Dickinsond2a9b202010-12-04 12:25:30 +0000553 if (mod) {
554 /* ensure the remainder has the same sign as the denominator */
555 if ((wx < 0) != (mod < 0)) {
556 mod += wx;
557 }
558 }
559 else {
560 /* the remainder is zero, and in the presence of signed zeroes
561 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000562 it has the same sign as the denominator. */
563 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
565 PyFPE_END_PROTECT(mod)
566 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000567}
568
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000570float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 double vx, wx;
573 double div, mod, floordiv;
574 CONVERT_TO_DOUBLE(v, vx);
575 CONVERT_TO_DOUBLE(w, wx);
576 if (wx == 0.0) {
577 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
578 return NULL;
579 }
580 PyFPE_START_PROTECT("divmod", return 0)
581 mod = fmod(vx, wx);
582 /* fmod is typically exact, so vx-mod is *mathematically* an
583 exact multiple of wx. But this is fp arithmetic, and fp
584 vx - mod is an approximation; the result is that div may
585 not be an exact integral value after the division, although
586 it will always be very close to one.
587 */
588 div = (vx - mod) / wx;
589 if (mod) {
590 /* ensure the remainder has the same sign as the denominator */
591 if ((wx < 0) != (mod < 0)) {
592 mod += wx;
593 div -= 1.0;
594 }
595 }
596 else {
597 /* the remainder is zero, and in the presence of signed zeroes
598 fmod returns different results across platforms; ensure
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000599 it has the same sign as the denominator. */
600 mod = copysign(0.0, wx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 }
602 /* snap quotient to nearest integral value */
603 if (div) {
604 floordiv = floor(div);
605 if (div - floordiv > 0.5)
606 floordiv += 1.0;
607 }
608 else {
609 /* div is zero - get the same sign as the true quotient */
Mark Dickinson7b1bee42010-12-04 13:14:29 +0000610 floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
612 PyFPE_END_PROTECT(floordiv)
613 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000614}
615
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000617float_floor_div(PyObject *v, PyObject *w)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyObject *t, *r;
Tim Peters63a35712001-12-11 19:57:24 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 t = float_divmod(v, w);
622 if (t == NULL || t == Py_NotImplemented)
623 return t;
624 assert(PyTuple_CheckExact(t));
625 r = PyTuple_GET_ITEM(t, 0);
626 Py_INCREF(r);
627 Py_DECREF(t);
628 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000629}
630
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000631/* determine whether x is an odd integer or not; assumes that
632 x is not an infinity or nan. */
633#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
634
Tim Peters63a35712001-12-11 19:57:24 +0000635static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000636float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 double iv, iw, ix;
639 int negate_result = 0;
Tim Peters32f453e2001-09-03 08:35:41 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if ((PyObject *)z != Py_None) {
642 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
643 "allowed unless all arguments are integers");
644 return NULL;
645 }
Tim Peters32f453e2001-09-03 08:35:41 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 CONVERT_TO_DOUBLE(v, iv);
648 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* Sort out special cases here instead of relying on pow() */
651 if (iw == 0) { /* v**0 is 1, even 0**0 */
652 return PyFloat_FromDouble(1.0);
653 }
654 if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
655 return PyFloat_FromDouble(iv);
656 }
657 if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
658 return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
659 }
660 if (Py_IS_INFINITY(iw)) {
661 /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
662 * abs(v) > 1 (including case where v infinite)
663 *
664 * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
665 * abs(v) > 1 (including case where v infinite)
666 */
667 iv = fabs(iv);
668 if (iv == 1.0)
669 return PyFloat_FromDouble(1.0);
670 else if ((iw > 0.0) == (iv > 1.0))
671 return PyFloat_FromDouble(fabs(iw)); /* return inf */
672 else
673 return PyFloat_FromDouble(0.0);
674 }
675 if (Py_IS_INFINITY(iv)) {
676 /* (+-inf)**w is: inf for w positive, 0 for w negative; in
677 * both cases, we need to add the appropriate sign if w is
678 * an odd integer.
679 */
680 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
681 if (iw > 0.0)
682 return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
683 else
684 return PyFloat_FromDouble(iw_is_odd ?
685 copysign(0.0, iv) : 0.0);
686 }
687 if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
688 (already dealt with above), and an error
689 if w is negative. */
690 int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
691 if (iw < 0.0) {
692 PyErr_SetString(PyExc_ZeroDivisionError,
693 "0.0 cannot be raised to a "
694 "negative power");
695 return NULL;
696 }
697 /* use correct sign if iw is odd */
698 return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
699 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (iv < 0.0) {
702 /* Whether this is an error is a mess, and bumps into libm
703 * bugs so we have to figure it out ourselves.
704 */
705 if (iw != floor(iw)) {
706 /* Negative numbers raised to fractional powers
707 * become complex.
708 */
709 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
710 }
711 /* iw is an exact integer, albeit perhaps a very large
712 * one. Replace iv by its absolute value and remember
713 * to negate the pow result if iw is odd.
714 */
715 iv = -iv;
716 negate_result = DOUBLE_IS_ODD_INTEGER(iw);
717 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
720 /* (-1) ** large_integer also ends up here. Here's an
721 * extract from the comments for the previous
722 * implementation explaining why this special case is
723 * necessary:
724 *
725 * -1 raised to an exact integer should never be exceptional.
726 * Alas, some libms (chiefly glibc as of early 2003) return
727 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
728 * happen to be representable in a *C* integer. That's a
729 * bug.
730 */
731 return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
732 }
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 /* Now iv and iw are finite, iw is nonzero, and iv is
735 * positive and not equal to 1.0. We finally allow
736 * the platform pow to step in and do the rest.
737 */
738 errno = 0;
739 PyFPE_START_PROTECT("pow", return NULL)
740 ix = pow(iv, iw);
741 PyFPE_END_PROTECT(ix)
742 Py_ADJUST_ERANGE1(ix);
743 if (negate_result)
744 ix = -ix;
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (errno != 0) {
747 /* We don't expect any errno value other than ERANGE, but
748 * the range of libm bugs appears unbounded.
749 */
750 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
751 PyExc_ValueError);
752 return NULL;
753 }
754 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755}
756
Mark Dickinson9ab44b52009-12-30 16:22:49 +0000757#undef DOUBLE_IS_ODD_INTEGER
758
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000759static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000760float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763}
764
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000766float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000769}
770
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000771static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000772float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 return v->ob_fval != 0.0;
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000775}
776
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000777static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000778float_is_integer(PyObject *v)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 double x = PyFloat_AsDouble(v);
781 PyObject *o;
782
783 if (x == -1.0 && PyErr_Occurred())
784 return NULL;
785 if (!Py_IS_FINITE(x))
786 Py_RETURN_FALSE;
787 errno = 0;
788 PyFPE_START_PROTECT("is_integer", return NULL)
789 o = (floor(x) == x) ? Py_True : Py_False;
790 PyFPE_END_PROTECT(x)
791 if (errno != 0) {
792 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
793 PyExc_ValueError);
794 return NULL;
795 }
796 Py_INCREF(o);
797 return o;
Christian Heimes53876d92008-04-19 00:31:39 +0000798}
799
800#if 0
801static PyObject *
802float_is_inf(PyObject *v)
803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 double x = PyFloat_AsDouble(v);
805 if (x == -1.0 && PyErr_Occurred())
806 return NULL;
807 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000808}
809
810static PyObject *
811float_is_nan(PyObject *v)
812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 double x = PyFloat_AsDouble(v);
814 if (x == -1.0 && PyErr_Occurred())
815 return NULL;
816 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000817}
818
819static PyObject *
820float_is_finite(PyObject *v)
821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 double x = PyFloat_AsDouble(v);
823 if (x == -1.0 && PyErr_Occurred())
824 return NULL;
825 return PyBool_FromLong((long)Py_IS_FINITE(x));
Christian Heimes53876d92008-04-19 00:31:39 +0000826}
827#endif
828
829static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000830float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 double x = PyFloat_AsDouble(v);
833 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 (void)modf(x, &wholepart);
836 /* Try to get out cheap if this fits in a Python int. The attempt
837 * to cast to long must be protected, as C doesn't define what
838 * happens if the double is too big to fit in a long. Some rare
839 * systems raise an exception then (RISCOS was mentioned as one,
840 * and someone using a non-default option on Sun also bumped into
841 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
842 * still be vulnerable: if a long has more bits of precision than
843 * a double, casting MIN/MAX to double may yield an approximation,
844 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
845 * yield true from the C expression wholepart<=LONG_MAX, despite
846 * that wholepart is actually greater than LONG_MAX.
847 */
848 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
849 const long aslong = (long)wholepart;
850 return PyLong_FromLong(aslong);
851 }
852 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000853}
854
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000855/* double_round: rounds a finite double to the closest multiple of
856 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
857 ndigits <= 323). Returns a Python float, or sets a Python error and
858 returns NULL on failure (OverflowError and memory errors are possible). */
859
860#ifndef PY_NO_SHORT_FLOAT_REPR
861/* version of double_round that uses the correctly-rounded string<->double
862 conversions from Python/dtoa.c */
863
864static PyObject *
865double_round(double x, int ndigits) {
866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 double rounded;
868 Py_ssize_t buflen, mybuflen=100;
869 char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
870 int decpt, sign;
871 PyObject *result = NULL;
Mark Dickinson261896b2012-01-27 21:16:01 +0000872 _Py_SET_53BIT_PRECISION_HEADER;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* round to a decimal string */
Mark Dickinson261896b2012-01-27 21:16:01 +0000875 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end);
Mark Dickinson261896b2012-01-27 21:16:01 +0000877 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (buf == NULL) {
879 PyErr_NoMemory();
880 return NULL;
881 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
884 buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
885 buflen = buf_end - buf;
886 if (buflen + 8 > mybuflen) {
887 mybuflen = buflen+8;
888 mybuf = (char *)PyMem_Malloc(mybuflen);
889 if (mybuf == NULL) {
890 PyErr_NoMemory();
891 goto exit;
892 }
893 }
894 /* copy buf to mybuf, adding exponent, sign and leading 0 */
895 PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
896 buf, decpt - (int)buflen);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* and convert the resulting string back to a double */
899 errno = 0;
Mark Dickinson261896b2012-01-27 21:16:01 +0000900 _Py_SET_53BIT_PRECISION_START;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 rounded = _Py_dg_strtod(mybuf, NULL);
Mark Dickinson261896b2012-01-27 21:16:01 +0000902 _Py_SET_53BIT_PRECISION_END;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (errno == ERANGE && fabs(rounded) >= 1.)
904 PyErr_SetString(PyExc_OverflowError,
905 "rounded value too large to represent");
906 else
907 result = PyFloat_FromDouble(rounded);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* done computing value; now clean up */
910 if (mybuf != shortbuf)
911 PyMem_Free(mybuf);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000912 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 _Py_dg_freedtoa(buf);
914 return result;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000915}
916
917#else /* PY_NO_SHORT_FLOAT_REPR */
918
919/* fallback version, to be used when correctly rounded binary<->decimal
920 conversions aren't available */
921
922static PyObject *
923double_round(double x, int ndigits) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 double pow1, pow2, y, z;
925 if (ndigits >= 0) {
926 if (ndigits > 22) {
927 /* pow1 and pow2 are each safe from overflow, but
928 pow1*pow2 ~= pow(10.0, ndigits) might overflow */
929 pow1 = pow(10.0, (double)(ndigits-22));
930 pow2 = 1e22;
931 }
932 else {
933 pow1 = pow(10.0, (double)ndigits);
934 pow2 = 1.0;
935 }
936 y = (x*pow1)*pow2;
937 /* if y overflows, then rounded value is exactly x */
938 if (!Py_IS_FINITE(y))
939 return PyFloat_FromDouble(x);
940 }
941 else {
942 pow1 = pow(10.0, (double)-ndigits);
943 pow2 = 1.0; /* unused; silences a gcc compiler warning */
944 y = x / pow1;
945 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 z = round(y);
948 if (fabs(y-z) == 0.5)
949 /* halfway between two integers; use round-half-even */
950 z = 2.0*round(y/2.0);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (ndigits >= 0)
953 z = (z / pow2) / pow1;
954 else
955 z *= pow1;
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* if computation resulted in overflow, raise OverflowError */
958 if (!Py_IS_FINITE(z)) {
959 PyErr_SetString(PyExc_OverflowError,
960 "overflow occurred during round");
961 return NULL;
962 }
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 return PyFloat_FromDouble(z);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000965}
966
967#endif /* PY_NO_SHORT_FLOAT_REPR */
968
969/* round a Python float v to the closest multiple of 10**-ndigits */
970
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000971static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000972float_round(PyObject *v, PyObject *args)
973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 double x, rounded;
975 PyObject *o_ndigits = NULL;
976 Py_ssize_t ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 x = PyFloat_AsDouble(v);
979 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
980 return NULL;
981 if (o_ndigits == NULL) {
982 /* single-argument round: round to nearest integer */
983 rounded = round(x);
984 if (fabs(x-rounded) == 0.5)
985 /* halfway case: round to even */
986 rounded = 2.0*round(x/2.0);
987 return PyLong_FromDouble(rounded);
988 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* interpret second argument as a Py_ssize_t; clips on overflow */
991 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
992 if (ndigits == -1 && PyErr_Occurred())
993 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* nans and infinities round to themselves */
996 if (!Py_IS_FINITE(x))
997 return PyFloat_FromDouble(x);
Mark Dickinsone6a076d2009-04-18 11:48:33 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
1000 always rounds to itself. For ndigits < NDIGITS_MIN, x always
1001 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001002#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
1003#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (ndigits > NDIGITS_MAX)
1005 /* return x */
1006 return PyFloat_FromDouble(x);
1007 else if (ndigits < NDIGITS_MIN)
1008 /* return 0.0, but with sign of x */
1009 return PyFloat_FromDouble(0.0*x);
1010 else
1011 /* finite x, and ndigits is not unreasonably large */
1012 return double_round(x, (int)ndigits);
Mark Dickinsone6a076d2009-04-18 11:48:33 +00001013#undef NDIGITS_MAX
1014#undef NDIGITS_MIN
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001015}
1016
1017static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001018float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (PyFloat_CheckExact(v))
1021 Py_INCREF(v);
1022 else
1023 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
1024 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001025}
1026
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001027/* turn ASCII hex characters into integer values and vice versa */
1028
1029static char
1030char_from_hex(int x)
1031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 assert(0 <= x && x < 16);
Victor Stinnerf5cff562011-10-14 02:13:11 +02001033 return Py_hexdigits[x];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001034}
1035
1036static int
1037hex_from_char(char c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 int x;
1039 switch(c) {
1040 case '0':
1041 x = 0;
1042 break;
1043 case '1':
1044 x = 1;
1045 break;
1046 case '2':
1047 x = 2;
1048 break;
1049 case '3':
1050 x = 3;
1051 break;
1052 case '4':
1053 x = 4;
1054 break;
1055 case '5':
1056 x = 5;
1057 break;
1058 case '6':
1059 x = 6;
1060 break;
1061 case '7':
1062 x = 7;
1063 break;
1064 case '8':
1065 x = 8;
1066 break;
1067 case '9':
1068 x = 9;
1069 break;
1070 case 'a':
1071 case 'A':
1072 x = 10;
1073 break;
1074 case 'b':
1075 case 'B':
1076 x = 11;
1077 break;
1078 case 'c':
1079 case 'C':
1080 x = 12;
1081 break;
1082 case 'd':
1083 case 'D':
1084 x = 13;
1085 break;
1086 case 'e':
1087 case 'E':
1088 x = 14;
1089 break;
1090 case 'f':
1091 case 'F':
1092 x = 15;
1093 break;
1094 default:
1095 x = -1;
1096 break;
1097 }
1098 return x;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001099}
1100
1101/* convert a float to a hexadecimal string */
1102
1103/* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer
1104 of the form 4k+1. */
1105#define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4
1106
1107static PyObject *
1108float_hex(PyObject *v)
1109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 double x, m;
1111 int e, shift, i, si, esign;
1112 /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
1113 trailing NUL byte. */
1114 char s[(TOHEX_NBITS-1)/4+3];
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 CONVERT_TO_DOUBLE(v, x);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
Mark Dickinson388122d2010-08-04 20:56:28 +00001119 return float_repr((PyFloatObject *)v);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (x == 0.0) {
Benjamin Peterson5d470832010-07-02 19:45:07 +00001122 if (copysign(1.0, x) == -1.0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 return PyUnicode_FromString("-0x0.0p+0");
1124 else
1125 return PyUnicode_FromString("0x0.0p+0");
1126 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 m = frexp(fabs(x), &e);
Victor Stinner640c35c2013-06-04 23:14:37 +02001129 shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 m = ldexp(m, shift);
1131 e -= shift;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 si = 0;
1134 s[si] = char_from_hex((int)m);
1135 si++;
1136 m -= (int)m;
1137 s[si] = '.';
1138 si++;
1139 for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
1140 m *= 16.0;
1141 s[si] = char_from_hex((int)m);
1142 si++;
1143 m -= (int)m;
1144 }
1145 s[si] = '\0';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (e < 0) {
1148 esign = (int)'-';
1149 e = -e;
1150 }
1151 else
1152 esign = (int)'+';
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (x < 0.0)
1155 return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e);
1156 else
1157 return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001158}
1159
1160PyDoc_STRVAR(float_hex_doc,
1161"float.hex() -> string\n\
1162\n\
1163Return a hexadecimal representation of a floating-point number.\n\
1164>>> (-0.1).hex()\n\
1165'-0x1.999999999999ap-4'\n\
1166>>> 3.14159.hex()\n\
1167'0x1.921f9f01b866ep+1'");
1168
1169/* Convert a hexadecimal string to a float. */
1170
1171static PyObject *
1172float_fromhex(PyObject *cls, PyObject *arg)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyObject *result_as_float, *result;
1175 double x;
1176 long exp, top_exp, lsb, key_digit;
1177 char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
1178 int half_eps, digit, round_up, negate=0;
1179 Py_ssize_t length, ndigits, fdigits, i;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 /*
1182 * For the sake of simplicity and correctness, we impose an artificial
1183 * limit on ndigits, the total number of hex digits in the coefficient
1184 * The limit is chosen to ensure that, writing exp for the exponent,
1185 *
1186 * (1) if exp > LONG_MAX/2 then the value of the hex string is
1187 * guaranteed to overflow (provided it's nonzero)
1188 *
1189 * (2) if exp < LONG_MIN/2 then the value of the hex string is
1190 * guaranteed to underflow to 0.
1191 *
1192 * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
1193 * overflow in the calculation of exp and top_exp below.
1194 *
1195 * More specifically, ndigits is assumed to satisfy the following
1196 * inequalities:
1197 *
1198 * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
1199 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
1200 *
1201 * If either of these inequalities is not satisfied, a ValueError is
1202 * raised. Otherwise, write x for the value of the hex string, and
1203 * assume x is nonzero. Then
1204 *
1205 * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
1206 *
1207 * Now if exp > LONG_MAX/2 then:
1208 *
1209 * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
1210 * = DBL_MAX_EXP
1211 *
1212 * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
1213 * double, so overflows. If exp < LONG_MIN/2, then
1214 *
1215 * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
1216 * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
1217 * = DBL_MIN_EXP - DBL_MANT_DIG - 1
1218 *
1219 * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
1220 * when converted to a C double.
1221 *
1222 * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
1223 * exp+4*ndigits and exp-4*ndigits are within the range of a long.
1224 */
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 s = _PyUnicode_AsStringAndSize(arg, &length);
1227 if (s == NULL)
1228 return NULL;
1229 s_end = s + length;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 /********************
1232 * Parse the string *
1233 ********************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* leading whitespace */
1236 while (Py_ISSPACE(*s))
1237 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /* infinities and nans */
1240 x = _Py_parse_inf_or_nan(s, &coeff_end);
1241 if (coeff_end != s) {
1242 s = coeff_end;
1243 goto finished;
1244 }
Mark Dickinsonbd16edd2009-05-20 22:05:25 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 /* optional sign */
1247 if (*s == '-') {
1248 s++;
1249 negate = 1;
1250 }
1251 else if (*s == '+')
1252 s++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 /* [0x] */
1255 s_store = s;
1256 if (*s == '0') {
1257 s++;
1258 if (*s == 'x' || *s == 'X')
1259 s++;
1260 else
1261 s = s_store;
1262 }
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 /* coefficient: <integer> [. <fraction>] */
1265 coeff_start = s;
1266 while (hex_from_char(*s) >= 0)
1267 s++;
1268 s_store = s;
1269 if (*s == '.') {
1270 s++;
1271 while (hex_from_char(*s) >= 0)
1272 s++;
1273 coeff_end = s-1;
1274 }
1275 else
1276 coeff_end = s;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* ndigits = total # of hex digits; fdigits = # after point */
1279 ndigits = coeff_end - coeff_start;
1280 fdigits = coeff_end - s_store;
1281 if (ndigits == 0)
1282 goto parse_error;
Victor Stinner640c35c2013-06-04 23:14:37 +02001283 if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
1284 LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 goto insane_length_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* [p <exponent>] */
1288 if (*s == 'p' || *s == 'P') {
1289 s++;
1290 exp_start = s;
1291 if (*s == '-' || *s == '+')
1292 s++;
1293 if (!('0' <= *s && *s <= '9'))
1294 goto parse_error;
1295 s++;
1296 while ('0' <= *s && *s <= '9')
1297 s++;
1298 exp = strtol(exp_start, NULL, 10);
1299 }
1300 else
1301 exp = 0;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001302
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001303/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
1305 coeff_end-(j) : \
1306 coeff_end-1-(j)))
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 /*******************************************
1309 * Compute rounded value of the hex string *
1310 *******************************************/
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 /* Discard leading zeros, and catch extreme overflow and underflow */
1313 while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
1314 ndigits--;
1315 if (ndigits == 0 || exp < LONG_MIN/2) {
1316 x = 0.0;
1317 goto finished;
1318 }
1319 if (exp > LONG_MAX/2)
1320 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 /* Adjust exponent for fractional part. */
1323 exp = exp - 4*((long)fdigits);
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* top_exp = 1 more than exponent of most sig. bit of coefficient */
1326 top_exp = exp + 4*((long)ndigits - 1);
1327 for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
1328 top_exp++;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* catch almost all nonextreme cases of overflow and underflow here */
1331 if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
1332 x = 0.0;
1333 goto finished;
1334 }
1335 if (top_exp > DBL_MAX_EXP)
1336 goto overflow_error;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* lsb = exponent of least significant bit of the *rounded* value.
1339 This is top_exp - DBL_MANT_DIG unless result is subnormal. */
Victor Stinner640c35c2013-06-04 23:14:37 +02001340 lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 x = 0.0;
1343 if (exp >= lsb) {
1344 /* no rounding required */
1345 for (i = ndigits-1; i >= 0; i--)
1346 x = 16.0*x + HEX_DIGIT(i);
1347 x = ldexp(x, (int)(exp));
1348 goto finished;
1349 }
1350 /* rounding required. key_digit is the index of the hex digit
1351 containing the first bit to be rounded away. */
1352 half_eps = 1 << (int)((lsb - exp - 1) % 4);
1353 key_digit = (lsb - exp - 1) / 4;
1354 for (i = ndigits-1; i > key_digit; i--)
1355 x = 16.0*x + HEX_DIGIT(i);
1356 digit = HEX_DIGIT(key_digit);
1357 x = 16.0*x + (double)(digit & (16-2*half_eps));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* round-half-even: round up if bit lsb-1 is 1 and at least one of
1360 bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
1361 if ((digit & half_eps) != 0) {
1362 round_up = 0;
1363 if ((digit & (3*half_eps-1)) != 0 ||
1364 (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1365 round_up = 1;
1366 else
1367 for (i = key_digit-1; i >= 0; i--)
1368 if (HEX_DIGIT(i) != 0) {
1369 round_up = 1;
1370 break;
1371 }
Mark Dickinson21a1f732010-07-06 15:11:44 +00001372 if (round_up) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 x += 2*half_eps;
1374 if (top_exp == DBL_MAX_EXP &&
1375 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
1376 /* overflow corner case: pre-rounded value <
1377 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
1378 goto overflow_error;
1379 }
1380 }
1381 x = ldexp(x, (int)(exp+4*key_digit));
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001382
1383 finished:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* optional trailing whitespace leading to the end of the string */
1385 while (Py_ISSPACE(*s))
1386 s++;
1387 if (s != s_end)
1388 goto parse_error;
1389 result_as_float = Py_BuildValue("(d)", negate ? -x : x);
1390 if (result_as_float == NULL)
1391 return NULL;
1392 result = PyObject_CallObject(cls, result_as_float);
1393 Py_DECREF(result_as_float);
1394 return result;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001395
1396 overflow_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyErr_SetString(PyExc_OverflowError,
1398 "hexadecimal value too large to represent as a float");
1399 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001400
1401 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 PyErr_SetString(PyExc_ValueError,
1403 "invalid hexadecimal floating-point string");
1404 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001405
1406 insane_length_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyErr_SetString(PyExc_ValueError,
1408 "hexadecimal string too long to convert");
1409 return NULL;
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001410}
1411
1412PyDoc_STRVAR(float_fromhex_doc,
1413"float.fromhex(string) -> float\n\
1414\n\
1415Create a floating-point number from a hexadecimal string.\n\
1416>>> float.fromhex('0x1.ffffp10')\n\
14172047.984375\n\
1418>>> float.fromhex('-0x1p-1074')\n\
1419-4.9406564584124654e-324");
1420
1421
Christian Heimes26855632008-01-27 23:50:43 +00001422static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001423float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 double self;
1426 double float_part;
1427 int exponent;
1428 int i;
Christian Heimes292d3512008-02-03 16:51:08 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyObject *prev;
1431 PyObject *py_exponent = NULL;
1432 PyObject *numerator = NULL;
1433 PyObject *denominator = NULL;
1434 PyObject *result_pair = NULL;
1435 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001436
1437#define INPLACE_UPDATE(obj, call) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 prev = obj; \
1439 obj = call; \
1440 Py_DECREF(prev); \
Christian Heimes26855632008-01-27 23:50:43 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 CONVERT_TO_DOUBLE(v, self);
Christian Heimes26855632008-01-27 23:50:43 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (Py_IS_INFINITY(self)) {
1445 PyErr_SetString(PyExc_OverflowError,
1446 "Cannot pass infinity to float.as_integer_ratio.");
1447 return NULL;
1448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (Py_IS_NAN(self)) {
1450 PyErr_SetString(PyExc_ValueError,
1451 "Cannot pass NaN to float.as_integer_ratio.");
1452 return NULL;
1453 }
Christian Heimes26855632008-01-27 23:50:43 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1456 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
1457 PyFPE_END_PROTECT(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1460 float_part *= 2.0;
1461 exponent--;
1462 }
1463 /* self == float_part * 2**exponent exactly and float_part is integral.
1464 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1465 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 numerator = PyLong_FromDouble(float_part);
1468 if (numerator == NULL) goto error;
Christian Heimes26855632008-01-27 23:50:43 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 /* fold in 2**exponent */
1471 denominator = PyLong_FromLong(1);
1472 py_exponent = PyLong_FromLong(labs((long)exponent));
1473 if (py_exponent == NULL) goto error;
1474 INPLACE_UPDATE(py_exponent,
1475 long_methods->nb_lshift(denominator, py_exponent));
1476 if (py_exponent == NULL) goto error;
1477 if (exponent > 0) {
1478 INPLACE_UPDATE(numerator,
1479 long_methods->nb_multiply(numerator, py_exponent));
1480 if (numerator == NULL) goto error;
1481 }
1482 else {
1483 Py_DECREF(denominator);
1484 denominator = py_exponent;
1485 py_exponent = NULL;
1486 }
1487
1488 result_pair = PyTuple_Pack(2, numerator, denominator);
Christian Heimes26855632008-01-27 23:50:43 +00001489
1490#undef INPLACE_UPDATE
1491error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_XDECREF(py_exponent);
1493 Py_XDECREF(denominator);
1494 Py_XDECREF(numerator);
1495 return result_pair;
Christian Heimes26855632008-01-27 23:50:43 +00001496}
1497
1498PyDoc_STRVAR(float_as_integer_ratio_doc,
1499"float.as_integer_ratio() -> (int, int)\n"
1500"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001501"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1502"float and with a positive denominator.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001503"Raises OverflowError on infinities and a ValueError on NaNs.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001504"\n"
1505">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001506"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001507">>> (0.0).as_integer_ratio()\n"
1508"(0, 1)\n"
1509">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001510"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001511
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001512
Jeremy Hylton938ace62002-07-17 16:30:39 +00001513static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001514float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1515
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516static PyObject *
1517float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyObject *x = Py_False; /* Integer zero */
1520 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (type != &PyFloat_Type)
1523 return float_subtype_new(type, args, kwds); /* Wimp out */
1524 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1525 return NULL;
1526 /* If it's a string, but not a string subclass, use
1527 PyFloat_FromString. */
1528 if (PyUnicode_CheckExact(x))
1529 return PyFloat_FromString(x);
1530 return PyNumber_Float(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531}
1532
Guido van Rossumbef14172001-08-29 15:47:46 +00001533/* Wimpy, slow approach to tp_new calls for subtypes of float:
1534 first create a regular float from whatever arguments we got,
1535 then allocate a subtype instance and initialize its ob_fval
1536 from the regular float. The regular float is then thrown away.
1537*/
1538static PyObject *
1539float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 assert(PyType_IsSubtype(type, &PyFloat_Type));
1544 tmp = float_new(&PyFloat_Type, args, kwds);
1545 if (tmp == NULL)
1546 return NULL;
1547 assert(PyFloat_CheckExact(tmp));
1548 newobj = type->tp_alloc(type, 0);
1549 if (newobj == NULL) {
1550 Py_DECREF(tmp);
1551 return NULL;
1552 }
1553 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
1554 Py_DECREF(tmp);
1555 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001556}
1557
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001558static PyObject *
1559float_getnewargs(PyFloatObject *v)
1560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 return Py_BuildValue("(d)", v->ob_fval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001562}
1563
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001564/* this is for the benefit of the pack/unpack routines below */
1565
1566typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 unknown_format, ieee_big_endian_format, ieee_little_endian_format
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001568} float_format_type;
1569
1570static float_format_type double_format, float_format;
1571static float_format_type detected_double_format, detected_float_format;
1572
1573static PyObject *
1574float_getformat(PyTypeObject *v, PyObject* arg)
1575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 char* s;
1577 float_format_type r;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (!PyUnicode_Check(arg)) {
1580 PyErr_Format(PyExc_TypeError,
1581 "__getformat__() argument must be string, not %.500s",
1582 Py_TYPE(arg)->tp_name);
1583 return NULL;
1584 }
1585 s = _PyUnicode_AsString(arg);
1586 if (s == NULL)
1587 return NULL;
1588 if (strcmp(s, "double") == 0) {
1589 r = double_format;
1590 }
1591 else if (strcmp(s, "float") == 0) {
1592 r = float_format;
1593 }
1594 else {
1595 PyErr_SetString(PyExc_ValueError,
1596 "__getformat__() argument 1 must be "
1597 "'double' or 'float'");
1598 return NULL;
1599 }
1600
1601 switch (r) {
1602 case unknown_format:
1603 return PyUnicode_FromString("unknown");
1604 case ieee_little_endian_format:
1605 return PyUnicode_FromString("IEEE, little-endian");
1606 case ieee_big_endian_format:
1607 return PyUnicode_FromString("IEEE, big-endian");
1608 default:
1609 Py_FatalError("insane float_format or double_format");
1610 return NULL;
1611 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001612}
1613
1614PyDoc_STRVAR(float_getformat_doc,
1615"float.__getformat__(typestr) -> string\n"
1616"\n"
1617"You probably don't want to use this function. It exists mainly to be\n"
1618"used in Python's test suite.\n"
1619"\n"
1620"typestr must be 'double' or 'float'. This function returns whichever of\n"
1621"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1622"format of floating point numbers used by the C type named by typestr.");
1623
1624static PyObject *
1625float_setformat(PyTypeObject *v, PyObject* args)
1626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 char* typestr;
1628 char* format;
1629 float_format_type f;
1630 float_format_type detected;
1631 float_format_type *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1634 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (strcmp(typestr, "double") == 0) {
1637 p = &double_format;
1638 detected = detected_double_format;
1639 }
1640 else if (strcmp(typestr, "float") == 0) {
1641 p = &float_format;
1642 detected = detected_float_format;
1643 }
1644 else {
1645 PyErr_SetString(PyExc_ValueError,
1646 "__setformat__() argument 1 must "
1647 "be 'double' or 'float'");
1648 return NULL;
1649 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 if (strcmp(format, "unknown") == 0) {
1652 f = unknown_format;
1653 }
1654 else if (strcmp(format, "IEEE, little-endian") == 0) {
1655 f = ieee_little_endian_format;
1656 }
1657 else if (strcmp(format, "IEEE, big-endian") == 0) {
1658 f = ieee_big_endian_format;
1659 }
1660 else {
1661 PyErr_SetString(PyExc_ValueError,
1662 "__setformat__() argument 2 must be "
1663 "'unknown', 'IEEE, little-endian' or "
1664 "'IEEE, big-endian'");
1665 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (f != unknown_format && f != detected) {
1670 PyErr_Format(PyExc_ValueError,
1671 "can only set %s format to 'unknown' or the "
1672 "detected platform value", typestr);
1673 return NULL;
1674 }
1675
1676 *p = f;
1677 Py_RETURN_NONE;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001678}
1679
1680PyDoc_STRVAR(float_setformat_doc,
1681"float.__setformat__(typestr, fmt) -> None\n"
1682"\n"
1683"You probably don't want to use this function. It exists mainly to be\n"
1684"used in Python's test suite.\n"
1685"\n"
1686"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1687"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1688"one of the latter two if it appears to match the underlying C reality.\n"
1689"\n"
1690"Overrides the automatic determination of C-level floating point type.\n"
1691"This affects how floats are converted to and from binary strings.");
1692
Guido van Rossumb43daf72007-08-01 18:08:08 +00001693static PyObject *
1694float_getzero(PyObject *v, void *closure)
1695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 return PyFloat_FromDouble(0.0);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001697}
1698
Eric Smith8c663262007-08-25 02:26:07 +00001699static PyObject *
1700float__format__(PyObject *self, PyObject *args)
1701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001703 _PyUnicodeWriter writer;
1704 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
1707 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708
Victor Stinner8f674cc2013-04-17 23:02:17 +02001709 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001710 ret = _PyFloat_FormatAdvancedWriter(
1711 &writer,
1712 self,
1713 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1714 if (ret == -1) {
1715 _PyUnicodeWriter_Dealloc(&writer);
1716 return NULL;
1717 }
1718 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00001719}
1720
1721PyDoc_STRVAR(float__format__doc,
1722"float.__format__(format_spec) -> string\n"
1723"\n"
1724"Formats the float according to format_spec.");
1725
1726
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001727static PyMethodDef float_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1729 "Returns self, the complex conjugate of any float."},
1730 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1731 "Returns the Integral closest to x between 0 and x."},
1732 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1733 "Returns the Integral closest to x, rounding half toward even.\n"
1734 "When an argument is passed, works like built-in round(x, ndigits)."},
1735 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1736 float_as_integer_ratio_doc},
1737 {"fromhex", (PyCFunction)float_fromhex,
1738 METH_O|METH_CLASS, float_fromhex_doc},
1739 {"hex", (PyCFunction)float_hex,
1740 METH_NOARGS, float_hex_doc},
1741 {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
1742 "Returns True if the float is an integer."},
Christian Heimes53876d92008-04-19 00:31:39 +00001743#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
1745 "Returns True if the float is positive or negative infinite."},
1746 {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
1747 "Returns True if the float is finite, neither infinite nor NaN."},
1748 {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
1749 "Returns True if the float is not a number (NaN)."},
Christian Heimes53876d92008-04-19 00:31:39 +00001750#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
1752 {"__getformat__", (PyCFunction)float_getformat,
1753 METH_O|METH_CLASS, float_getformat_doc},
1754 {"__setformat__", (PyCFunction)float_setformat,
1755 METH_VARARGS|METH_CLASS, float_setformat_doc},
1756 {"__format__", (PyCFunction)float__format__,
1757 METH_VARARGS, float__format__doc},
1758 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001759};
1760
Guido van Rossumb43daf72007-08-01 18:08:08 +00001761static PyGetSetDef float_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001763 (getter)float_float, (setter)NULL,
1764 "the real part of a complex number",
1765 NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 {"imag",
Guido van Rossumb43daf72007-08-01 18:08:08 +00001767 (getter)float_getzero, (setter)NULL,
1768 "the imaginary part of a complex number",
1769 NULL},
1770 {NULL} /* Sentinel */
1771};
1772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001773PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774"float(x) -> floating point number\n\
1775\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001776Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
1778
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001779static PyNumberMethods float_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 float_add, /*nb_add*/
1781 float_sub, /*nb_subtract*/
1782 float_mul, /*nb_multiply*/
1783 float_rem, /*nb_remainder*/
1784 float_divmod, /*nb_divmod*/
1785 float_pow, /*nb_power*/
1786 (unaryfunc)float_neg, /*nb_negative*/
1787 (unaryfunc)float_float, /*nb_positive*/
1788 (unaryfunc)float_abs, /*nb_absolute*/
1789 (inquiry)float_bool, /*nb_bool*/
1790 0, /*nb_invert*/
1791 0, /*nb_lshift*/
1792 0, /*nb_rshift*/
1793 0, /*nb_and*/
1794 0, /*nb_xor*/
1795 0, /*nb_or*/
1796 float_trunc, /*nb_int*/
1797 0, /*nb_reserved*/
1798 float_float, /*nb_float*/
1799 0, /* nb_inplace_add */
1800 0, /* nb_inplace_subtract */
1801 0, /* nb_inplace_multiply */
1802 0, /* nb_inplace_remainder */
1803 0, /* nb_inplace_power */
1804 0, /* nb_inplace_lshift */
1805 0, /* nb_inplace_rshift */
1806 0, /* nb_inplace_and */
1807 0, /* nb_inplace_xor */
1808 0, /* nb_inplace_or */
1809 float_floor_div, /* nb_floor_divide */
1810 float_div, /* nb_true_divide */
1811 0, /* nb_inplace_floor_divide */
1812 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001813};
1814
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001815PyTypeObject PyFloat_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1817 "float",
1818 sizeof(PyFloatObject),
1819 0,
1820 (destructor)float_dealloc, /* tp_dealloc */
1821 0, /* tp_print */
1822 0, /* tp_getattr */
1823 0, /* tp_setattr */
1824 0, /* tp_reserved */
1825 (reprfunc)float_repr, /* tp_repr */
1826 &float_as_number, /* tp_as_number */
1827 0, /* tp_as_sequence */
1828 0, /* tp_as_mapping */
1829 (hashfunc)float_hash, /* tp_hash */
1830 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001831 (reprfunc)float_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyObject_GenericGetAttr, /* tp_getattro */
1833 0, /* tp_setattro */
1834 0, /* tp_as_buffer */
1835 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1836 float_doc, /* tp_doc */
1837 0, /* tp_traverse */
1838 0, /* tp_clear */
1839 float_richcompare, /* tp_richcompare */
1840 0, /* tp_weaklistoffset */
1841 0, /* tp_iter */
1842 0, /* tp_iternext */
1843 float_methods, /* tp_methods */
1844 0, /* tp_members */
1845 float_getset, /* tp_getset */
1846 0, /* tp_base */
1847 0, /* tp_dict */
1848 0, /* tp_descr_get */
1849 0, /* tp_descr_set */
1850 0, /* tp_dictoffset */
1851 0, /* tp_init */
1852 0, /* tp_alloc */
1853 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001855
Victor Stinner1c8f0592013-07-22 22:24:54 +02001856int
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001857_PyFloat_Init(void)
1858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* We attempt to determine if this machine is using IEEE
1860 floating point formats by peering at the bits of some
1861 carefully chosen values. If it looks like we are on an
1862 IEEE platform, the float packing/unpacking routines can
1863 just copy bits, if not they resort to arithmetic & shifts
1864 and masks. The shifts & masks approach works on all finite
1865 values, but what happens to infinities, NaNs and signed
1866 zeroes on packing is an accident, and attempting to unpack
1867 a NaN or an infinity will raise an exception.
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 Note that if we're on some whacked-out platform which uses
1870 IEEE formats but isn't strictly little-endian or big-
1871 endian, we will fall back to the portable shifts & masks
1872 method. */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001873
1874#if SIZEOF_DOUBLE == 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 {
1876 double x = 9006104071832581.0;
1877 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1878 detected_double_format = ieee_big_endian_format;
1879 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1880 detected_double_format = ieee_little_endian_format;
1881 else
1882 detected_double_format = unknown_format;
1883 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001884#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 detected_double_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001886#endif
1887
1888#if SIZEOF_FLOAT == 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 {
1890 float y = 16711938.0;
1891 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1892 detected_float_format = ieee_big_endian_format;
1893 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1894 detected_float_format = ieee_little_endian_format;
1895 else
1896 detected_float_format = unknown_format;
1897 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001898#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 detected_float_format = unknown_format;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001900#endif
1901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 double_format = detected_double_format;
1903 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Init float info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001906 if (FloatInfoType.tp_name == NULL) {
1907 if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0)
1908 return 0;
1909 }
1910 return 1;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001911}
1912
Georg Brandl2ee470f2008-07-16 12:55:28 +00001913int
1914PyFloat_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001915{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001916 PyFloatObject *f = free_list, *next;
1917 int i = numfree;
1918 while (f) {
1919 next = (PyFloatObject*) Py_TYPE(f);
1920 PyObject_FREE(f);
1921 f = next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001923 free_list = NULL;
1924 numfree = 0;
1925 return i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001926}
1927
1928void
1929PyFloat_Fini(void)
1930{
Kristján Valur Jónssondaa06542012-03-30 09:18:15 +00001931 (void)PyFloat_ClearFreeList();
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001932}
Tim Peters9905b942003-03-20 20:53:32 +00001933
David Malcolm49526f42012-06-22 14:55:41 -04001934/* Print summary info about the state of the optimized allocator */
1935void
1936_PyFloat_DebugMallocStats(FILE *out)
1937{
1938 _PyDebugAllocatorStats(out,
1939 "free PyFloatObject",
1940 numfree, sizeof(PyFloatObject));
1941}
1942
1943
Tim Peters9905b942003-03-20 20:53:32 +00001944/*----------------------------------------------------------------------------
1945 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001946 */
1947int
1948_PyFloat_Pack4(double x, unsigned char *p, int le)
1949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (float_format == unknown_format) {
1951 unsigned char sign;
1952 int e;
1953 double f;
1954 unsigned int fbits;
1955 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (le) {
1958 p += 3;
1959 incr = -1;
1960 }
Tim Peters9905b942003-03-20 20:53:32 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (x < 0) {
1963 sign = 1;
1964 x = -x;
1965 }
1966 else
1967 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* Normalize f to be in the range [1.0, 2.0) */
1972 if (0.5 <= f && f < 1.0) {
1973 f *= 2.0;
1974 e--;
1975 }
1976 else if (f == 0.0)
1977 e = 0;
1978 else {
1979 PyErr_SetString(PyExc_SystemError,
1980 "frexp() result out of range");
1981 return -1;
1982 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (e >= 128)
1985 goto Overflow;
1986 else if (e < -126) {
1987 /* Gradual underflow */
1988 f = ldexp(f, 126 + e);
1989 e = 0;
1990 }
1991 else if (!(e == 0 && f == 0.0)) {
1992 e += 127;
1993 f -= 1.0; /* Get rid of leading 1 */
1994 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 f *= 8388608.0; /* 2**23 */
1997 fbits = (unsigned int)(f + 0.5); /* Round */
1998 assert(fbits <= 8388608);
1999 if (fbits >> 23) {
2000 /* The carry propagated out of a string of 23 1 bits. */
2001 fbits = 0;
2002 ++e;
2003 if (e >= 255)
2004 goto Overflow;
2005 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 /* First byte */
2008 *p = (sign << 7) | (e >> 1);
2009 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 /* Second byte */
2012 *p = (char) (((e & 1) << 7) | (fbits >> 16));
2013 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Third byte */
2016 *p = (fbits >> 8) & 0xFF;
2017 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 /* Fourth byte */
2020 *p = fbits & 0xFF;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* Done */
2023 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 }
2026 else {
2027 float y = (float)x;
2028 const char *s = (char*)&y;
2029 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
2032 goto Overflow;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if ((float_format == ieee_little_endian_format && !le)
2035 || (float_format == ieee_big_endian_format && le)) {
2036 p += 3;
2037 incr = -1;
2038 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 for (i = 0; i < 4; i++) {
2041 *p = *s++;
2042 p += incr;
2043 }
2044 return 0;
2045 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002046 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 PyErr_SetString(PyExc_OverflowError,
2048 "float too large to pack with f format");
2049 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00002050}
2051
2052int
2053_PyFloat_Pack8(double x, unsigned char *p, int le)
2054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (double_format == unknown_format) {
2056 unsigned char sign;
2057 int e;
2058 double f;
2059 unsigned int fhi, flo;
2060 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (le) {
2063 p += 7;
2064 incr = -1;
2065 }
Tim Peters9905b942003-03-20 20:53:32 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (x < 0) {
2068 sign = 1;
2069 x = -x;
2070 }
2071 else
2072 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 /* Normalize f to be in the range [1.0, 2.0) */
2077 if (0.5 <= f && f < 1.0) {
2078 f *= 2.0;
2079 e--;
2080 }
2081 else if (f == 0.0)
2082 e = 0;
2083 else {
2084 PyErr_SetString(PyExc_SystemError,
2085 "frexp() result out of range");
2086 return -1;
2087 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (e >= 1024)
2090 goto Overflow;
2091 else if (e < -1022) {
2092 /* Gradual underflow */
2093 f = ldexp(f, 1022 + e);
2094 e = 0;
2095 }
2096 else if (!(e == 0 && f == 0.0)) {
2097 e += 1023;
2098 f -= 1.0; /* Get rid of leading 1 */
2099 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
2102 f *= 268435456.0; /* 2**28 */
2103 fhi = (unsigned int)f; /* Truncate */
2104 assert(fhi < 268435456);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 f -= (double)fhi;
2107 f *= 16777216.0; /* 2**24 */
2108 flo = (unsigned int)(f + 0.5); /* Round */
2109 assert(flo <= 16777216);
2110 if (flo >> 24) {
2111 /* The carry propagated out of a string of 24 1 bits. */
2112 flo = 0;
2113 ++fhi;
2114 if (fhi >> 28) {
2115 /* And it also progagated out of the next 28 bits. */
2116 fhi = 0;
2117 ++e;
2118 if (e >= 2047)
2119 goto Overflow;
2120 }
2121 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* First byte */
2124 *p = (sign << 7) | (e >> 4);
2125 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 /* Second byte */
2128 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
2129 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 /* Third byte */
2132 *p = (fhi >> 16) & 0xFF;
2133 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* Fourth byte */
2136 *p = (fhi >> 8) & 0xFF;
2137 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 /* Fifth byte */
2140 *p = fhi & 0xFF;
2141 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* Sixth byte */
2144 *p = (flo >> 16) & 0xFF;
2145 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 /* Seventh byte */
2148 *p = (flo >> 8) & 0xFF;
2149 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Eighth byte */
2152 *p = flo & 0xFF;
Brett Cannonb94767f2011-02-22 20:15:44 +00002153 /* p += incr; */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* Done */
2156 return 0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 Overflow:
2159 PyErr_SetString(PyExc_OverflowError,
2160 "float too large to pack with d format");
2161 return -1;
2162 }
2163 else {
2164 const char *s = (char*)&x;
2165 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if ((double_format == ieee_little_endian_format && !le)
2168 || (double_format == ieee_big_endian_format && le)) {
2169 p += 7;
2170 incr = -1;
2171 }
2172
2173 for (i = 0; i < 8; i++) {
2174 *p = *s++;
2175 p += incr;
2176 }
2177 return 0;
2178 }
Tim Peters9905b942003-03-20 20:53:32 +00002179}
2180
2181double
2182_PyFloat_Unpack4(const unsigned char *p, int le)
2183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (float_format == unknown_format) {
2185 unsigned char sign;
2186 int e;
2187 unsigned int f;
2188 double x;
2189 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (le) {
2192 p += 3;
2193 incr = -1;
2194 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* First byte */
2197 sign = (*p >> 7) & 1;
2198 e = (*p & 0x7F) << 1;
2199 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Second byte */
2202 e |= (*p >> 7) & 1;
2203 f = (*p & 0x7F) << 16;
2204 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (e == 255) {
2207 PyErr_SetString(
2208 PyExc_ValueError,
2209 "can't unpack IEEE 754 special value "
2210 "on non-IEEE platform");
2211 return -1;
2212 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* Third byte */
2215 f |= *p << 8;
2216 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Fourth byte */
2219 f |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 x = (double)f / 8388608.0;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* XXX This sadly ignores Inf/NaN issues */
2224 if (e == 0)
2225 e = -126;
2226 else {
2227 x += 1.0;
2228 e -= 127;
2229 }
2230 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (sign)
2233 x = -x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return x;
2236 }
2237 else {
2238 float x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 if ((float_format == ieee_little_endian_format && !le)
2241 || (float_format == ieee_big_endian_format && le)) {
2242 char buf[4];
2243 char *d = &buf[3];
2244 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 for (i = 0; i < 4; i++) {
2247 *d-- = *p++;
2248 }
2249 memcpy(&x, buf, 4);
2250 }
2251 else {
2252 memcpy(&x, p, 4);
2253 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 return x;
2256 }
Tim Peters9905b942003-03-20 20:53:32 +00002257}
2258
2259double
2260_PyFloat_Unpack8(const unsigned char *p, int le)
2261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if (double_format == unknown_format) {
2263 unsigned char sign;
2264 int e;
2265 unsigned int fhi, flo;
2266 double x;
2267 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (le) {
2270 p += 7;
2271 incr = -1;
2272 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* First byte */
2275 sign = (*p >> 7) & 1;
2276 e = (*p & 0x7F) << 4;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* Second byte */
2281 e |= (*p >> 4) & 0xF;
2282 fhi = (*p & 0xF) << 24;
2283 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (e == 2047) {
2286 PyErr_SetString(
2287 PyExc_ValueError,
2288 "can't unpack IEEE 754 special value "
2289 "on non-IEEE platform");
2290 return -1.0;
2291 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 /* Third byte */
2294 fhi |= *p << 16;
2295 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Fourth byte */
2298 fhi |= *p << 8;
2299 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Fifth byte */
2302 fhi |= *p;
2303 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Sixth byte */
2306 flo = *p << 16;
2307 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Seventh byte */
2310 flo |= *p << 8;
2311 p += incr;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Eighth byte */
2314 flo |= *p;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2317 x /= 268435456.0; /* 2**28 */
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 if (e == 0)
2320 e = -1022;
2321 else {
2322 x += 1.0;
2323 e -= 1023;
2324 }
2325 x = ldexp(x, e);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (sign)
2328 x = -x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return x;
2331 }
2332 else {
2333 double x;
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if ((double_format == ieee_little_endian_format && !le)
2336 || (double_format == ieee_big_endian_format && le)) {
2337 char buf[8];
2338 char *d = &buf[7];
2339 int i;
2340
2341 for (i = 0; i < 8; i++) {
2342 *d-- = *p++;
2343 }
2344 memcpy(&x, buf, 8);
2345 }
2346 else {
2347 memcpy(&x, p, 8);
2348 }
2349
2350 return x;
2351 }
Tim Peters9905b942003-03-20 20:53:32 +00002352}