blob: 689edcdb5ade3cc313610b1834e5c89393b9c9aa [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum3f5da241990-12-20 15:06:42 +000010#include <ctype.h>
Christian Heimesdfdfaab2007-12-01 11:20:10 +000011#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Christian Heimesc94e2b52008-01-14 04:13:37 +000013
Jack Janseneddc1442003-11-20 01:44:59 +000014#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000015extern double fmod(double, double);
16extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000017#endif
18
Neal Norwitz5f95a792008-01-25 08:04:16 +000019#ifdef _OSF_SOURCE
20/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
21extern int finite(double);
22#endif
23
Guido van Rossum93ad0df1997-05-13 21:00:42 +000024/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000025#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000026#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000027#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000028
Guido van Rossum3fce8831999-03-12 19:43:17 +000029struct _floatblock {
30 struct _floatblock *next;
31 PyFloatObject objects[N_FLOATOBJECTS];
32};
33
34typedef struct _floatblock PyFloatBlock;
35
36static PyFloatBlock *block_list = NULL;
37static PyFloatObject *free_list = NULL;
38
Guido van Rossum93ad0df1997-05-13 21:00:42 +000039static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000040fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000041{
42 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000043 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
44 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000045 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000046 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000047 ((PyFloatBlock *)p)->next = block_list;
48 block_list = (PyFloatBlock *)p;
49 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 q = p + N_FLOATOBJECTS;
51 while (--q > p)
Christian Heimese93237d2007-12-19 02:37:44 +000052 Py_TYPE(q) = (struct _typeobject *)(q-1);
53 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000054 return p + N_FLOATOBJECTS - 1;
55}
56
Christian Heimesdfdfaab2007-12-01 11:20:10 +000057double
58PyFloat_GetMax(void)
59{
60 return DBL_MAX;
61}
62
63double
64PyFloat_GetMin(void)
65{
66 return DBL_MIN;
67}
68
Christian Heimesc94e2b52008-01-14 04:13:37 +000069static PyTypeObject FloatInfoType = {0};
70
71PyDoc_STRVAR(floatinfo__doc__,
72"sys.floatinfo\n\
73\n\
74A structseq holding information about the float type. It contains low level\n\
75information about the precision and internal representation. Please study\n\
76your system's :file:`float.h` for more information.");
77
78static PyStructSequence_Field floatinfo_fields[] = {
79 {"max", "DBL_MAX -- maximum representable finite float"},
80 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
81 "is representable"},
82 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
83 "is representable"},
84 {"min", "DBL_MIN -- Minimum positive normalizer float"},
85 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
86 "is a normalized float"},
87 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
88 "a normalized"},
89 {"dig", "DBL_DIG -- digits"},
90 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
91 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
92 "representable float"},
93 {"radix", "FLT_RADIX -- radix of exponent"},
94 {"rounds", "FLT_ROUNDS -- addition rounds"},
95 {0}
96};
97
98static PyStructSequence_Desc floatinfo_desc = {
99 "sys.floatinfo", /* name */
100 floatinfo__doc__, /* doc */
101 floatinfo_fields, /* fields */
102 11
103};
104
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000105PyObject *
106PyFloat_GetInfo(void)
107{
Christian Heimesc94e2b52008-01-14 04:13:37 +0000108 static PyObject* floatinfo;
109 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000110
Christian Heimesc94e2b52008-01-14 04:13:37 +0000111 if (floatinfo != NULL) {
112 Py_INCREF(floatinfo);
113 return floatinfo;
114 }
115 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
116
117 floatinfo = PyStructSequence_New(&FloatInfoType);
118 if (floatinfo == NULL) {
119 return NULL;
120 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000121
Christian Heimesc94e2b52008-01-14 04:13:37 +0000122#define SetIntFlag(flag) \
123 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
124#define SetDblFlag(flag) \
125 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000126
Christian Heimesc94e2b52008-01-14 04:13:37 +0000127 SetDblFlag(DBL_MAX);
128 SetIntFlag(DBL_MAX_EXP);
129 SetIntFlag(DBL_MAX_10_EXP);
130 SetDblFlag(DBL_MIN);
131 SetIntFlag(DBL_MIN_EXP);
132 SetIntFlag(DBL_MIN_10_EXP);
133 SetIntFlag(DBL_DIG);
134 SetIntFlag(DBL_MANT_DIG);
135 SetDblFlag(DBL_EPSILON);
136 SetIntFlag(FLT_RADIX);
137 SetIntFlag(FLT_ROUNDS);
138#undef SetIntFlag
139#undef SetDblFlag
140
141 if (PyErr_Occurred()) {
142 Py_CLEAR(floatinfo);
143 return NULL;
144 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000145
Christian Heimesc94e2b52008-01-14 04:13:37 +0000146 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000147}
148
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000152 register PyFloatObject *op;
153 if (free_list == NULL) {
154 if ((free_list = fill_free_list()) == NULL)
155 return NULL;
156 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000157 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000158 op = free_list;
Christian Heimese93237d2007-12-19 02:37:44 +0000159 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000160 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000161 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Tim Petersef14d732000-09-23 03:39:17 +0000165/**************************************************************************
166RED_FLAG 22-Sep-2000 tim
167PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
168
1691. If v was a regular string, *pend was set to point to its terminating
170 null byte. That's useless (the caller can find that without any
171 help from this function!).
172
1732. If v was a Unicode string, or an object convertible to a character
174 buffer, *pend was set to point into stack trash (the auto temp
175 vector holding the character buffer). That was downright dangerous.
176
177Since we can't change the interface of a public API function, pend is
178still supported but now *officially* useless: if pend is not NULL,
179*pend is set to NULL.
180**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000182PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000183{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000184 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000185 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000186 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000187#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000188 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000189#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000190 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000191
Tim Petersef14d732000-09-23 03:39:17 +0000192 if (pend)
193 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000194 if (PyString_Check(v)) {
195 s = PyString_AS_STRING(v);
196 len = PyString_GET_SIZE(v);
197 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000198#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000200 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000201 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000202 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000203 return NULL;
204 }
Tim Petersef14d732000-09-23 03:39:17 +0000205 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000206 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000207 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000208 NULL))
209 return NULL;
210 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000211 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000212 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000213#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000214 else if (PyObject_AsCharBuffer(v, &s, &len)) {
215 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000216 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000218 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000219
Guido van Rossum4c08d552000-03-10 22:55:18 +0000220 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000221 while (*s && isspace(Py_CHARMASK(*s)))
222 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000223 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000224 PyErr_SetString(PyExc_ValueError, "empty string for float()");
225 return NULL;
226 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000227 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000228 /* We don't care about overflow or underflow. If the platform supports
229 * them, infinities and signed zeroes (on underflow) are fine.
230 * However, strtod can return 0 for denormalized numbers, where atof
231 * does not. So (alas!) we special-case a zero result. Note that
232 * whether strtod sets errno on underflow is not defined, so we can't
233 * key off errno.
234 */
Tim Peters858346e2000-09-25 21:01:28 +0000235 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000236 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000237 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000238 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000239 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000240 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000241 if (end > last)
242 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000243 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000244 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000245 char *p = (char*)sp;
246 int sign = 1;
247
248 if (*p == '-') {
249 sign = -1;
250 p++;
251 }
252 if (*p == '+') {
253 p++;
254 }
255 if (PyOS_strnicmp(p, "inf", 4) == 0) {
256 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
257 }
258#ifdef Py_NAN
259 if(PyOS_strnicmp(p, "nan", 4) == 0) {
260 return PyFloat_FromDouble(Py_NAN);
261 }
262#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000263 PyOS_snprintf(buffer, sizeof(buffer),
264 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000265 PyErr_SetString(PyExc_ValueError, buffer);
266 return NULL;
267 }
268 /* Since end != s, the platform made *some* kind of sense out
269 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000270 while (*end && isspace(Py_CHARMASK(*end)))
271 end++;
272 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000273 PyOS_snprintf(buffer, sizeof(buffer),
274 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000275 PyErr_SetString(PyExc_ValueError, buffer);
276 return NULL;
277 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000278 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000279 PyErr_SetString(PyExc_ValueError,
280 "null byte in argument for float()");
281 return NULL;
282 }
Tim Petersef14d732000-09-23 03:39:17 +0000283 if (x == 0.0) {
284 /* See above -- may have been strtod being anal
285 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000286 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000287 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000288 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000289 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000290 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000291 return PyFloat_FromDouble(x);
292}
293
Guido van Rossum234f9421993-06-17 12:35:49 +0000294static void
Fred Drakefd99de62000-07-09 05:02:18 +0000295float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000296{
Guido van Rossum9475a232001-10-05 20:51:39 +0000297 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000298 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000299 free_list = op;
300 }
301 else
Christian Heimese93237d2007-12-19 02:37:44 +0000302 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000303}
304
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305double
Fred Drakefd99de62000-07-09 05:02:18 +0000306PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 PyNumberMethods *nb;
309 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 if (op && PyFloat_Check(op))
313 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000314
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000315 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000316 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317 return -1;
318 }
Tim Petersd2364e82001-11-01 20:09:42 +0000319
Christian Heimese93237d2007-12-19 02:37:44 +0000320 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000321 PyErr_SetString(PyExc_TypeError, "a float is required");
322 return -1;
323 }
324
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000325 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000326 if (fo == NULL)
327 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 if (!PyFloat_Check(fo)) {
329 PyErr_SetString(PyExc_TypeError,
330 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000331 return -1;
332 }
Tim Petersd2364e82001-11-01 20:09:42 +0000333
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000334 val = PyFloat_AS_DOUBLE(fo);
335 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000336
Guido van Rossumb6775db1994-08-01 11:34:53 +0000337 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338}
339
340/* Methods */
341
Tim Peters97019e42001-11-28 22:43:45 +0000342static void
343format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344{
345 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000346 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000347 int i;
348
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349 /* Subroutine for float_repr and float_print.
350 We want float numbers to be recognizable as such,
351 i.e., they should contain a decimal point or an exponent.
352 However, %g may print the number as an integer;
353 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000354
355 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000356 PyOS_snprintf(format, 32, "%%.%ig", precision);
357 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358 cp = buf;
359 if (*cp == '-')
360 cp++;
361 for (; *cp != '\0'; cp++) {
362 /* Any non-digit means it's not an integer;
363 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000364 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365 break;
366 }
367 if (*cp == '\0') {
368 *cp++ = '.';
369 *cp++ = '0';
370 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000371 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000373 /* Checking the next three chars should be more than enough to
374 * detect inf or nan, even on Windows. We check for inf or nan
375 * at last because they are rare cases.
376 */
377 for (i=0; *cp != '\0' && i<3; cp++, i++) {
378 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
379 continue;
380 /* found something that is neither a digit nor point
381 * it might be a NaN or INF
382 */
383#ifdef Py_NAN
384 if (Py_IS_NAN(v->ob_fval)) {
385 strcpy(buf, "nan");
386 }
387 else
388#endif
389 if (Py_IS_INFINITY(v->ob_fval)) {
390 cp = buf;
391 if (*cp == '-')
392 cp++;
393 strcpy(cp, "inf");
394 }
395 break;
396 }
397
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Tim Peters97019e42001-11-28 22:43:45 +0000400/* XXX PyFloat_AsStringEx should not be a public API function (for one
401 XXX thing, its signature passes a buffer without a length; for another,
402 XXX it isn't useful outside this file).
403*/
404void
405PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
406{
407 format_float(buf, 100, v, precision);
408}
409
Christian Heimesf15c66e2007-12-11 00:54:34 +0000410#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000411/* The following function is based on Tcl_PrintDouble,
412 * from tclUtil.c.
413 */
414
415#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
416#define is_nan(d) ((d) != (d))
417
418static void
419format_double_repr(char *dst, double value)
420{
421 char *p, c;
422 int exp;
423 int signum;
424 char buffer[30];
425
426 /*
427 * Handle NaN.
428 */
429
430 if (is_nan(value)) {
431 strcpy(dst, "nan");
432 return;
433 }
434
435 /*
436 * Handle infinities.
437 */
438
439 if (is_infinite(value)) {
440 if (value < 0) {
441 strcpy(dst, "-inf");
442 } else {
443 strcpy(dst, "inf");
444 }
445 return;
446 }
447
448 /*
449 * Ordinary (normal and denormal) values.
450 */
451
452 exp = _PyFloat_Digits(buffer, value, &signum)+1;
453 if (signum) {
454 *dst++ = '-';
455 }
456 p = buffer;
457 if (exp < -3 || exp > 17) {
458 /*
459 * E format for numbers < 1e-3 or >= 1e17.
460 */
461
462 *dst++ = *p++;
463 c = *p;
464 if (c != '\0') {
465 *dst++ = '.';
466 while (c != '\0') {
467 *dst++ = c;
468 c = *++p;
469 }
470 }
471 sprintf(dst, "e%+d", exp-1);
472 } else {
473 /*
474 * F format for others.
475 */
476
477 if (exp <= 0) {
478 *dst++ = '0';
479 }
480 c = *p;
481 while (exp-- > 0) {
482 if (c != '\0') {
483 *dst++ = c;
484 c = *++p;
485 } else {
486 *dst++ = '0';
487 }
488 }
489 *dst++ = '.';
490 if (c == '\0') {
491 *dst++ = '0';
492 } else {
493 while (++exp < 0) {
494 *dst++ = '0';
495 }
496 while (c != '\0') {
497 *dst++ = c;
498 c = *++p;
499 }
500 }
501 *dst++ = '\0';
502 }
503}
504
505static void
506format_float_repr(char *buf, PyFloatObject *v)
507{
508 assert(PyFloat_Check(v));
509 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
510}
511
Christian Heimesf15c66e2007-12-11 00:54:34 +0000512#endif /* Py_BROKEN_REPR */
513
Neil Schemenauer32117e52001-01-04 01:44:34 +0000514/* Macro and helper that convert PyObject obj to a C double and store
515 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000516 slot function. If conversion to double raises an exception, obj is
517 set to NULL, and the function invoking this macro returns NULL. If
518 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
519 stored in obj, and returned from the function invoking this macro.
520*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000521#define CONVERT_TO_DOUBLE(obj, dbl) \
522 if (PyFloat_Check(obj)) \
523 dbl = PyFloat_AS_DOUBLE(obj); \
524 else if (convert_to_double(&(obj), &(dbl)) < 0) \
525 return obj;
526
527static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000528convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000529{
530 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000531
Neil Schemenauer32117e52001-01-04 01:44:34 +0000532 if (PyInt_Check(obj)) {
533 *dbl = (double)PyInt_AS_LONG(obj);
534 }
535 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000536 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000537 if (*dbl == -1.0 && PyErr_Occurred()) {
538 *v = NULL;
539 return -1;
540 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000541 }
542 else {
543 Py_INCREF(Py_NotImplemented);
544 *v = Py_NotImplemented;
545 return -1;
546 }
547 return 0;
548}
549
Guido van Rossum57072eb1999-12-23 19:00:28 +0000550/* Precisions used by repr() and str(), respectively.
551
552 The repr() precision (17 significant decimal digits) is the minimal number
553 that is guaranteed to have enough precision so that if the number is read
554 back in the exact same binary value is recreated. This is true for IEEE
555 floating point by design, and also happens to work for all other modern
556 hardware.
557
558 The str() precision is chosen so that in most cases, the rounding noise
559 created by various operations is suppressed, while giving plenty of
560 precision for practical use.
561
562*/
563
564#define PREC_REPR 17
565#define PREC_STR 12
566
Tim Peters97019e42001-11-28 22:43:45 +0000567/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
568 XXX they pass a char buffer without passing a length.
569*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000570void
Fred Drakefd99de62000-07-09 05:02:18 +0000571PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000572{
Tim Peters97019e42001-11-28 22:43:45 +0000573 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000574}
575
Tim Peters72f98e92001-05-08 15:19:57 +0000576void
577PyFloat_AsReprString(char *buf, PyFloatObject *v)
578{
Tim Peters97019e42001-11-28 22:43:45 +0000579 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000580}
581
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000582/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000583static int
Fred Drakefd99de62000-07-09 05:02:18 +0000584float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
586 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000587 format_float(buf, sizeof(buf), v,
588 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000589 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000591 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000592 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593}
594
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000595static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000596float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000598#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000599 char buf[30];
600 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000601#else
602 char buf[100];
603 format_float(buf, sizeof(buf), v, PREC_REPR);
604#endif
605
Guido van Rossum57072eb1999-12-23 19:00:28 +0000606 return PyString_FromString(buf);
607}
608
609static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000610float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000611{
612 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000613 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000615}
616
Tim Peters307fa782004-09-23 08:06:40 +0000617/* Comparison is pretty much a nightmare. When comparing float to float,
618 * we do it as straightforwardly (and long-windedly) as conceivable, so
619 * that, e.g., Python x == y delivers the same result as the platform
620 * C x == y when x and/or y is a NaN.
621 * When mixing float with an integer type, there's no good *uniform* approach.
622 * Converting the double to an integer obviously doesn't work, since we
623 * may lose info from fractional bits. Converting the integer to a double
624 * also has two failure modes: (1) a long int may trigger overflow (too
625 * large to fit in the dynamic range of a C double); (2) even a C long may have
626 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
627 * 63 bits of precision, but a C double probably has only 53), and then
628 * we can falsely claim equality when low-order integer bits are lost by
629 * coercion to double. So this part is painful too.
630 */
631
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000632static PyObject*
633float_richcompare(PyObject *v, PyObject *w, int op)
634{
635 double i, j;
636 int r = 0;
637
Tim Peters307fa782004-09-23 08:06:40 +0000638 assert(PyFloat_Check(v));
639 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000640
Tim Peters307fa782004-09-23 08:06:40 +0000641 /* Switch on the type of w. Set i and j to doubles to be compared,
642 * and op to the richcomp to use.
643 */
644 if (PyFloat_Check(w))
645 j = PyFloat_AS_DOUBLE(w);
646
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000647 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000648 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000649 /* If i is an infinity, its magnitude exceeds any
650 * finite integer, so it doesn't matter which int we
651 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000652 */
653 j = 0.0;
654 else
655 goto Unimplemented;
656 }
657
658 else if (PyInt_Check(w)) {
659 long jj = PyInt_AS_LONG(w);
660 /* In the worst realistic case I can imagine, C double is a
661 * Cray single with 48 bits of precision, and long has 64
662 * bits.
663 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000664#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000665 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
666 if (abs >> 48) {
667 /* Needs more than 48 bits. Make it take the
668 * PyLong path.
669 */
670 PyObject *result;
671 PyObject *ww = PyLong_FromLong(jj);
672
673 if (ww == NULL)
674 return NULL;
675 result = float_richcompare(v, ww, op);
676 Py_DECREF(ww);
677 return result;
678 }
679#endif
680 j = (double)jj;
681 assert((long)j == jj);
682 }
683
684 else if (PyLong_Check(w)) {
685 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
686 int wsign = _PyLong_Sign(w);
687 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000688 int exponent;
689
690 if (vsign != wsign) {
691 /* Magnitudes are irrelevant -- the signs alone
692 * determine the outcome.
693 */
694 i = (double)vsign;
695 j = (double)wsign;
696 goto Compare;
697 }
698 /* The signs are the same. */
699 /* Convert w to a double if it fits. In particular, 0 fits. */
700 nbits = _PyLong_NumBits(w);
701 if (nbits == (size_t)-1 && PyErr_Occurred()) {
702 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000703 * to hold the # of bits. Replace with little doubles
704 * that give the same outcome -- w is so large that
705 * its magnitude must exceed the magnitude of any
706 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000707 */
708 PyErr_Clear();
709 i = (double)vsign;
710 assert(wsign != 0);
711 j = wsign * 2.0;
712 goto Compare;
713 }
714 if (nbits <= 48) {
715 j = PyLong_AsDouble(w);
716 /* It's impossible that <= 48 bits overflowed. */
717 assert(j != -1.0 || ! PyErr_Occurred());
718 goto Compare;
719 }
720 assert(wsign != 0); /* else nbits was 0 */
721 assert(vsign != 0); /* if vsign were 0, then since wsign is
722 * not 0, we would have taken the
723 * vsign != wsign branch at the start */
724 /* We want to work with non-negative numbers. */
725 if (vsign < 0) {
726 /* "Multiply both sides" by -1; this also swaps the
727 * comparator.
728 */
729 i = -i;
730 op = _Py_SwappedOp[op];
731 }
732 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000733 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000734 /* exponent is the # of bits in v before the radix point;
735 * we know that nbits (the # of bits in w) > 48 at this point
736 */
737 if (exponent < 0 || (size_t)exponent < nbits) {
738 i = 1.0;
739 j = 2.0;
740 goto Compare;
741 }
742 if ((size_t)exponent > nbits) {
743 i = 2.0;
744 j = 1.0;
745 goto Compare;
746 }
747 /* v and w have the same number of bits before the radix
748 * point. Construct two longs that have the same comparison
749 * outcome.
750 */
751 {
752 double fracpart;
753 double intpart;
754 PyObject *result = NULL;
755 PyObject *one = NULL;
756 PyObject *vv = NULL;
757 PyObject *ww = w;
758
759 if (wsign < 0) {
760 ww = PyNumber_Negative(w);
761 if (ww == NULL)
762 goto Error;
763 }
764 else
765 Py_INCREF(ww);
766
767 fracpart = modf(i, &intpart);
768 vv = PyLong_FromDouble(intpart);
769 if (vv == NULL)
770 goto Error;
771
772 if (fracpart != 0.0) {
773 /* Shift left, and or a 1 bit into vv
774 * to represent the lost fraction.
775 */
776 PyObject *temp;
777
778 one = PyInt_FromLong(1);
779 if (one == NULL)
780 goto Error;
781
782 temp = PyNumber_Lshift(ww, one);
783 if (temp == NULL)
784 goto Error;
785 Py_DECREF(ww);
786 ww = temp;
787
788 temp = PyNumber_Lshift(vv, one);
789 if (temp == NULL)
790 goto Error;
791 Py_DECREF(vv);
792 vv = temp;
793
794 temp = PyNumber_Or(vv, one);
795 if (temp == NULL)
796 goto Error;
797 Py_DECREF(vv);
798 vv = temp;
799 }
800
801 r = PyObject_RichCompareBool(vv, ww, op);
802 if (r < 0)
803 goto Error;
804 result = PyBool_FromLong(r);
805 Error:
806 Py_XDECREF(vv);
807 Py_XDECREF(ww);
808 Py_XDECREF(one);
809 return result;
810 }
811 } /* else if (PyLong_Check(w)) */
812
813 else /* w isn't float, int, or long */
814 goto Unimplemented;
815
816 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000817 PyFPE_START_PROTECT("richcompare", return NULL)
818 switch (op) {
819 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000820 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000821 break;
822 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000823 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000824 break;
825 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000826 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000827 break;
828 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000829 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000830 break;
831 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000832 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000833 break;
834 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000835 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000836 break;
837 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000838 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000839 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000840
841 Unimplemented:
842 Py_INCREF(Py_NotImplemented);
843 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000844}
845
Guido van Rossum9bfef441993-03-29 10:43:31 +0000846static long
Fred Drakefd99de62000-07-09 05:02:18 +0000847float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000848{
Tim Peters39dce292000-08-15 03:34:48 +0000849 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000850}
851
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000852static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000853float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000854{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000855 double a,b;
856 CONVERT_TO_DOUBLE(v, a);
857 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000858 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000859 a = a + b;
860 PyFPE_END_PROTECT(a)
861 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000862}
863
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000864static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000865float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000866{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000867 double a,b;
868 CONVERT_TO_DOUBLE(v, a);
869 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000870 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000871 a = a - b;
872 PyFPE_END_PROTECT(a)
873 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000874}
875
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000877float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000878{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000879 double a,b;
880 CONVERT_TO_DOUBLE(v, a);
881 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000882 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000883 a = a * b;
884 PyFPE_END_PROTECT(a)
885 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000886}
887
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000888static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000889float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000890{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000891 double a,b;
892 CONVERT_TO_DOUBLE(v, a);
893 CONVERT_TO_DOUBLE(w, b);
894 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000895 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000896 return NULL;
897 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000898 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000899 a = a / b;
900 PyFPE_END_PROTECT(a)
901 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000902}
903
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000904static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000905float_classic_div(PyObject *v, PyObject *w)
906{
907 double a,b;
908 CONVERT_TO_DOUBLE(v, a);
909 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000910 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000911 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
912 return NULL;
913 if (b == 0.0) {
914 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
915 return NULL;
916 }
917 PyFPE_START_PROTECT("divide", return 0)
918 a = a / b;
919 PyFPE_END_PROTECT(a)
920 return PyFloat_FromDouble(a);
921}
922
923static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000924float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000925{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000926 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000927 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000928 CONVERT_TO_DOUBLE(v, vx);
929 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000930 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000932 return NULL;
933 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000934 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000935 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000936 /* note: checking mod*wx < 0 is incorrect -- underflows to
937 0 if wx < sqrt(smallest nonzero double) */
938 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000939 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000940 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000941 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000942 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000943}
944
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000945static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000946float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000947{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000948 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000949 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000950 CONVERT_TO_DOUBLE(v, vx);
951 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000952 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000953 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000954 return NULL;
955 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000956 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000957 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000958 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000959 exact multiple of wx. But this is fp arithmetic, and fp
960 vx - mod is an approximation; the result is that div may
961 not be an exact integral value after the division, although
962 it will always be very close to one.
963 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000964 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000965 if (mod) {
966 /* ensure the remainder has the same sign as the denominator */
967 if ((wx < 0) != (mod < 0)) {
968 mod += wx;
969 div -= 1.0;
970 }
971 }
972 else {
973 /* the remainder is zero, and in the presence of signed zeroes
974 fmod returns different results across platforms; ensure
975 it has the same sign as the denominator; we'd like to do
976 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000977 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000978 if (wx < 0.0)
979 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000980 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000981 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000982 if (div) {
983 floordiv = floor(div);
984 if (div - floordiv > 0.5)
985 floordiv += 1.0;
986 }
987 else {
988 /* div is zero - get the same sign as the true quotient */
989 div *= div; /* hide "div = +0" from optimizers */
990 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
991 }
992 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000993 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000994}
995
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000997float_floor_div(PyObject *v, PyObject *w)
998{
999 PyObject *t, *r;
1000
1001 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +00001002 if (t == NULL || t == Py_NotImplemented)
1003 return t;
1004 assert(PyTuple_CheckExact(t));
1005 r = PyTuple_GET_ITEM(t, 0);
1006 Py_INCREF(r);
1007 Py_DECREF(t);
1008 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001009}
1010
1011static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001012float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001013{
1014 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001015
1016 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001017 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001018 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001019 return NULL;
1020 }
1021
Neil Schemenauer32117e52001-01-04 01:44:34 +00001022 CONVERT_TO_DOUBLE(v, iv);
1023 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001024
1025 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001026 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001027 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001028 }
Tim Peters96685bf2001-08-23 22:31:37 +00001029 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001030 if (iw < 0.0) {
1031 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001032 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001033 return NULL;
1034 }
1035 return PyFloat_FromDouble(0.0);
1036 }
Tim Peterse87568d2003-05-24 20:18:24 +00001037 if (iv < 0.0) {
1038 /* Whether this is an error is a mess, and bumps into libm
1039 * bugs so we have to figure it out ourselves.
1040 */
1041 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001042 PyErr_SetString(PyExc_ValueError, "negative number "
1043 "cannot be raised to a fractional power");
1044 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001045 }
1046 /* iw is an exact integer, albeit perhaps a very large one.
1047 * -1 raised to an exact integer should never be exceptional.
1048 * Alas, some libms (chiefly glibc as of early 2003) return
1049 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1050 * happen to be representable in a *C* integer. That's a
1051 * bug; we let that slide in math.pow() (which currently
1052 * reflects all platform accidents), but not for Python's **.
1053 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001054 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001055 /* Return 1 if iw is even, -1 if iw is odd; there's
1056 * no guarantee that any C integral type is big
1057 * enough to hold iw, so we have to check this
1058 * indirectly.
1059 */
1060 ix = floor(iw * 0.5) * 2.0;
1061 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1062 }
1063 /* Else iv != -1.0, and overflow or underflow are possible.
1064 * Unless we're to write pow() ourselves, we have to trust
1065 * the platform to do this correctly.
1066 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001067 }
Tim Peters96685bf2001-08-23 22:31:37 +00001068 errno = 0;
1069 PyFPE_START_PROTECT("pow", return NULL)
1070 ix = pow(iv, iw);
1071 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001072 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001073 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001074 /* We don't expect any errno value other than ERANGE, but
1075 * the range of libm bugs appears unbounded.
1076 */
Alex Martelli348dc882006-08-23 22:17:59 +00001077 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1078 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001079 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001080 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001081 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001082}
1083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001084static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001085float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001086{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001087 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001088}
1089
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001090static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001091float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001092{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001093 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001094}
1095
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001096static int
Fred Drakefd99de62000-07-09 05:02:18 +00001097float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001098{
1099 return v->ob_fval != 0.0;
1100}
1101
Guido van Rossum234f9421993-06-17 12:35:49 +00001102static int
Fred Drakefd99de62000-07-09 05:02:18 +00001103float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001104{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001105 if (PyInt_Check(*pw)) {
1106 long x = PyInt_AsLong(*pw);
1107 *pw = PyFloat_FromDouble((double)x);
1108 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001109 return 0;
1110 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001111 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001112 double x = PyLong_AsDouble(*pw);
1113 if (x == -1.0 && PyErr_Occurred())
1114 return -1;
1115 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001116 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001117 return 0;
1118 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001119 else if (PyFloat_Check(*pw)) {
1120 Py_INCREF(*pv);
1121 Py_INCREF(*pw);
1122 return 0;
1123 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001124 return 1; /* Can't do it */
1125}
1126
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001127static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001128float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001129{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001130 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001131 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001132
1133 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001134 /* Try to get out cheap if this fits in a Python int. The attempt
1135 * to cast to long must be protected, as C doesn't define what
1136 * happens if the double is too big to fit in a long. Some rare
1137 * systems raise an exception then (RISCOS was mentioned as one,
1138 * and someone using a non-default option on Sun also bumped into
1139 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1140 * still be vulnerable: if a long has more bits of precision than
1141 * a double, casting MIN/MAX to double may yield an approximation,
1142 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1143 * yield true from the C expression wholepart<=LONG_MAX, despite
1144 * that wholepart is actually greater than LONG_MAX.
1145 */
1146 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1147 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001148 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001149 }
1150 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001151}
1152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001153static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001154float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001155{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001156 if (PyFloat_CheckExact(v))
1157 Py_INCREF(v);
1158 else
1159 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001160 return v;
1161}
1162
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001163static PyObject *
1164float_as_integer_ratio(PyObject *v)
1165{
1166 double self;
1167 double float_part;
1168 int exponent;
1169 int is_negative;
1170 const int chunk_size = 28;
1171 PyObject *prev;
1172 PyObject *py_chunk = NULL;
1173 PyObject *py_exponent = NULL;
1174 PyObject *numerator = NULL;
1175 PyObject *denominator = NULL;
1176 PyObject *result_pair = NULL;
1177 PyNumberMethods *long_methods;
1178
1179#define INPLACE_UPDATE(obj, call) \
1180 prev = obj; \
1181 obj = call; \
1182 Py_DECREF(prev); \
1183
1184 CONVERT_TO_DOUBLE(v, self);
1185
1186 if (Py_IS_INFINITY(self)) {
1187 PyErr_SetString(PyExc_OverflowError,
1188 "Cannot pass infinity to float.as_integer_ratio.");
1189 return NULL;
1190 }
1191#ifdef Py_NAN
1192 if (Py_IS_NAN(self)) {
1193 PyErr_SetString(PyExc_ValueError,
1194 "Cannot pass nan to float.as_integer_ratio.");
1195 return NULL;
1196 }
1197#endif
1198
1199 if (self == 0) {
1200 numerator = PyInt_FromLong(0);
1201 if (numerator == NULL) goto error;
1202 denominator = PyInt_FromLong(1);
1203 if (denominator == NULL) goto error;
1204 result_pair = PyTuple_Pack(2, numerator, denominator);
1205 /* Hand ownership over to the tuple. If the tuple
1206 wasn't created successfully, we want to delete the
1207 ints anyway. */
1208 Py_DECREF(numerator);
1209 Py_DECREF(denominator);
1210 return result_pair;
1211 }
1212
1213 /* XXX: Could perhaps handle FLT_RADIX!=2 by using ilogb and
1214 scalbn, but those may not be in C89. */
1215 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1216 float_part = frexp(self, &exponent);
1217 is_negative = 0;
1218 if (float_part < 0) {
1219 float_part = -float_part;
1220 is_negative = 1;
1221 /* 0.5 <= float_part < 1.0 */
1222 }
1223 PyFPE_END_PROTECT(float_part);
1224 /* abs(self) == float_part * 2**exponent exactly */
1225
1226 /* Suck up chunk_size bits at a time; 28 is enough so that we
1227 suck up all bits in 2 iterations for all known binary
1228 double-precision formats, and small enough to fit in a
1229 long. */
1230 numerator = PyLong_FromLong(0);
1231 if (numerator == NULL) goto error;
1232
1233 long_methods = PyLong_Type.tp_as_number;
1234
1235 py_chunk = PyLong_FromLong(chunk_size);
1236 if (py_chunk == NULL) goto error;
1237
1238 while (float_part != 0) {
1239 /* invariant: abs(self) ==
1240 (numerator + float_part) * 2**exponent exactly */
1241 long digit;
1242 PyObject *py_digit;
1243
1244 PyFPE_START_PROTECT("as_integer_ratio", goto error);
1245 /* Pull chunk_size bits out of float_part, into digits. */
1246 float_part = ldexp(float_part, chunk_size);
1247 digit = (long)float_part;
1248 float_part -= digit;
1249 /* 0 <= float_part < 1 */
1250 exponent -= chunk_size;
1251 PyFPE_END_PROTECT(float_part);
1252
1253 /* Shift digits into numerator. */
1254 // numerator <<= chunk_size
1255 INPLACE_UPDATE(numerator,
1256 long_methods->nb_lshift(numerator, py_chunk));
1257 if (numerator == NULL) goto error;
1258
1259 // numerator |= digit
1260 py_digit = PyLong_FromLong(digit);
1261 if (py_digit == NULL) goto error;
1262 INPLACE_UPDATE(numerator,
1263 long_methods->nb_or(numerator, py_digit));
1264 Py_DECREF(py_digit);
1265 if (numerator == NULL) goto error;
1266 }
1267
1268 /* Add in the sign bit. */
1269 if (is_negative) {
1270 INPLACE_UPDATE(numerator,
1271 long_methods->nb_negative(numerator));
1272 if (numerator == NULL) goto error;
1273 }
1274
1275 /* now self = numerator * 2**exponent exactly; fold in 2**exponent */
1276 denominator = PyLong_FromLong(1);
1277 py_exponent = PyLong_FromLong(labs(exponent));
1278 if (py_exponent == NULL) goto error;
1279 INPLACE_UPDATE(py_exponent,
1280 long_methods->nb_lshift(denominator, py_exponent));
1281 if (py_exponent == NULL) goto error;
1282 if (exponent > 0) {
1283 INPLACE_UPDATE(numerator,
1284 long_methods->nb_multiply(numerator,
1285 py_exponent));
1286 if (numerator == NULL) goto error;
1287 }
1288 else {
1289 Py_DECREF(denominator);
1290 denominator = py_exponent;
1291 py_exponent = NULL;
1292 }
1293
1294 result_pair = PyTuple_Pack(2, numerator, denominator);
1295
1296#undef INPLACE_UPDATE
1297error:
1298 Py_XDECREF(py_exponent);
1299 Py_XDECREF(py_chunk);
1300 Py_XDECREF(denominator);
1301 Py_XDECREF(numerator);
1302 return result_pair;
1303}
1304
1305PyDoc_STRVAR(float_as_integer_ratio_doc,
1306"float.as_integer_ratio() -> (int, int)\n"
1307"\n"
1308"Returns a pair of integers, not necessarily in lowest terms, whose\n"
1309"ratio is exactly equal to the original float. This method raises an\n"
1310"OverflowError on infinities and a ValueError on nans. The resulting\n"
1311"denominator will be positive.\n"
1312"\n"
1313">>> (10.0).as_integer_ratio()\n"
1314"(167772160L, 16777216L)\n"
1315">>> (0.0).as_integer_ratio()\n"
1316"(0, 1)\n"
1317">>> (-.25).as_integer_ratio()\n"
1318"(-134217728L, 536870912L)");
1319
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001320
Jeremy Hylton938ace62002-07-17 16:30:39 +00001321static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001322float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1323
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324static PyObject *
1325float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1326{
1327 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001328 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329
Guido van Rossumbef14172001-08-29 15:47:46 +00001330 if (type != &PyFloat_Type)
1331 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1333 return NULL;
1334 if (PyString_Check(x))
1335 return PyFloat_FromString(x, NULL);
1336 return PyNumber_Float(x);
1337}
1338
Guido van Rossumbef14172001-08-29 15:47:46 +00001339/* Wimpy, slow approach to tp_new calls for subtypes of float:
1340 first create a regular float from whatever arguments we got,
1341 then allocate a subtype instance and initialize its ob_fval
1342 from the regular float. The regular float is then thrown away.
1343*/
1344static PyObject *
1345float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1346{
Anthony Baxter377be112006-04-11 06:54:30 +00001347 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001348
1349 assert(PyType_IsSubtype(type, &PyFloat_Type));
1350 tmp = float_new(&PyFloat_Type, args, kwds);
1351 if (tmp == NULL)
1352 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001353 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001354 newobj = type->tp_alloc(type, 0);
1355 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001356 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001357 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001358 }
Anthony Baxter377be112006-04-11 06:54:30 +00001359 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001360 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001361 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001362}
1363
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001364static PyObject *
1365float_getnewargs(PyFloatObject *v)
1366{
1367 return Py_BuildValue("(d)", v->ob_fval);
1368}
1369
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001370/* this is for the benefit of the pack/unpack routines below */
1371
1372typedef enum {
1373 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1374} float_format_type;
1375
1376static float_format_type double_format, float_format;
1377static float_format_type detected_double_format, detected_float_format;
1378
1379static PyObject *
1380float_getformat(PyTypeObject *v, PyObject* arg)
1381{
1382 char* s;
1383 float_format_type r;
1384
1385 if (!PyString_Check(arg)) {
1386 PyErr_Format(PyExc_TypeError,
1387 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001388 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001389 return NULL;
1390 }
1391 s = PyString_AS_STRING(arg);
1392 if (strcmp(s, "double") == 0) {
1393 r = double_format;
1394 }
1395 else if (strcmp(s, "float") == 0) {
1396 r = float_format;
1397 }
1398 else {
1399 PyErr_SetString(PyExc_ValueError,
1400 "__getformat__() argument 1 must be "
1401 "'double' or 'float'");
1402 return NULL;
1403 }
1404
1405 switch (r) {
1406 case unknown_format:
1407 return PyString_FromString("unknown");
1408 case ieee_little_endian_format:
1409 return PyString_FromString("IEEE, little-endian");
1410 case ieee_big_endian_format:
1411 return PyString_FromString("IEEE, big-endian");
1412 default:
1413 Py_FatalError("insane float_format or double_format");
1414 return NULL;
1415 }
1416}
1417
1418PyDoc_STRVAR(float_getformat_doc,
1419"float.__getformat__(typestr) -> string\n"
1420"\n"
1421"You probably don't want to use this function. It exists mainly to be\n"
1422"used in Python's test suite.\n"
1423"\n"
1424"typestr must be 'double' or 'float'. This function returns whichever of\n"
1425"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1426"format of floating point numbers used by the C type named by typestr.");
1427
1428static PyObject *
1429float_setformat(PyTypeObject *v, PyObject* args)
1430{
1431 char* typestr;
1432 char* format;
1433 float_format_type f;
1434 float_format_type detected;
1435 float_format_type *p;
1436
1437 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1438 return NULL;
1439
1440 if (strcmp(typestr, "double") == 0) {
1441 p = &double_format;
1442 detected = detected_double_format;
1443 }
1444 else if (strcmp(typestr, "float") == 0) {
1445 p = &float_format;
1446 detected = detected_float_format;
1447 }
1448 else {
1449 PyErr_SetString(PyExc_ValueError,
1450 "__setformat__() argument 1 must "
1451 "be 'double' or 'float'");
1452 return NULL;
1453 }
1454
1455 if (strcmp(format, "unknown") == 0) {
1456 f = unknown_format;
1457 }
1458 else if (strcmp(format, "IEEE, little-endian") == 0) {
1459 f = ieee_little_endian_format;
1460 }
1461 else if (strcmp(format, "IEEE, big-endian") == 0) {
1462 f = ieee_big_endian_format;
1463 }
1464 else {
1465 PyErr_SetString(PyExc_ValueError,
1466 "__setformat__() argument 2 must be "
1467 "'unknown', 'IEEE, little-endian' or "
1468 "'IEEE, big-endian'");
1469 return NULL;
1470
1471 }
1472
1473 if (f != unknown_format && f != detected) {
1474 PyErr_Format(PyExc_ValueError,
1475 "can only set %s format to 'unknown' or the "
1476 "detected platform value", typestr);
1477 return NULL;
1478 }
1479
1480 *p = f;
1481 Py_RETURN_NONE;
1482}
1483
1484PyDoc_STRVAR(float_setformat_doc,
1485"float.__setformat__(typestr, fmt) -> None\n"
1486"\n"
1487"You probably don't want to use this function. It exists mainly to be\n"
1488"used in Python's test suite.\n"
1489"\n"
1490"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1491"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1492"one of the latter two if it appears to match the underlying C reality.\n"
1493"\n"
1494"Overrides the automatic determination of C-level floating point type.\n"
1495"This affects how floats are converted to and from binary strings.");
1496
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001497static PyObject *
1498float_getzero(PyObject *v, void *closure)
1499{
1500 return PyFloat_FromDouble(0.0);
1501}
1502
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001503static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001504 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1505 "Returns self, the complex conjugate of any float."},
1506 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1507 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001508 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1509 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001510 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001511 {"__getformat__", (PyCFunction)float_getformat,
1512 METH_O|METH_CLASS, float_getformat_doc},
1513 {"__setformat__", (PyCFunction)float_setformat,
1514 METH_VARARGS|METH_CLASS, float_setformat_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001515 {NULL, NULL} /* sentinel */
1516};
1517
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001518static PyGetSetDef float_getset[] = {
1519 {"real",
1520 (getter)float_float, (setter)NULL,
1521 "the real part of a complex number",
1522 NULL},
1523 {"imag",
1524 (getter)float_getzero, (setter)NULL,
1525 "the imaginary part of a complex number",
1526 NULL},
1527 {NULL} /* Sentinel */
1528};
1529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001530PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531"float(x) -> floating point number\n\
1532\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001533Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
1535
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001536static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001537 float_add, /*nb_add*/
1538 float_sub, /*nb_subtract*/
1539 float_mul, /*nb_multiply*/
1540 float_classic_div, /*nb_divide*/
1541 float_rem, /*nb_remainder*/
1542 float_divmod, /*nb_divmod*/
1543 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001544 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001545 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001546 (unaryfunc)float_abs, /*nb_absolute*/
1547 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001548 0, /*nb_invert*/
1549 0, /*nb_lshift*/
1550 0, /*nb_rshift*/
1551 0, /*nb_and*/
1552 0, /*nb_xor*/
1553 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001554 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001555 float_trunc, /*nb_int*/
1556 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001557 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001558 0, /* nb_oct */
1559 0, /* nb_hex */
1560 0, /* nb_inplace_add */
1561 0, /* nb_inplace_subtract */
1562 0, /* nb_inplace_multiply */
1563 0, /* nb_inplace_divide */
1564 0, /* nb_inplace_remainder */
1565 0, /* nb_inplace_power */
1566 0, /* nb_inplace_lshift */
1567 0, /* nb_inplace_rshift */
1568 0, /* nb_inplace_and */
1569 0, /* nb_inplace_xor */
1570 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001571 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001572 float_div, /* nb_true_divide */
1573 0, /* nb_inplace_floor_divide */
1574 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001575};
1576
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001577PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001578 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001579 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001580 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001581 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582 (destructor)float_dealloc, /* tp_dealloc */
1583 (printfunc)float_print, /* tp_print */
1584 0, /* tp_getattr */
1585 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001586 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587 (reprfunc)float_repr, /* tp_repr */
1588 &float_as_number, /* tp_as_number */
1589 0, /* tp_as_sequence */
1590 0, /* tp_as_mapping */
1591 (hashfunc)float_hash, /* tp_hash */
1592 0, /* tp_call */
1593 (reprfunc)float_str, /* tp_str */
1594 PyObject_GenericGetAttr, /* tp_getattro */
1595 0, /* tp_setattro */
1596 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001597 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1598 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599 float_doc, /* tp_doc */
1600 0, /* tp_traverse */
1601 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001602 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 0, /* tp_weaklistoffset */
1604 0, /* tp_iter */
1605 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001606 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001608 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 0, /* tp_base */
1610 0, /* tp_dict */
1611 0, /* tp_descr_get */
1612 0, /* tp_descr_set */
1613 0, /* tp_dictoffset */
1614 0, /* tp_init */
1615 0, /* tp_alloc */
1616 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001617};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001618
1619void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001620_PyFloat_Init(void)
1621{
1622 /* We attempt to determine if this machine is using IEEE
1623 floating point formats by peering at the bits of some
1624 carefully chosen values. If it looks like we are on an
1625 IEEE platform, the float packing/unpacking routines can
1626 just copy bits, if not they resort to arithmetic & shifts
1627 and masks. The shifts & masks approach works on all finite
1628 values, but what happens to infinities, NaNs and signed
1629 zeroes on packing is an accident, and attempting to unpack
1630 a NaN or an infinity will raise an exception.
1631
1632 Note that if we're on some whacked-out platform which uses
1633 IEEE formats but isn't strictly little-endian or big-
1634 endian, we will fall back to the portable shifts & masks
1635 method. */
1636
1637#if SIZEOF_DOUBLE == 8
1638 {
1639 double x = 9006104071832581.0;
1640 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1641 detected_double_format = ieee_big_endian_format;
1642 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1643 detected_double_format = ieee_little_endian_format;
1644 else
1645 detected_double_format = unknown_format;
1646 }
1647#else
1648 detected_double_format = unknown_format;
1649#endif
1650
1651#if SIZEOF_FLOAT == 4
1652 {
1653 float y = 16711938.0;
1654 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1655 detected_float_format = ieee_big_endian_format;
1656 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1657 detected_float_format = ieee_little_endian_format;
1658 else
1659 detected_float_format = unknown_format;
1660 }
1661#else
1662 detected_float_format = unknown_format;
1663#endif
1664
1665 double_format = detected_double_format;
1666 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001667
1668#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001669 /* Initialize floating point repr */
1670 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001671#endif
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001672}
1673
1674void
Fred Drakefd99de62000-07-09 05:02:18 +00001675PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001676{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001677 PyFloatObject *p;
1678 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001679 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001680 int bc, bf; /* block count, number of freed blocks */
1681 int frem, fsum; /* remaining unfreed floats per block, total */
1682
1683 bc = 0;
1684 bf = 0;
1685 fsum = 0;
1686 list = block_list;
1687 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001688 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001689 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001690 bc++;
1691 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001692 for (i = 0, p = &list->objects[0];
1693 i < N_FLOATOBJECTS;
1694 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001695 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001696 frem++;
1697 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001698 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001699 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001700 list->next = block_list;
1701 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001702 for (i = 0, p = &list->objects[0];
1703 i < N_FLOATOBJECTS;
1704 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001705 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001706 Py_REFCNT(p) == 0) {
1707 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001708 free_list;
1709 free_list = p;
1710 }
1711 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001712 }
1713 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001714 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001715 bf++;
1716 }
1717 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001718 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001719 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001720 if (!Py_VerboseFlag)
1721 return;
1722 fprintf(stderr, "# cleanup floats");
1723 if (!fsum) {
1724 fprintf(stderr, "\n");
1725 }
1726 else {
1727 fprintf(stderr,
1728 ": %d unfreed float%s in %d out of %d block%s\n",
1729 fsum, fsum == 1 ? "" : "s",
1730 bc - bf, bc, bc == 1 ? "" : "s");
1731 }
1732 if (Py_VerboseFlag > 1) {
1733 list = block_list;
1734 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001735 for (i = 0, p = &list->objects[0];
1736 i < N_FLOATOBJECTS;
1737 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001738 if (PyFloat_CheckExact(p) &&
Christian Heimese93237d2007-12-19 02:37:44 +00001739 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001740 char buf[100];
1741 PyFloat_AsString(buf, p);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001742 /* XXX(twouters) cast refcount to
1743 long until %zd is universally
1744 available
1745 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001746 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001747 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimese93237d2007-12-19 02:37:44 +00001748 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001749 }
1750 }
1751 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001752 }
1753 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001754}
Tim Peters9905b942003-03-20 20:53:32 +00001755
1756/*----------------------------------------------------------------------------
1757 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
1758 *
1759 * TODO: On platforms that use the standard IEEE-754 single and double
1760 * formats natively, these routines could simply copy the bytes.
1761 */
1762int
1763_PyFloat_Pack4(double x, unsigned char *p, int le)
1764{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001765 if (float_format == unknown_format) {
1766 unsigned char sign;
1767 int e;
1768 double f;
1769 unsigned int fbits;
1770 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001771
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001772 if (le) {
1773 p += 3;
1774 incr = -1;
1775 }
Tim Peters9905b942003-03-20 20:53:32 +00001776
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001777 if (x < 0) {
1778 sign = 1;
1779 x = -x;
1780 }
1781 else
1782 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001783
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001784 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001785
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001786 /* Normalize f to be in the range [1.0, 2.0) */
1787 if (0.5 <= f && f < 1.0) {
1788 f *= 2.0;
1789 e--;
1790 }
1791 else if (f == 0.0)
1792 e = 0;
1793 else {
1794 PyErr_SetString(PyExc_SystemError,
1795 "frexp() result out of range");
1796 return -1;
1797 }
1798
1799 if (e >= 128)
1800 goto Overflow;
1801 else if (e < -126) {
1802 /* Gradual underflow */
1803 f = ldexp(f, 126 + e);
1804 e = 0;
1805 }
1806 else if (!(e == 0 && f == 0.0)) {
1807 e += 127;
1808 f -= 1.0; /* Get rid of leading 1 */
1809 }
1810
1811 f *= 8388608.0; /* 2**23 */
1812 fbits = (unsigned int)(f + 0.5); /* Round */
1813 assert(fbits <= 8388608);
1814 if (fbits >> 23) {
1815 /* The carry propagated out of a string of 23 1 bits. */
1816 fbits = 0;
1817 ++e;
1818 if (e >= 255)
1819 goto Overflow;
1820 }
1821
1822 /* First byte */
1823 *p = (sign << 7) | (e >> 1);
1824 p += incr;
1825
1826 /* Second byte */
1827 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1828 p += incr;
1829
1830 /* Third byte */
1831 *p = (fbits >> 8) & 0xFF;
1832 p += incr;
1833
1834 /* Fourth byte */
1835 *p = fbits & 0xFF;
1836
1837 /* Done */
1838 return 0;
1839
1840 Overflow:
1841 PyErr_SetString(PyExc_OverflowError,
1842 "float too large to pack with f format");
Tim Peters9905b942003-03-20 20:53:32 +00001843 return -1;
1844 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001845 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001846 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001847 const char *s = (char*)&y;
1848 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001849
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001850 if ((float_format == ieee_little_endian_format && !le)
1851 || (float_format == ieee_big_endian_format && le)) {
1852 p += 3;
1853 incr = -1;
1854 }
1855
1856 for (i = 0; i < 4; i++) {
1857 *p = *s++;
1858 p += incr;
1859 }
1860 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001861 }
Tim Peters9905b942003-03-20 20:53:32 +00001862}
1863
1864int
1865_PyFloat_Pack8(double x, unsigned char *p, int le)
1866{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001867 if (double_format == unknown_format) {
1868 unsigned char sign;
1869 int e;
1870 double f;
1871 unsigned int fhi, flo;
1872 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001873
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001874 if (le) {
1875 p += 7;
1876 incr = -1;
1877 }
Tim Peters9905b942003-03-20 20:53:32 +00001878
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001879 if (x < 0) {
1880 sign = 1;
1881 x = -x;
1882 }
1883 else
1884 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001885
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001886 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001887
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001888 /* Normalize f to be in the range [1.0, 2.0) */
1889 if (0.5 <= f && f < 1.0) {
1890 f *= 2.0;
1891 e--;
1892 }
1893 else if (f == 0.0)
1894 e = 0;
1895 else {
1896 PyErr_SetString(PyExc_SystemError,
1897 "frexp() result out of range");
1898 return -1;
1899 }
1900
1901 if (e >= 1024)
1902 goto Overflow;
1903 else if (e < -1022) {
1904 /* Gradual underflow */
1905 f = ldexp(f, 1022 + e);
1906 e = 0;
1907 }
1908 else if (!(e == 0 && f == 0.0)) {
1909 e += 1023;
1910 f -= 1.0; /* Get rid of leading 1 */
1911 }
1912
1913 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1914 f *= 268435456.0; /* 2**28 */
1915 fhi = (unsigned int)f; /* Truncate */
1916 assert(fhi < 268435456);
1917
1918 f -= (double)fhi;
1919 f *= 16777216.0; /* 2**24 */
1920 flo = (unsigned int)(f + 0.5); /* Round */
1921 assert(flo <= 16777216);
1922 if (flo >> 24) {
1923 /* The carry propagated out of a string of 24 1 bits. */
1924 flo = 0;
1925 ++fhi;
1926 if (fhi >> 28) {
1927 /* And it also progagated out of the next 28 bits. */
1928 fhi = 0;
1929 ++e;
1930 if (e >= 2047)
1931 goto Overflow;
1932 }
1933 }
1934
1935 /* First byte */
1936 *p = (sign << 7) | (e >> 4);
1937 p += incr;
1938
1939 /* Second byte */
1940 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1941 p += incr;
1942
1943 /* Third byte */
1944 *p = (fhi >> 16) & 0xFF;
1945 p += incr;
1946
1947 /* Fourth byte */
1948 *p = (fhi >> 8) & 0xFF;
1949 p += incr;
1950
1951 /* Fifth byte */
1952 *p = fhi & 0xFF;
1953 p += incr;
1954
1955 /* Sixth byte */
1956 *p = (flo >> 16) & 0xFF;
1957 p += incr;
1958
1959 /* Seventh byte */
1960 *p = (flo >> 8) & 0xFF;
1961 p += incr;
1962
1963 /* Eighth byte */
1964 *p = flo & 0xFF;
1965 p += incr;
1966
1967 /* Done */
1968 return 0;
1969
1970 Overflow:
1971 PyErr_SetString(PyExc_OverflowError,
1972 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001973 return -1;
1974 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001975 else {
1976 const char *s = (char*)&x;
1977 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001978
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001979 if ((double_format == ieee_little_endian_format && !le)
1980 || (double_format == ieee_big_endian_format && le)) {
1981 p += 7;
1982 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001983 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001984
1985 for (i = 0; i < 8; i++) {
1986 *p = *s++;
1987 p += incr;
1988 }
1989 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001990 }
Tim Peters9905b942003-03-20 20:53:32 +00001991}
1992
1993double
1994_PyFloat_Unpack4(const unsigned char *p, int le)
1995{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001996 if (float_format == unknown_format) {
1997 unsigned char sign;
1998 int e;
1999 unsigned int f;
2000 double x;
2001 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002002
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002003 if (le) {
2004 p += 3;
2005 incr = -1;
2006 }
2007
2008 /* First byte */
2009 sign = (*p >> 7) & 1;
2010 e = (*p & 0x7F) << 1;
2011 p += incr;
2012
2013 /* Second byte */
2014 e |= (*p >> 7) & 1;
2015 f = (*p & 0x7F) << 16;
2016 p += incr;
2017
2018 if (e == 255) {
2019 PyErr_SetString(
2020 PyExc_ValueError,
2021 "can't unpack IEEE 754 special value "
2022 "on non-IEEE platform");
2023 return -1;
2024 }
2025
2026 /* Third byte */
2027 f |= *p << 8;
2028 p += incr;
2029
2030 /* Fourth byte */
2031 f |= *p;
2032
2033 x = (double)f / 8388608.0;
2034
2035 /* XXX This sadly ignores Inf/NaN issues */
2036 if (e == 0)
2037 e = -126;
2038 else {
2039 x += 1.0;
2040 e -= 127;
2041 }
2042 x = ldexp(x, e);
2043
2044 if (sign)
2045 x = -x;
2046
2047 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002048 }
Tim Peters9905b942003-03-20 20:53:32 +00002049 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002050 float x;
2051
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002052 if ((float_format == ieee_little_endian_format && !le)
2053 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002054 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002055 char *d = &buf[3];
2056 int i;
Tim Peters9905b942003-03-20 20:53:32 +00002057
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002058 for (i = 0; i < 4; i++) {
2059 *d-- = *p++;
2060 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002061 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002062 }
2063 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002064 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002065 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002066
2067 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002068 }
Tim Peters9905b942003-03-20 20:53:32 +00002069}
2070
2071double
2072_PyFloat_Unpack8(const unsigned char *p, int le)
2073{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002074 if (double_format == unknown_format) {
2075 unsigned char sign;
2076 int e;
2077 unsigned int fhi, flo;
2078 double x;
2079 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00002080
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002081 if (le) {
2082 p += 7;
2083 incr = -1;
2084 }
2085
2086 /* First byte */
2087 sign = (*p >> 7) & 1;
2088 e = (*p & 0x7F) << 4;
2089
2090 p += incr;
2091
2092 /* Second byte */
2093 e |= (*p >> 4) & 0xF;
2094 fhi = (*p & 0xF) << 24;
2095 p += incr;
2096
2097 if (e == 2047) {
2098 PyErr_SetString(
2099 PyExc_ValueError,
2100 "can't unpack IEEE 754 special value "
2101 "on non-IEEE platform");
2102 return -1.0;
2103 }
2104
2105 /* Third byte */
2106 fhi |= *p << 16;
2107 p += incr;
2108
2109 /* Fourth byte */
2110 fhi |= *p << 8;
2111 p += incr;
2112
2113 /* Fifth byte */
2114 fhi |= *p;
2115 p += incr;
2116
2117 /* Sixth byte */
2118 flo = *p << 16;
2119 p += incr;
2120
2121 /* Seventh byte */
2122 flo |= *p << 8;
2123 p += incr;
2124
2125 /* Eighth byte */
2126 flo |= *p;
2127
2128 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2129 x /= 268435456.0; /* 2**28 */
2130
2131 if (e == 0)
2132 e = -1022;
2133 else {
2134 x += 1.0;
2135 e -= 1023;
2136 }
2137 x = ldexp(x, e);
2138
2139 if (sign)
2140 x = -x;
2141
2142 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002143 }
Tim Peters9905b942003-03-20 20:53:32 +00002144 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002145 double x;
2146
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002147 if ((double_format == ieee_little_endian_format && !le)
2148 || (double_format == ieee_big_endian_format && le)) {
2149 char buf[8];
2150 char *d = &buf[7];
2151 int i;
2152
2153 for (i = 0; i < 8; i++) {
2154 *d-- = *p++;
2155 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002156 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002157 }
2158 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002159 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002160 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002161
2162 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002163 }
Tim Peters9905b942003-03-20 20:53:32 +00002164}